blob: fadb47bccafc9dcf65202dc8c2990efc24cb64f3 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
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 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Steve Anton75737c02017-11-06 10:37:17 -0800603} // namespace
604
Henrik Boström31638672017-11-23 17:48:32 +0100605// Upon completion, posts a task to execute the callback of the
606// SetSessionDescriptionObserver asynchronously on the same thread. At this
607// point, the state of the peer connection might no longer reflect the effects
608// of the SetRemoteDescription operation, as the peer connection could have been
609// modified during the post.
610// TODO(hbos): Remove this class once we remove the version of
611// PeerConnectionInterface::SetRemoteDescription() that takes a
612// SetSessionDescriptionObserver as an argument.
613class PeerConnection::SetRemoteDescriptionObserverAdapter
614 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
615 public:
616 SetRemoteDescriptionObserverAdapter(
617 rtc::scoped_refptr<PeerConnection> pc,
618 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
619 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
620
621 // SetRemoteDescriptionObserverInterface implementation.
622 void OnSetRemoteDescriptionComplete(RTCError error) override {
623 if (error.ok())
624 pc_->PostSetSessionDescriptionSuccess(wrapper_);
625 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100626 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100627 }
628
629 private:
630 rtc::scoped_refptr<PeerConnection> pc_;
631 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
632};
633
deadbeef293e9262017-01-11 12:28:30 -0800634bool PeerConnectionInterface::RTCConfiguration::operator==(
635 const PeerConnectionInterface::RTCConfiguration& o) const {
636 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700637 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800638 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000639 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700640 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800641 BundlePolicy bundle_policy;
642 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700643 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
644 int ice_candidate_pool_size;
645 bool disable_ipv6;
646 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700647 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100648 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700649 bool enable_rtp_data_channel;
650 rtc::Optional<int> screencast_min_bitrate;
651 rtc::Optional<bool> combined_audio_video_bwe;
652 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800653 TcpCandidatePolicy tcp_candidate_policy;
654 CandidateNetworkPolicy candidate_network_policy;
655 int audio_jitter_buffer_max_packets;
656 bool audio_jitter_buffer_fast_accelerate;
657 int ice_connection_receiving_timeout;
658 int ice_backup_candidate_pair_ping_interval;
659 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800660 bool prioritize_most_likely_ice_candidate_pairs;
661 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800662 bool prune_turn_ports;
663 bool presume_writable_when_fully_relayed;
664 bool enable_ice_renomination;
665 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800666 rtc::Optional<int> ice_check_interval_strong_connectivity;
667 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800668 rtc::Optional<int> ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800669 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200671 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800672 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800673 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800674 };
675 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
676 "Did you add something to RTCConfiguration and forget to "
677 "update operator==?");
678 return type == o.type && servers == o.servers &&
679 bundle_policy == o.bundle_policy &&
680 rtcp_mux_policy == o.rtcp_mux_policy &&
681 tcp_candidate_policy == o.tcp_candidate_policy &&
682 candidate_network_policy == o.candidate_network_policy &&
683 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
684 audio_jitter_buffer_fast_accelerate ==
685 o.audio_jitter_buffer_fast_accelerate &&
686 ice_connection_receiving_timeout ==
687 o.ice_connection_receiving_timeout &&
688 ice_backup_candidate_pair_ping_interval ==
689 o.ice_backup_candidate_pair_ping_interval &&
690 continual_gathering_policy == o.continual_gathering_policy &&
691 certificates == o.certificates &&
692 prioritize_most_likely_ice_candidate_pairs ==
693 o.prioritize_most_likely_ice_candidate_pairs &&
694 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800695 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700696 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100697 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800698 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800699 screencast_min_bitrate == o.screencast_min_bitrate &&
700 combined_audio_video_bwe == o.combined_audio_video_bwe &&
701 enable_dtls_srtp == o.enable_dtls_srtp &&
702 ice_candidate_pool_size == o.ice_candidate_pool_size &&
703 prune_turn_ports == o.prune_turn_ports &&
704 presume_writable_when_fully_relayed ==
705 o.presume_writable_when_fully_relayed &&
706 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800707 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800708 ice_check_interval_strong_connectivity ==
709 o.ice_check_interval_strong_connectivity &&
710 ice_check_interval_weak_connectivity ==
711 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700712 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800713 stun_candidate_keepalive_interval ==
714 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200715 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800716 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800717 sdp_semantics == o.sdp_semantics &&
718 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800719}
720
721bool PeerConnectionInterface::RTCConfiguration::operator!=(
722 const PeerConnectionInterface::RTCConfiguration& o) const {
723 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800724}
725
zhihuang8f65cdf2016-05-06 18:40:30 -0700726// Generate a RTCP CNAME when a PeerConnection is created.
727std::string GenerateRtcpCname() {
728 std::string cname;
729 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800731 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700732 }
733 return cname;
734}
735
zhihuang1c378ed2017-08-17 14:10:50 -0700736bool ValidateOfferAnswerOptions(
737 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
738 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
739 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700740}
741
zhihuang1c378ed2017-08-17 14:10:50 -0700742// From |rtc_options|, fill parts of |session_options| shared by all generated
743// m= sections (in other words, nothing that involves a map/array).
744void ExtractSharedMediaSessionOptions(
745 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
746 cricket::MediaSessionOptions* session_options) {
747 session_options->vad_enabled = rtc_options.voice_activity_detection;
748 session_options->bundle_enabled = rtc_options.use_rtp_mux;
749}
zhihuanga77e6bb2017-08-14 18:17:48 -0700750
zhihuang1c378ed2017-08-17 14:10:50 -0700751bool ConvertConstraintsToOfferAnswerOptions(
752 const MediaConstraintsInterface* constraints,
753 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700754 if (!constraints) {
755 return true;
756 }
zhihuang1c378ed2017-08-17 14:10:50 -0700757
758 bool value = false;
759 size_t mandatory_constraints_satisfied = 0;
760
761 if (FindConstraint(constraints,
762 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
763 &mandatory_constraints_satisfied)) {
764 offer_answer_options->offer_to_receive_audio =
765 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
766 kOfferToReceiveMediaTrue
767 : 0;
768 }
769
770 if (FindConstraint(constraints,
771 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
772 &mandatory_constraints_satisfied)) {
773 offer_answer_options->offer_to_receive_video =
774 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
775 kOfferToReceiveMediaTrue
776 : 0;
777 }
778 if (FindConstraint(constraints,
779 MediaConstraintsInterface::kVoiceActivityDetection, &value,
780 &mandatory_constraints_satisfied)) {
781 offer_answer_options->voice_activity_detection = value;
782 }
783 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
784 &mandatory_constraints_satisfied)) {
785 offer_answer_options->use_rtp_mux = value;
786 }
787 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
788 &value, &mandatory_constraints_satisfied)) {
789 offer_answer_options->ice_restart = value;
790 }
791
deadbeefab9b2d12015-10-14 11:33:11 -0700792 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
793}
794
zhihuang38ede132017-06-15 12:52:32 -0700795PeerConnection::PeerConnection(PeerConnectionFactory* factory,
796 std::unique_ptr<RtcEventLog> event_log,
797 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700799 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700800 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700801 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700802 remote_streams_(StreamCollection::Create()),
803 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804
805PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100806 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800807 RTC_DCHECK_RUN_ON(signaling_thread());
808
Steve Anton8af21862017-12-15 11:20:13 -0800809 // Need to stop transceivers before destroying the stats collector because
810 // AudioRtpSender has a reference to the StatsCollector it will update when
811 // stopping.
812 for (auto transceiver : transceivers_) {
813 transceiver->Stop();
814 }
Steve Anton4171afb2017-11-20 10:20:22 -0800815
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700816 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800817 if (stats_collector_) {
818 stats_collector_->WaitForPendingRequest();
819 stats_collector_ = nullptr;
820 }
Steve Anton75737c02017-11-06 10:37:17 -0800821
Steve Anton8af21862017-12-15 11:20:13 -0800822 // Don't destroy BaseChannels until after stats has been cleaned up so that
823 // the last stats request can still read from the channels.
824 DestroyAllChannels();
825
Mirko Bonadei675513b2017-11-09 11:09:25 +0100826 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800827
828 webrtc_session_desc_factory_.reset();
829 sctp_invoker_.reset();
830 sctp_factory_.reset();
831 transport_controller_.reset();
832
deadbeef91dd5672016-05-18 16:55:30 -0700833 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700834 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700835 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700836 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700837 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700838 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800839 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700840 event_log_.reset();
841 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842}
843
Steve Anton8af21862017-12-15 11:20:13 -0800844void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800845 // Destroy video channels first since they may have a pointer to a voice
846 // channel.
847 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800848 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800849 DestroyTransceiverChannel(transceiver);
850 }
851 }
852 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800853 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800854 DestroyTransceiverChannel(transceiver);
855 }
856 }
857 DestroyDataChannel();
858}
859
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000861 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700862 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200863 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800864 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100865 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700866
867 RTCError config_error = ValidateConfiguration(configuration);
868 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100869 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700870 return false;
871 }
872
deadbeef293e9262017-01-11 12:28:30 -0800873 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100874 RTC_LOG(LS_ERROR)
875 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100876 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800877 return false;
878 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200879
deadbeef653b8e02015-11-11 12:55:10 -0800880 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800881 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100882 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100883 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800884 return false;
885 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000886 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800887 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800888
deadbeef91dd5672016-05-18 16:55:30 -0700889 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700890 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700891 if (!network_thread()->Invoke<bool>(
892 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
893 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894 return false;
895 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896
Steve Anton75737c02017-11-06 10:37:17 -0800897 // RFC 3264: The numeric value of the session id and version in the
898 // o line MUST be representable with a "64 bit signed integer".
899 // Due to this constraint session id |session_id_| is max limited to
900 // LLONG_MAX.
901 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
902 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800903 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
904 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800905 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
906 transport_controller_->SignalConnectionState.connect(
907 this, &PeerConnection::OnTransportControllerConnectionState);
908 transport_controller_->SignalGatheringState.connect(
909 this, &PeerConnection::OnTransportControllerGatheringState);
910 transport_controller_->SignalCandidatesGathered.connect(
911 this, &PeerConnection::OnTransportControllerCandidatesGathered);
912 transport_controller_->SignalCandidatesRemoved.connect(
913 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
914 transport_controller_->SignalDtlsHandshakeError.connect(
915 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
916
917 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700918
deadbeefab9b2d12015-10-14 11:33:11 -0700919 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700920 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921
Steve Antonba818672017-11-06 10:21:57 -0800922 configuration_ = configuration;
923
Steve Anton75737c02017-11-06 10:37:17 -0800924 const PeerConnectionFactoryInterface::Options& options = factory_->options();
925
926 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
927
928 // Obtain a certificate from RTCConfiguration if any were provided (optional).
929 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
930 if (!configuration.certificates.empty()) {
931 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
932 // just picking the first one. The decision should be made based on the DTLS
933 // handshake. The DTLS negotiations need to know about all certificates.
934 certificate = configuration.certificates[0];
935 }
936
Steve Antond25da372017-11-06 14:50:29 -0800937 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800938
939 if (options.disable_encryption) {
940 dtls_enabled_ = false;
941 } else {
942 // Enable DTLS by default if we have an identity store or a certificate.
943 dtls_enabled_ = (cert_generator || certificate);
944 // |configuration| can override the default |dtls_enabled_| value.
945 if (configuration.enable_dtls_srtp) {
946 dtls_enabled_ = *(configuration.enable_dtls_srtp);
947 }
948 }
949
950 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
951 // It takes precendence over the disable_sctp_data_channels
952 // PeerConnectionFactoryInterface::Options.
953 if (configuration.enable_rtp_data_channel) {
954 data_channel_type_ = cricket::DCT_RTP;
955 } else {
956 // DTLS has to be enabled to use SCTP.
957 if (!options.disable_sctp_data_channels && dtls_enabled_) {
958 data_channel_type_ = cricket::DCT_SCTP;
959 }
960 }
961
962 video_options_.screencast_min_bitrate_kbps =
963 configuration.screencast_min_bitrate;
964 audio_options_.combined_audio_video_bwe =
965 configuration.combined_audio_video_bwe;
966
967 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100968 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800969
970 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100971 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800972
973 // Whether the certificate generator/certificate is null or not determines
974 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
975 // the right instructions by clearing the variables if needed.
976 if (!dtls_enabled_) {
977 cert_generator.reset();
978 certificate = nullptr;
979 } else if (certificate) {
980 // Favor generated certificate over the certificate generator.
981 cert_generator.reset();
982 }
983
984 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
985 signaling_thread(), channel_manager(), this, session_id(),
986 std::move(cert_generator), certificate));
987 webrtc_session_desc_factory_->SignalCertificateReady.connect(
988 this, &PeerConnection::OnCertificateReady);
989
990 if (options.disable_encryption) {
991 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
992 }
993
994 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
995 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996
Steve Anton4171afb2017-11-20 10:20:22 -0800997 // Add default audio/video transceivers for Plan B SDP.
998 if (!IsUnifiedPlan()) {
999 transceivers_.push_back(
1000 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1001 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1002 transceivers_.push_back(
1003 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1004 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1005 }
1006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 return true;
1008}
1009
Steve Anton038834f2017-07-14 15:59:59 -07001010RTCError PeerConnection::ValidateConfiguration(
1011 const RTCConfiguration& config) const {
1012 if (config.ice_regather_interval_range &&
1013 config.continual_gathering_policy == GATHER_ONCE) {
1014 return RTCError(RTCErrorType::INVALID_PARAMETER,
1015 "ice_regather_interval_range specified but continual "
1016 "gathering policy is GATHER_ONCE");
1017 }
1018 return RTCError::OK();
1019}
1020
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001021rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001023 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1024 "Plan SdpSemantics. Please use GetSenders "
1025 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001026 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027}
1028
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001029rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001031 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1032 "Plan SdpSemantics. Please use GetReceivers "
1033 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001034 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035}
1036
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001037bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001038 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1039 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001040 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 if (IsClosed()) {
1042 return false;
1043 }
deadbeefab9b2d12015-10-14 11:33:11 -07001044 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 return false;
1046 }
deadbeefab9b2d12015-10-14 11:33:11 -07001047
1048 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001049 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1050 observer->SignalAudioTrackAdded.connect(this,
1051 &PeerConnection::OnAudioTrackAdded);
1052 observer->SignalAudioTrackRemoved.connect(
1053 this, &PeerConnection::OnAudioTrackRemoved);
1054 observer->SignalVideoTrackAdded.connect(this,
1055 &PeerConnection::OnVideoTrackAdded);
1056 observer->SignalVideoTrackRemoved.connect(
1057 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001058 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001059
deadbeefab9b2d12015-10-14 11:33:11 -07001060 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001061 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001062 }
1063 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001064 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001065 }
1066
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001067 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 observer_->OnRenegotiationNeeded();
1069 return true;
1070}
1071
1072void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001073 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1074 "Plan SdpSemantics. Please use RemoveTrack "
1075 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001077 if (!IsClosed()) {
1078 for (const auto& track : local_stream->GetAudioTracks()) {
1079 RemoveAudioTrack(track.get(), local_stream);
1080 }
1081 for (const auto& track : local_stream->GetVideoTracks()) {
1082 RemoveVideoTrack(track.get(), local_stream);
1083 }
deadbeefab9b2d12015-10-14 11:33:11 -07001084 }
deadbeefab9b2d12015-10-14 11:33:11 -07001085 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001086 stream_observers_.erase(
1087 std::remove_if(
1088 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001089 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001090 return observer->stream()->label().compare(local_stream->label()) ==
1091 0;
1092 }),
1093 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001094
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 if (IsClosed()) {
1096 return;
1097 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 observer_->OnRenegotiationNeeded();
1099}
1100
deadbeefe1f9d832016-01-14 15:35:42 -08001101rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1102 MediaStreamTrackInterface* track,
1103 std::vector<MediaStreamInterface*> streams) {
1104 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001105 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001106 for (auto* stream : streams) {
1107 if (!stream) {
1108 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1109 return nullptr;
1110 }
Seth Hampson845e8782018-03-02 11:34:10 -08001111 stream_ids.push_back(stream->label());
Steve Antonf9381f02017-12-14 10:23:57 -08001112 }
Seth Hampson845e8782018-03-02 11:34:10 -08001113 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001114 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001115 return nullptr;
1116 }
Steve Antonf9381f02017-12-14 10:23:57 -08001117 return sender_or_error.MoveValue();
1118}
1119
Steve Anton2d6c76a2018-01-05 17:10:52 -08001120RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001121 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001122 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001123 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001124 if (!track) {
1125 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1126 }
1127 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1128 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1130 "Track has invalid kind: " + track->kind());
1131 }
1132 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
Seth Hampson845e8782018-03-02 11:34:10 -08001133 if (stream_ids.size() > 1u) {
Steve Antonf9381f02017-12-14 10:23:57 -08001134 LOG_AND_RETURN_ERROR(
1135 RTCErrorType::UNSUPPORTED_OPERATION,
1136 "AddTrack with more than one stream is not currently supported.");
1137 }
1138 if (IsClosed()) {
1139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1140 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001141 }
Steve Anton4171afb2017-11-20 10:20:22 -08001142 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001143 LOG_AND_RETURN_ERROR(
1144 RTCErrorType::INVALID_PARAMETER,
1145 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001146 }
Steve Antonf9381f02017-12-14 10:23:57 -08001147 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1148 // one stream. AddTrackInternal will return an error if there is more than one
1149 // stream, but if the caller specifies none then we need to generate a random
Seth Hampson845e8782018-03-02 11:34:10 -08001150 // stream id.
1151 std::vector<std::string> adjusted_stream_ids = stream_ids;
1152 if (stream_ids.empty()) {
1153 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
Steve Antonf9381f02017-12-14 10:23:57 -08001154 }
Seth Hampson845e8782018-03-02 11:34:10 -08001155 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001156 auto sender_or_error =
Seth Hampson845e8782018-03-02 11:34:10 -08001157 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1158 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001159 if (sender_or_error.ok()) {
1160 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001161 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001162 }
1163 return sender_or_error;
1164}
deadbeefe1f9d832016-01-14 15:35:42 -08001165
Steve Antonf9381f02017-12-14 10:23:57 -08001166RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1167PeerConnection::AddTrackPlanB(
1168 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001169 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001170 cricket::MediaType media_type =
1171 (track->kind() == MediaStreamTrackInterface::kAudioKind
1172 ? cricket::MEDIA_TYPE_AUDIO
1173 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001174 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001175 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001176 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001177 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001178 const RtpSenderInfo* sender_info =
1179 FindSenderInfo(local_audio_sender_infos_,
1180 new_sender->internal()->stream_id(), track->id());
1181 if (sender_info) {
1182 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001183 }
Steve Antonf9381f02017-12-14 10:23:57 -08001184 } else {
1185 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001186 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001187 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001188 const RtpSenderInfo* sender_info =
1189 FindSenderInfo(local_video_sender_infos_,
1190 new_sender->internal()->stream_id(), track->id());
1191 if (sender_info) {
1192 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001193 }
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001195 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001196}
deadbeefe1f9d832016-01-14 15:35:42 -08001197
Steve Antonf9381f02017-12-14 10:23:57 -08001198RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1199PeerConnection::AddTrackUnifiedPlan(
1200 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001201 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001202 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1203 if (transceiver) {
1204 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001205 transceiver->internal()->set_direction(
1206 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001207 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001208 transceiver->internal()->set_direction(
1209 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001210 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001211 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001212 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001213 } else {
1214 cricket::MediaType media_type =
1215 (track->kind() == MediaStreamTrackInterface::kAudioKind
1216 ? cricket::MEDIA_TYPE_AUDIO
1217 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001218 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001219 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1220 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001221 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001222 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 return transceiver->sender();
1225}
1226
1227rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1228PeerConnection::FindFirstTransceiverForAddedTrack(
1229 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1230 RTC_DCHECK(track);
1231 for (auto transceiver : transceivers_) {
1232 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001233 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001234 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001235 !transceiver->internal()->has_ever_been_used_to_send() &&
1236 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001237 return transceiver;
1238 }
1239 }
1240 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001241}
1242
1243bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1244 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001245 return RemoveTrackInternal(sender).ok();
1246}
1247
1248RTCError PeerConnection::RemoveTrackInternal(
1249 rtc::scoped_refptr<RtpSenderInterface> sender) {
1250 if (!sender) {
1251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1252 }
deadbeefe1f9d832016-01-14 15:35:42 -08001253 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1255 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001256 }
Steve Antonf9381f02017-12-14 10:23:57 -08001257 if (IsUnifiedPlan()) {
1258 auto transceiver = FindTransceiverBySender(sender);
1259 if (!transceiver || !sender->track()) {
1260 return RTCError::OK();
1261 }
1262 sender->SetTrack(nullptr);
1263 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001264 transceiver->internal()->set_direction(
1265 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001266 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001267 transceiver->internal()->set_direction(
1268 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001269 }
Steve Anton4171afb2017-11-20 10:20:22 -08001270 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001271 bool removed;
1272 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1273 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1274 } else {
1275 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1276 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1277 }
1278 if (!removed) {
1279 LOG_AND_RETURN_ERROR(
1280 RTCErrorType::INVALID_PARAMETER,
1281 "Couldn't find sender " + sender->id() + " to remove.");
1282 }
Steve Anton4171afb2017-11-20 10:20:22 -08001283 }
deadbeefe1f9d832016-01-14 15:35:42 -08001284 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001285 return RTCError::OK();
1286}
1287
1288rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1289PeerConnection::FindTransceiverBySender(
1290 rtc::scoped_refptr<RtpSenderInterface> sender) {
1291 for (auto transceiver : transceivers_) {
1292 if (transceiver->sender() == sender) {
1293 return transceiver;
1294 }
1295 }
1296 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001297}
1298
Steve Anton9158ef62017-11-27 13:01:52 -08001299RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1300PeerConnection::AddTransceiver(
1301 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1302 return AddTransceiver(track, RtpTransceiverInit());
1303}
1304
1305RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1306PeerConnection::AddTransceiver(
1307 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1308 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001309 RTC_CHECK(IsUnifiedPlan())
1310 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001311 if (!track) {
1312 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1313 }
1314 cricket::MediaType media_type;
1315 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1316 media_type = cricket::MEDIA_TYPE_AUDIO;
1317 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1318 media_type = cricket::MEDIA_TYPE_VIDEO;
1319 } else {
1320 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1321 "Track kind is not audio or video");
1322 }
1323 return AddTransceiver(media_type, track, init);
1324}
1325
1326RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1327PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1328 return AddTransceiver(media_type, RtpTransceiverInit());
1329}
1330
1331RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1332PeerConnection::AddTransceiver(cricket::MediaType media_type,
1333 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001334 RTC_CHECK(IsUnifiedPlan())
1335 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001336 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1337 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1338 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1339 "media type is not audio or video");
1340 }
1341 return AddTransceiver(media_type, nullptr, init);
1342}
1343
1344RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1345PeerConnection::AddTransceiver(
1346 cricket::MediaType media_type,
1347 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001348 const RtpTransceiverInit& init,
1349 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001350 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1351 media_type == cricket::MEDIA_TYPE_VIDEO));
1352 if (track) {
1353 RTC_DCHECK_EQ(media_type,
1354 (track->kind() == MediaStreamTrackInterface::kAudioKind
1355 ? cricket::MEDIA_TYPE_AUDIO
1356 : cricket::MEDIA_TYPE_VIDEO));
1357 }
1358
1359 // TODO(bugs.webrtc.org/7600): Verify init.
1360
Seth Hampson513449e2018-03-06 09:35:56 -08001361 if (init.stream_ids.size() > 1u) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001362 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1363 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001364 }
1365
Seth Hampson513449e2018-03-06 09:35:56 -08001366 std::vector<std::string> stream_ids = {
1367 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
Steve Anton02ee47c2018-01-10 16:26:06 -08001368
Seth Hampson845e8782018-03-02 11:34:10 -08001369 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001370 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1371 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1372 transceiver->internal()->set_direction(init.direction);
1373
Steve Anton22da89f2018-01-25 13:58:07 -08001374 if (fire_callback) {
1375 observer_->OnRenegotiationNeeded();
1376 }
Steve Antonf9381f02017-12-14 10:23:57 -08001377
1378 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1379}
1380
Steve Anton02ee47c2018-01-10 16:26:06 -08001381rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1382PeerConnection::CreateSender(
1383 cricket::MediaType media_type,
1384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001385 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001386 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001387 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1388 RTC_DCHECK(!track ||
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1390 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1391 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001392 new AudioRtpSender(worker_thread(),
1393 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001394 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 } else {
1396 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1397 RTC_DCHECK(!track ||
1398 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1399 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1400 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001401 new VideoRtpSender(worker_thread(),
1402 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001403 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 }
Seth Hampson845e8782018-03-02 11:34:10 -08001405 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 return sender;
1407}
1408
1409rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1410PeerConnection::CreateReceiver(cricket::MediaType media_type,
1411 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001412 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1413 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001414 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001415 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001416 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001417 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001418 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001419 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001420 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1421 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001422 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001423 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001424 return receiver;
1425}
1426
1427rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1428PeerConnection::CreateAndAddTransceiver(
1429 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1430 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1431 receiver) {
1432 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1433 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001434 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001435 transceiver->internal()->SignalNegotiationNeeded.connect(
1436 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001437 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001438}
1439
Steve Anton52d86772018-02-20 15:48:12 -08001440void PeerConnection::OnNegotiationNeeded() {
1441 RTC_DCHECK_RUN_ON(signaling_thread());
1442 RTC_DCHECK(!IsClosed());
1443 observer_->OnRenegotiationNeeded();
1444}
1445
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001448 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001449 if (IsClosed()) {
1450 return nullptr;
1451 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001453 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001454 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455 }
Steve Anton4171afb2017-11-20 10:20:22 -08001456 auto track_sender = FindSenderForTrack(track);
1457 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001458 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001459 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 }
1461
Steve Anton4171afb2017-11-20 10:20:22 -08001462 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463}
1464
deadbeeffac06552015-11-25 11:26:01 -08001465rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001466 const std::string& kind,
1467 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001468 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1469 "Plan SdpSemantics. Please use AddTransceiver "
1470 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001471 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001472 if (IsClosed()) {
1473 return nullptr;
1474 }
Steve Anton4171afb2017-11-20 10:20:22 -08001475
Seth Hampson845e8782018-03-02 11:34:10 -08001476 std::vector<std::string> stream_ids;
Steve Anton02ee47c2018-01-10 16:26:06 -08001477 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001478 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001479 }
1480
Steve Anton4171afb2017-11-20 10:20:22 -08001481 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001482 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001483 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001484 auto* audio_sender =
1485 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001486 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001487 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001488 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001489 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001490 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001491 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001492 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001493 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001494 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001496 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001497 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001498 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001499 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001500 }
Steve Anton4171afb2017-11-20 10:20:22 -08001501
deadbeefe1f9d832016-01-14 15:35:42 -08001502 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001503}
1504
deadbeef70ab1a12015-09-28 16:53:55 -07001505std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1506 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001507 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001508 for (auto sender : GetSendersInternal()) {
1509 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001510 }
1511 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001512}
1513
Steve Anton4171afb2017-11-20 10:20:22 -08001514std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1515PeerConnection::GetSendersInternal() const {
1516 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1517 all_senders;
1518 for (auto transceiver : transceivers_) {
1519 auto senders = transceiver->internal()->senders();
1520 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1521 }
1522 return all_senders;
1523}
1524
deadbeef70ab1a12015-09-28 16:53:55 -07001525std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1526PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001527 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001528 for (const auto& receiver : GetReceiversInternal()) {
1529 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001530 }
1531 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001532}
1533
Steve Anton4171afb2017-11-20 10:20:22 -08001534std::vector<
1535 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1536PeerConnection::GetReceiversInternal() const {
1537 std::vector<
1538 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1539 all_receivers;
1540 for (auto transceiver : transceivers_) {
1541 auto receivers = transceiver->internal()->receivers();
1542 all_receivers.insert(all_receivers.end(), receivers.begin(),
1543 receivers.end());
1544 }
1545 return all_receivers;
1546}
1547
Steve Anton9158ef62017-11-27 13:01:52 -08001548std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1549PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001550 RTC_CHECK(IsUnifiedPlan())
1551 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001552 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1553 for (auto transceiver : transceivers_) {
1554 all_transceivers.push_back(transceiver);
1555 }
1556 return all_transceivers;
1557}
1558
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001560 MediaStreamTrackInterface* track,
1561 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001562 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001563 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001564 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 return false;
1567 }
1568
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001569 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001570 // The StatsCollector is used to tell if a track is valid because it may
1571 // remember tracks that the PeerConnection previously removed.
1572 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001573 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1574 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001575 return false;
1576 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001577 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001578 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 return true;
1580}
1581
hbos74e1a4f2016-09-15 23:33:01 -07001582void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1583 RTC_DCHECK(stats_collector_);
1584 stats_collector_->GetStatsReport(callback);
1585}
1586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001587PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1588 return signaling_state_;
1589}
1590
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591PeerConnectionInterface::IceConnectionState
1592PeerConnection::ice_connection_state() {
1593 return ice_connection_state_;
1594}
1595
1596PeerConnectionInterface::IceGatheringState
1597PeerConnection::ice_gathering_state() {
1598 return ice_gathering_state_;
1599}
1600
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001601rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001602PeerConnection::CreateDataChannel(
1603 const std::string& label,
1604 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001605 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001606
deadbeefab9b2d12015-10-14 11:33:11 -07001607 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001608
kwibergd1fe2812016-04-27 06:47:29 -07001609 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001610 if (config) {
1611 internal_config.reset(new InternalDataChannelInit(*config));
1612 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001613 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001614 InternalCreateDataChannel(label, internal_config.get()));
1615 if (!channel.get()) {
1616 return nullptr;
1617 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001619 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1620 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001621 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001622 observer_->OnRenegotiationNeeded();
1623 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001624
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625 return DataChannelProxy::Create(signaling_thread(), channel.get());
1626}
1627
1628void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1629 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001630 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001631
zhihuang1c378ed2017-08-17 14:10:50 -07001632 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1633 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1634 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1635 // compares the mandatory fields parsed with the mandatory fields added in the
1636 // |constraints| and some downstream applications might create offers with
1637 // mandatory fields which would not be parsed in the helper method. For
1638 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1639 // |constraints| as a mandatory field but it is not parsed.
1640 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001641
zhihuang1c378ed2017-08-17 14:10:50 -07001642 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001643}
1644
1645void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1646 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001647 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001648
nisse7ce109a2017-01-31 00:57:56 -08001649 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001650 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001651 return;
1652 }
deadbeefab9b2d12015-10-14 11:33:11 -07001653
Steve Anton8d3444d2017-10-20 15:30:51 -07001654 if (IsClosed()) {
1655 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001656 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001657 PostCreateSessionDescriptionFailure(
1658 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001659 return;
1660 }
1661
zhihuang1c378ed2017-08-17 14:10:50 -07001662 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001663 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001665 PostCreateSessionDescriptionFailure(
1666 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001667 return;
1668 }
1669
Steve Anton22da89f2018-01-25 13:58:07 -08001670 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1671 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1672 if (IsUnifiedPlan()) {
1673 RTCError error = HandleLegacyOfferOptions(options);
1674 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001675 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001676 return;
1677 }
1678 }
1679
zhihuang1c378ed2017-08-17 14:10:50 -07001680 cricket::MediaSessionOptions session_options;
1681 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001682 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683}
1684
Steve Anton22da89f2018-01-25 13:58:07 -08001685RTCError PeerConnection::HandleLegacyOfferOptions(
1686 const RTCOfferAnswerOptions& options) {
1687 RTC_DCHECK(IsUnifiedPlan());
1688
1689 if (options.offer_to_receive_audio == 0) {
1690 RemoveRecvDirectionFromReceivingTransceiversOfType(
1691 cricket::MEDIA_TYPE_AUDIO);
1692 } else if (options.offer_to_receive_audio == 1) {
1693 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1694 } else if (options.offer_to_receive_audio > 1) {
1695 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1696 "offer_to_receive_audio > 1 is not supported.");
1697 }
1698
1699 if (options.offer_to_receive_video == 0) {
1700 RemoveRecvDirectionFromReceivingTransceiversOfType(
1701 cricket::MEDIA_TYPE_VIDEO);
1702 } else if (options.offer_to_receive_video == 1) {
1703 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1704 } else if (options.offer_to_receive_video > 1) {
1705 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1706 "offer_to_receive_video > 1 is not supported.");
1707 }
1708
1709 return RTCError::OK();
1710}
1711
1712void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1713 cricket::MediaType media_type) {
1714 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1715 transceiver->internal()->set_direction(
1716 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1717 }
1718}
1719
1720void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1721 cricket::MediaType media_type) {
1722 if (GetReceivingTransceiversOfType(media_type).empty()) {
1723 RtpTransceiverInit init;
1724 init.direction = RtpTransceiverDirection::kRecvOnly;
1725 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1726 }
1727}
1728
1729std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1730PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1731 std::vector<
1732 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1733 receiving_transceivers;
1734 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001735 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001736 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1737 receiving_transceivers.push_back(transceiver);
1738 }
1739 }
1740 return receiving_transceivers;
1741}
1742
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743void PeerConnection::CreateAnswer(
1744 CreateSessionDescriptionObserver* observer,
1745 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001746 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001747
nisse7ce109a2017-01-31 00:57:56 -08001748 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001750 return;
1751 }
deadbeefab9b2d12015-10-14 11:33:11 -07001752
zhihuang1c378ed2017-08-17 14:10:50 -07001753 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1754 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1755 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001756 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001757 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001758 PostCreateSessionDescriptionFailure(
1759 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001760 return;
1761 }
1762
Steve Anton8d3444d2017-10-20 15:30:51 -07001763 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001764}
1765
1766void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1767 const RTCOfferAnswerOptions& options) {
1768 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001769 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001770 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001771 return;
1772 }
1773
Steve Antondffead82018-02-06 10:31:29 -08001774 if (!(signaling_state_ == kHaveRemoteOffer ||
1775 signaling_state_ == kHaveLocalPrAnswer)) {
1776 std::string error =
1777 "PeerConnection cannot create an answer in a state other than "
1778 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001779 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001780 PostCreateSessionDescriptionFailure(
1781 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001782 return;
1783 }
1784
Steve Antondffead82018-02-06 10:31:29 -08001785 // The remote description should be set if we're in the right state.
1786 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001787
Steve Anton22da89f2018-01-25 13:58:07 -08001788 if (IsUnifiedPlan()) {
1789 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1790 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1791 "supported with Unified Plan semantics. Use the "
1792 "RtpTransceiver API instead.";
1793 }
1794 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1795 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1796 "supported with Unified Plan semantics. Use the "
1797 "RtpTransceiver API instead.";
1798 }
1799 }
1800
htaa2a49d92016-03-04 02:51:39 -08001801 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001802 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001803
Steve Antond25da372017-11-06 14:50:29 -08001804 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805}
1806
1807void PeerConnection::SetLocalDescription(
1808 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001809 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001810 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001811
Steve Anton80dd7b52018-02-16 17:08:42 -08001812 // The SetLocalDescription contract is that we take ownership of the session
1813 // description regardless of the outcome, so wrap it in a unique_ptr right
1814 // away. Ideally, SetLocalDescription's signature will be changed to take the
1815 // description as a unique_ptr argument to formalize this agreement.
1816 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1817
nisse7ce109a2017-01-31 00:57:56 -08001818 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return;
1821 }
Steve Anton8a006912017-12-04 15:25:56 -08001822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostSetSessionDescriptionFailure(
1825 observer,
1826 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 return;
1828 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001829
Steve Anton80dd7b52018-02-16 17:08:42 -08001830 // If a session error has occurred the PeerConnection is in a possibly
1831 // inconsistent state so fail right away.
1832 if (session_error() != SessionError::kNone) {
1833 std::string error_message = GetSessionErrorMsg();
1834 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001835 PostSetSessionDescriptionFailure(
1836 observer,
1837 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001838 return;
1839 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001840
Steve Anton80dd7b52018-02-16 17:08:42 -08001841 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1842 if (!error.ok()) {
1843 std::string error_message = GetSetDescriptionErrorMessage(
1844 cricket::CS_LOCAL, desc->GetType(), error);
1845 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001846 PostSetSessionDescriptionFailure(
1847 observer,
1848 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001849 return;
1850 }
1851
1852 // Grab the description type before moving ownership to ApplyLocalDescription,
1853 // which may destroy it before returning.
1854 const SdpType type = desc->GetType();
1855
1856 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001857 // |desc| may be destroyed at this point.
1858
1859 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001860 // If ApplyLocalDescription fails, the PeerConnection could be in an
1861 // inconsistent state, so act conservatively here and set the session error
1862 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1863 SetSessionError(SessionError::kContent, error.message());
1864 std::string error_message =
1865 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1866 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001867 PostSetSessionDescriptionFailure(
1868 observer,
1869 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001870 return;
1871 }
Steve Anton8a006912017-12-04 15:25:56 -08001872 RTC_DCHECK(local_description());
1873
1874 PostSetSessionDescriptionSuccess(observer);
1875
1876 // According to JSEP, after setLocalDescription, changing the candidate pool
1877 // size is not allowed, and changing the set of ICE servers will not result
1878 // in new candidates being gathered.
1879 port_allocator_->FreezeCandidatePool();
1880
1881 // MaybeStartGathering needs to be called after posting
1882 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1883 // before signaling that SetLocalDescription completed.
1884 transport_controller_->MaybeStartGathering();
1885
Steve Antona3a92c22017-12-07 10:27:41 -08001886 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001887 // TODO(deadbeef): We already had to hop to the network thread for
1888 // MaybeStartGathering...
1889 network_thread()->Invoke<void>(
1890 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1891 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001892 // Make UMA notes about what was agreed to.
1893 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001894 }
1895}
1896
1897RTCError PeerConnection::ApplyLocalDescription(
1898 std::unique_ptr<SessionDescriptionInterface> desc) {
1899 RTC_DCHECK_RUN_ON(signaling_thread());
1900 RTC_DCHECK(desc);
1901
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 // Update stats here so that we have the most recent stats for tracks and
1903 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001904 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001905
1906 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001907 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001908 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001909 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001910 if (*initial_offerer_) {
1911 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1912 } else {
1913 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1914 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 }
Steve Anton8a006912017-12-04 15:25:56 -08001916
Steve Antondcc3c022017-12-22 16:02:54 -08001917 // Take a reference to the old local description since it's used below to
1918 // compare against the new local description. When setting the new local
1919 // description, grab ownership of the replaced session description in case it
1920 // is the same as |old_local_description|, to keep it alive for the duration
1921 // of the method.
1922 const SessionDescriptionInterface* old_local_description =
1923 local_description();
1924 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001925 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001926 replaced_local_description = pending_local_description_
1927 ? std::move(pending_local_description_)
1928 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001929 current_local_description_ = std::move(desc);
1930 pending_local_description_ = nullptr;
1931 current_remote_description_ = std::move(pending_remote_description_);
1932 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001933 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001934 pending_local_description_ = std::move(desc);
1935 }
1936 // The session description to apply now must be accessed by
1937 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001938 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001939
Steve Antondcc3c022017-12-22 16:02:54 -08001940 if (IsUnifiedPlan()) {
1941 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001942 cricket::CS_LOCAL, *local_description(), old_local_description,
1943 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001944 if (!error.ok()) {
1945 return error;
1946 }
Steve Antondcc3c022017-12-22 16:02:54 -08001947 for (auto transceiver : transceivers_) {
1948 const ContentInfo* content =
1949 FindMediaSectionForTransceiver(transceiver, local_description());
1950 if (!content) {
1951 continue;
1952 }
1953 const MediaContentDescription* media_desc = content->media_description();
1954 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1955 transceiver->internal()->set_current_direction(media_desc->direction());
1956 }
1957 if (content->rejected && !transceiver->stopped()) {
1958 transceiver->Stop();
1959 }
1960 }
1961 } else {
1962 // Transport and Media channels will be created only when offer is set.
1963 if (type == SdpType::kOffer) {
1964 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1965 // description is applied. Restore back to old description.
1966 RTCError error = CreateChannels(*local_description()->description());
1967 if (!error.ok()) {
1968 return error;
1969 }
1970 }
Steve Anton8a006912017-12-04 15:25:56 -08001971
Steve Antondcc3c022017-12-22 16:02:54 -08001972 // Remove unused channels if MediaContentDescription is rejected.
1973 RemoveUnusedChannels(local_description()->description());
1974 }
Steve Anton8a006912017-12-04 15:25:56 -08001975
Steve Anton80dd7b52018-02-16 17:08:42 -08001976 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001977 if (!error.ok()) {
1978 return error;
1979 }
Steve Antondcc3c022017-12-22 16:02:54 -08001980
Steve Anton8a006912017-12-04 15:25:56 -08001981 if (remote_description()) {
1982 // Now that we have a local description, we can push down remote candidates.
1983 UseCandidatesInSessionDescription(remote_description());
1984 }
1985
1986 pending_ice_restarts_.clear();
1987 if (session_error() != SessionError::kNone) {
1988 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1989 }
1990
deadbeefab9b2d12015-10-14 11:33:11 -07001991 // If setting the description decided our SSL role, allocate any necessary
1992 // SCTP sids.
1993 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001994 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001995 AllocateSctpSids(role);
1996 }
1997
Steve Antond3679212018-01-17 17:41:02 -08001998 if (IsUnifiedPlan()) {
1999 for (auto transceiver : transceivers_) {
2000 const ContentInfo* content =
2001 FindMediaSectionForTransceiver(transceiver, local_description());
2002 if (!content) {
2003 continue;
2004 }
2005 if (content->rejected && !transceiver->stopped()) {
2006 transceiver->Stop();
2007 }
Steve Anton74255ff2018-01-24 18:32:57 -08002008 const auto& streams = content->media_description()->streams();
2009 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002010 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002011 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002012 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002013 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002014 }
2015 }
2016 } else {
2017 // Plan B semantics.
2018
Steve Antondcc3c022017-12-22 16:02:54 -08002019 // Update state and SSRC of local MediaStreams and DataChannels based on the
2020 // local session description.
2021 const cricket::ContentInfo* audio_content =
2022 GetFirstAudioContent(local_description()->description());
2023 if (audio_content) {
2024 if (audio_content->rejected) {
2025 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2026 } else {
2027 const cricket::AudioContentDescription* audio_desc =
2028 audio_content->media_description()->as_audio();
2029 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2030 }
deadbeeffaac4972015-11-12 15:33:07 -08002031 }
deadbeefab9b2d12015-10-14 11:33:11 -07002032
Steve Antondcc3c022017-12-22 16:02:54 -08002033 const cricket::ContentInfo* video_content =
2034 GetFirstVideoContent(local_description()->description());
2035 if (video_content) {
2036 if (video_content->rejected) {
2037 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2038 } else {
2039 const cricket::VideoContentDescription* video_desc =
2040 video_content->media_description()->as_video();
2041 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2042 }
deadbeeffaac4972015-11-12 15:33:07 -08002043 }
deadbeefab9b2d12015-10-14 11:33:11 -07002044 }
2045
2046 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002047 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002048 if (data_content) {
2049 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002050 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002051 if (rtc::starts_with(data_desc->protocol().data(),
2052 cricket::kMediaProtocolRtpPrefix)) {
2053 UpdateLocalRtpDataChannels(data_desc->streams());
2054 }
2055 }
2056
Steve Anton8a006912017-12-04 15:25:56 -08002057 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058}
2059
2060void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002061 SetSessionDescriptionObserver* observer,
2062 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002063 SetRemoteDescription(
2064 std::unique_ptr<SessionDescriptionInterface>(desc),
2065 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2066 new SetRemoteDescriptionObserverAdapter(this, observer)));
2067}
2068
2069void PeerConnection::SetRemoteDescription(
2070 std::unique_ptr<SessionDescriptionInterface> desc,
2071 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002072 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002073
nisse7ce109a2017-01-31 00:57:56 -08002074 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002075 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 return;
2077 }
Steve Anton8a006912017-12-04 15:25:56 -08002078
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002080 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002081 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002082 return;
2083 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002084
Steve Anton80dd7b52018-02-16 17:08:42 -08002085 // If a session error has occurred the PeerConnection is in a possibly
2086 // inconsistent state so fail right away.
2087 if (session_error() != SessionError::kNone) {
2088 std::string error_message = GetSessionErrorMsg();
2089 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2090 observer->OnSetRemoteDescriptionComplete(
2091 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2092 return;
2093 }
Steve Anton71439a62018-02-15 11:53:06 -08002094
Steve Anton80dd7b52018-02-16 17:08:42 -08002095 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002096 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002097 std::string error_message = GetSetDescriptionErrorMessage(
2098 cricket::CS_REMOTE, desc->GetType(), error);
2099 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002100 observer->OnSetRemoteDescriptionComplete(
2101 RTCError(error.type(), std::move(error_message)));
2102 return;
2103 }
Steve Anton71439a62018-02-15 11:53:06 -08002104
Steve Anton80dd7b52018-02-16 17:08:42 -08002105 // Grab the description type before moving ownership to
2106 // ApplyRemoteDescription, which may destroy it before returning.
2107 const SdpType type = desc->GetType();
2108
2109 error = ApplyRemoteDescription(std::move(desc));
2110 // |desc| may be destroyed at this point.
2111
2112 if (!error.ok()) {
2113 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2114 // inconsistent state, so act conservatively here and set the session error
2115 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2116 SetSessionError(SessionError::kContent, error.message());
2117 std::string error_message =
2118 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2119 RTC_LOG(LS_ERROR) << error_message;
2120 observer->OnSetRemoteDescriptionComplete(
2121 RTCError(error.type(), std::move(error_message)));
2122 return;
2123 }
2124 RTC_DCHECK(remote_description());
2125
Steve Anton8e20f172018-03-06 10:55:04 -08002126 if (type == SdpType::kOffer) {
2127 // Report to UMA the format of the received offer.
2128 ReportSdpFormatReceived(*remote_description());
2129 }
2130
Steve Anton80dd7b52018-02-16 17:08:42 -08002131 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002132 // TODO(deadbeef): We already had to hop to the network thread for
2133 // MaybeStartGathering...
2134 network_thread()->Invoke<void>(
2135 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2136 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002137 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002138 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002139 }
2140
2141 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2142}
2143
2144RTCError PeerConnection::ApplyRemoteDescription(
2145 std::unique_ptr<SessionDescriptionInterface> desc) {
2146 RTC_DCHECK_RUN_ON(signaling_thread());
2147 RTC_DCHECK(desc);
2148
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 // Update stats here so that we have the most recent stats for tracks and
2150 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002151 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002152
Steve Antondcc3c022017-12-22 16:02:54 -08002153 // Take a reference to the old remote description since it's used below to
2154 // compare against the new remote description. When setting the new remote
2155 // description, grab ownership of the replaced session description in case it
2156 // is the same as |old_remote_description|, to keep it alive for the duration
2157 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002158 const SessionDescriptionInterface* old_remote_description =
2159 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002160 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002161 SdpType type = desc->GetType();
2162 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002163 replaced_remote_description = pending_remote_description_
2164 ? std::move(pending_remote_description_)
2165 : std::move(current_remote_description_);
2166 current_remote_description_ = std::move(desc);
2167 pending_remote_description_ = nullptr;
2168 current_local_description_ = std::move(pending_local_description_);
2169 } else {
2170 replaced_remote_description = std::move(pending_remote_description_);
2171 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 }
Steve Anton8a006912017-12-04 15:25:56 -08002173 // The session description to apply now must be accessed by
2174 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002175 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176
Steve Anton8a006912017-12-04 15:25:56 -08002177 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002178 if (IsUnifiedPlan()) {
2179 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002180 cricket::CS_REMOTE, *remote_description(), local_description(),
2181 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002182 if (!error.ok()) {
2183 return error;
2184 }
Steve Antondcc3c022017-12-22 16:02:54 -08002185 } else {
2186 if (type == SdpType::kOffer) {
2187 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2188 // description is applied. Restore back to old description.
2189 RTCError error = CreateChannels(*remote_description()->description());
2190 if (!error.ok()) {
2191 return error;
2192 }
2193 }
Steve Anton8a006912017-12-04 15:25:56 -08002194
Steve Antondcc3c022017-12-22 16:02:54 -08002195 // Remove unused channels if MediaContentDescription is rejected.
2196 RemoveUnusedChannels(remote_description()->description());
2197 }
Steve Anton8a006912017-12-04 15:25:56 -08002198
2199 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2200 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002201 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002202 if (!error.ok()) {
2203 return error;
2204 }
2205
2206 if (local_description() &&
2207 !UseCandidatesInSessionDescription(remote_description())) {
2208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2209 }
2210
2211 if (old_remote_description) {
2212 for (const cricket::ContentInfo& content :
2213 old_remote_description->description()->contents()) {
2214 // Check if this new SessionDescription contains new ICE ufrag and
2215 // password that indicates the remote peer requests an ICE restart.
2216 // TODO(deadbeef): When we start storing both the current and pending
2217 // remote description, this should reset pending_ice_restarts and compare
2218 // against the current description.
2219 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2220 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002221 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002222 pending_ice_restarts_.insert(content.name);
2223 }
2224 } else {
2225 // We retain all received candidates only if ICE is not restarted.
2226 // When ICE is restarted, all previous candidates belong to an old
2227 // generation and should not be kept.
2228 // TODO(deadbeef): This goes against the W3C spec which says the remote
2229 // description should only contain candidates from the last set remote
2230 // description plus any candidates added since then. We should remove
2231 // this once we're sure it won't break anything.
2232 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2233 old_remote_description, content.name, mutable_remote_description());
2234 }
2235 }
2236 }
2237
2238 if (session_error() != SessionError::kNone) {
2239 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2240 }
2241
2242 // Set the the ICE connection state to connecting since the connection may
2243 // become writable with peer reflexive candidates before any remote candidate
2244 // is signaled.
2245 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2246 // is to have a new signal the indicates a change in checking state from the
2247 // transport and expose a new checking() member from transport that can be
2248 // read to determine the current checking state. The existing SignalConnecting
2249 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002250 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002251 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2252 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2253 }
2254
deadbeefab9b2d12015-10-14 11:33:11 -07002255 // If setting the description decided our SSL role, allocate any necessary
2256 // SCTP sids.
2257 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002258 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002259 AllocateSctpSids(role);
2260 }
2261
Steve Antondcc3c022017-12-22 16:02:54 -08002262 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002263 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2264 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002265 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002266 for (auto transceiver : transceivers_) {
2267 const ContentInfo* content =
2268 FindMediaSectionForTransceiver(transceiver, remote_description());
2269 if (!content) {
2270 continue;
2271 }
2272 const MediaContentDescription* media_desc = content->media_description();
2273 RtpTransceiverDirection local_direction =
2274 RtpTransceiverDirectionReversed(media_desc->direction());
2275 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2276 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2277 // transceiver's current direction is neither sendrecv nor recvonly,
2278 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002279 //
2280 // Create a sync label in the case of an unsignalled msid.
2281 std::string sync_label = rtc::CreateRandomUuid();
2282 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002283 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002284 if (!stream_params.stream_ids().empty()) {
2285 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002286 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002287 }
Steve Antondcc3c022017-12-22 16:02:54 -08002288 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2289 (!transceiver->current_direction() ||
2290 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002291 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002292 rtc::scoped_refptr<MediaStreamInterface> stream =
2293 remote_streams_->find(sync_label);
2294 if (!stream) {
2295 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2296 MediaStream::Create(sync_label));
2297 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002298 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002299 }
2300 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002301 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002302 }
2303 // If direction is sendonly or inactive, and transceiver's current
2304 // direction is neither sendonly nor inactive, process the removal of a
2305 // remote track for the media description.
2306 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002307 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002308 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002309 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002310 }
2311 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2312 transceiver->internal()->set_current_direction(local_direction);
2313 }
2314 if (content->rejected && !transceiver->stopped()) {
2315 transceiver->Stop();
2316 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002317 if (!content->rejected &&
2318 RtpTransceiverDirectionHasRecv(local_direction)) {
2319 // Set ssrc to 0 in the case of an unsignalled ssrc.
2320 uint32_t ssrc = 0;
2321 if (!media_desc->streams().empty()) {
2322 ssrc = media_desc->streams()[0].first_ssrc();
2323 }
2324 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002325 }
Steve Antondcc3c022017-12-22 16:02:54 -08002326 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002327 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002328 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002329 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002330 observer_->OnTrack(transceiver);
2331 observer_->OnAddTrack(transceiver->receiver(),
2332 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002333 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002334 for (auto stream : added_streams) {
2335 observer_->OnAddStream(stream);
2336 }
Steve Antondcc3c022017-12-22 16:02:54 -08002337 }
2338
Henrik Boströmfdb92012017-11-09 19:55:44 +01002339 const cricket::ContentInfo* audio_content =
2340 GetFirstAudioContent(remote_description()->description());
2341 const cricket::ContentInfo* video_content =
2342 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002343 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002344 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002345 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002346 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002347 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002348 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002349
2350 // Check if the descriptions include streams, just in case the peer supports
2351 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002352 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002353 (audio_desc && !audio_desc->streams().empty()) ||
2354 (video_desc && !video_desc->streams().empty())) {
2355 remote_peer_supports_msid_ = true;
2356 }
deadbeefab9b2d12015-10-14 11:33:11 -07002357
2358 // We wait to signal new streams until we finish processing the description,
2359 // since only at that point will new streams have all their tracks.
2360 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2361
Steve Antondcc3c022017-12-22 16:02:54 -08002362 if (!IsUnifiedPlan()) {
2363 // TODO(steveanton): When removing RTP senders/receivers in response to a
2364 // rejected media section, there is some cleanup logic that expects the
2365 // voice/ video channel to still be set. But in this method the voice/video
2366 // channel would have been destroyed by the SetRemoteDescription caller
2367 // above so the cleanup that relies on them fails to run. The RemoveSenders
2368 // calls should be moved to right before the DestroyChannel calls to fix
2369 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002370
Steve Antondcc3c022017-12-22 16:02:54 -08002371 // Find all audio rtp streams and create corresponding remote AudioTracks
2372 // and MediaStreams.
2373 if (audio_content) {
2374 if (audio_content->rejected) {
2375 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2376 } else {
2377 bool default_audio_track_needed =
2378 !remote_peer_supports_msid_ &&
2379 RtpTransceiverDirectionHasSend(audio_desc->direction());
2380 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2381 default_audio_track_needed, audio_desc->type(),
2382 new_streams);
2383 }
deadbeeffaac4972015-11-12 15:33:07 -08002384 }
deadbeefab9b2d12015-10-14 11:33:11 -07002385
Steve Antondcc3c022017-12-22 16:02:54 -08002386 // Find all video rtp streams and create corresponding remote VideoTracks
2387 // and MediaStreams.
2388 if (video_content) {
2389 if (video_content->rejected) {
2390 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2391 } else {
2392 bool default_video_track_needed =
2393 !remote_peer_supports_msid_ &&
2394 RtpTransceiverDirectionHasSend(video_desc->direction());
2395 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2396 default_video_track_needed, video_desc->type(),
2397 new_streams);
2398 }
deadbeeffaac4972015-11-12 15:33:07 -08002399 }
deadbeefab9b2d12015-10-14 11:33:11 -07002400
Steve Antondcc3c022017-12-22 16:02:54 -08002401 // Update the DataChannels with the information from the remote peer.
2402 if (data_desc) {
2403 if (rtc::starts_with(data_desc->protocol().data(),
2404 cricket::kMediaProtocolRtpPrefix)) {
2405 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2406 }
deadbeefab9b2d12015-10-14 11:33:11 -07002407 }
deadbeefab9b2d12015-10-14 11:33:11 -07002408
Steve Antondcc3c022017-12-22 16:02:54 -08002409 // Iterate new_streams and notify the observer about new MediaStreams.
2410 for (size_t i = 0; i < new_streams->count(); ++i) {
2411 MediaStreamInterface* new_stream = new_streams->at(i);
2412 stats_->AddStream(new_stream);
2413 observer_->OnAddStream(
2414 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2415 }
deadbeefab9b2d12015-10-14 11:33:11 -07002416
Steve Antondcc3c022017-12-22 16:02:54 -08002417 UpdateEndedRemoteMediaStreams();
2418 }
deadbeefab9b2d12015-10-14 11:33:11 -07002419
Steve Anton8a006912017-12-04 15:25:56 -08002420 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002421}
2422
Steve Antondcc3c022017-12-22 16:02:54 -08002423RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2424 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002425 const SessionDescriptionInterface& new_session,
2426 const SessionDescriptionInterface* old_local_description,
2427 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002428 RTC_DCHECK(IsUnifiedPlan());
2429
Steve Anton7464fca2018-01-19 11:10:37 -08002430 const cricket::ContentGroup* bundle_group = nullptr;
2431 if (new_session.GetType() == SdpType::kOffer) {
2432 auto bundle_group_or_error =
2433 GetEarlyBundleGroup(*new_session.description());
2434 if (!bundle_group_or_error.ok()) {
2435 return bundle_group_or_error.MoveError();
2436 }
2437 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002438 }
Steve Antondcc3c022017-12-22 16:02:54 -08002439
Steve Antondcc3c022017-12-22 16:02:54 -08002440 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002441 for (size_t i = 0; i < new_contents.size(); ++i) {
2442 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002443 cricket::MediaType media_type = new_content.media_description()->type();
2444 seen_mids_.insert(new_content.name);
2445 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2446 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002447 const cricket::ContentInfo* old_local_content = nullptr;
2448 if (old_local_description &&
2449 i < old_local_description->description()->contents().size()) {
2450 old_local_content =
2451 &old_local_description->description()->contents()[i];
2452 }
2453 const cricket::ContentInfo* old_remote_content = nullptr;
2454 if (old_remote_description &&
2455 i < old_remote_description->description()->contents().size()) {
2456 old_remote_content =
2457 &old_remote_description->description()->contents()[i];
2458 }
Steve Antondcc3c022017-12-22 16:02:54 -08002459 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002460 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2461 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002462 if (!transceiver_or_error.ok()) {
2463 return transceiver_or_error.MoveError();
2464 }
2465 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002466 RTCError error =
2467 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2468 if (!error.ok()) {
2469 return error;
2470 }
2471 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002472 if (GetDataMid() && new_content.name != *GetDataMid()) {
2473 // Ignore all but the first data section.
2474 continue;
2475 }
2476 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2477 if (!error.ok()) {
2478 return error;
2479 }
Steve Antondcc3c022017-12-22 16:02:54 -08002480 } else {
2481 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2482 "Unknown section type.");
2483 }
2484 }
2485
2486 return RTCError::OK();
2487}
2488
2489RTCError PeerConnection::UpdateTransceiverChannel(
2490 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2491 transceiver,
2492 const cricket::ContentInfo& content,
2493 const cricket::ContentGroup* bundle_group) {
2494 RTC_DCHECK(IsUnifiedPlan());
2495 RTC_DCHECK(transceiver);
2496 cricket::BaseChannel* channel = transceiver->internal()->channel();
2497 if (content.rejected) {
2498 if (channel) {
2499 transceiver->internal()->SetChannel(nullptr);
2500 DestroyBaseChannel(channel);
2501 }
2502 } else {
2503 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002504 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002505 channel = CreateVoiceChannel(
2506 content.name,
2507 GetTransportNameForMediaSection(content.name, bundle_group));
2508 } else {
Steve Anton69470252018-02-09 11:43:08 -08002509 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002510 channel = CreateVideoChannel(
2511 content.name,
2512 GetTransportNameForMediaSection(content.name, bundle_group));
2513 }
2514 if (!channel) {
2515 LOG_AND_RETURN_ERROR(
2516 RTCErrorType::INTERNAL_ERROR,
2517 "Failed to create channel for mid=" + content.name);
2518 }
2519 transceiver->internal()->SetChannel(channel);
2520 }
2521 }
2522 return RTCError::OK();
2523}
2524
Steve Antonfa2260d2017-12-28 16:38:23 -08002525RTCError PeerConnection::UpdateDataChannel(
2526 cricket::ContentSource source,
2527 const cricket::ContentInfo& content,
2528 const cricket::ContentGroup* bundle_group) {
2529 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002530 // If data channels are disabled, ignore this media section. CreateAnswer
2531 // will take care of rejecting it.
2532 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002533 }
2534 if (content.rejected) {
2535 DestroyDataChannel();
2536 } else {
2537 if (!rtp_data_channel_ && !sctp_transport_) {
2538 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2539 content.name, bundle_group))) {
2540 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2541 "Failed to create data channel.");
2542 }
2543 }
2544 if (source == cricket::CS_REMOTE) {
2545 const MediaContentDescription* data_desc = content.media_description();
2546 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2547 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2548 }
2549 }
2550 }
2551 return RTCError::OK();
2552}
2553
Steve Antondcc3c022017-12-22 16:02:54 -08002554RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2555PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002556 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002557 size_t mline_index,
2558 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002559 const ContentInfo* old_local_content,
2560 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002561 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002562 // If this is an offer then the m= section might be recycled. If the m=
2563 // section is being recycled (defined as: rejected in the current local or
2564 // remote description and not rejected in new description), dissociate the
2565 // currently associated RtpTransceiver by setting its mid property to null,
2566 // and discard the mapping between the transceiver and its m= section index.
2567 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2568 old_remote_content)) {
2569 // We want to dissociate the transceiver that has the rejected mid.
2570 const std::string& old_mid =
2571 (old_local_content && old_local_content->rejected)
2572 ? old_local_content->name
2573 : old_remote_content->name;
2574 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002575 if (old_transceiver) {
2576 old_transceiver->internal()->set_mid(rtc::nullopt);
2577 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2578 }
2579 }
2580 const MediaContentDescription* media_desc = content.media_description();
2581 auto transceiver = GetAssociatedTransceiver(content.name);
2582 if (source == cricket::CS_LOCAL) {
2583 // Find the RtpTransceiver that corresponds to this m= section, using the
2584 // mapping between transceivers and m= section indices established when
2585 // creating the offer.
2586 if (!transceiver) {
2587 transceiver = GetTransceiverByMLineIndex(mline_index);
2588 }
2589 if (!transceiver) {
2590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2591 "Unknown transceiver");
2592 }
2593 } else {
2594 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2595 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2596 // of the same type...
2597 if (!transceiver &&
2598 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2599 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2600 }
2601 // If no RtpTransceiver was found in the previous step, create one with a
2602 // recvonly direction.
2603 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002604 auto sender =
2605 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002606 std::string receiver_id;
2607 if (!media_desc->streams().empty()) {
2608 receiver_id = media_desc->streams()[0].id;
2609 } else {
2610 receiver_id = rtc::CreateRandomUuid();
2611 }
2612 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002613 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002614 transceiver->internal()->set_direction(
2615 RtpTransceiverDirection::kRecvOnly);
2616 }
2617 }
2618 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002619 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002620 LOG_AND_RETURN_ERROR(
2621 RTCErrorType::INVALID_PARAMETER,
2622 "Transceiver type does not match media description type.");
2623 }
2624 // Associate the found or created RtpTransceiver with the m= section by
2625 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2626 // section, and establish a mapping between the transceiver and the index of
2627 // the m= section.
2628 transceiver->internal()->set_mid(content.name);
2629 transceiver->internal()->set_mline_index(mline_index);
2630 return std::move(transceiver);
2631}
2632
2633rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2634PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2635 RTC_DCHECK(IsUnifiedPlan());
2636 for (auto transceiver : transceivers_) {
2637 if (transceiver->mid() == mid) {
2638 return transceiver;
2639 }
2640 }
2641 return nullptr;
2642}
2643
2644rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2645PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2646 RTC_DCHECK(IsUnifiedPlan());
2647 for (auto transceiver : transceivers_) {
2648 if (transceiver->internal()->mline_index() == mline_index) {
2649 return transceiver;
2650 }
2651 }
2652 return nullptr;
2653}
2654
2655rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2656PeerConnection::FindAvailableTransceiverToReceive(
2657 cricket::MediaType media_type) const {
2658 RTC_DCHECK(IsUnifiedPlan());
2659 // From JSEP section 5.10 (Applying a Remote Description):
2660 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2661 // the same type that were added to the PeerConnection by addTrack and are not
2662 // associated with any m= section and are not stopped, find the first such
2663 // RtpTransceiver.
2664 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002665 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002666 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2667 !transceiver->stopped()) {
2668 return transceiver;
2669 }
2670 }
2671 return nullptr;
2672}
2673
Steve Antoned10bd92017-12-05 10:52:59 -08002674const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2675 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2676 transceiver,
2677 const SessionDescriptionInterface* sdesc) const {
2678 RTC_DCHECK(transceiver);
2679 RTC_DCHECK(sdesc);
2680 if (IsUnifiedPlan()) {
2681 if (!transceiver->internal()->mid()) {
2682 // This transceiver is not associated with a media section yet.
2683 return nullptr;
2684 }
2685 return sdesc->description()->GetContentByName(
2686 *transceiver->internal()->mid());
2687 } else {
2688 // Plan B only allows at most one audio and one video section, so use the
2689 // first media section of that type.
2690 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002691 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002692 }
2693}
2694
deadbeef46c73892016-11-16 19:42:04 -08002695PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2696 return configuration_;
2697}
2698
deadbeef293e9262017-01-11 12:28:30 -08002699bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2700 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002701 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002702
Steve Anton75737c02017-11-06 10:37:17 -08002703 if (local_description() && configuration.ice_candidate_pool_size !=
2704 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002705 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2706 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002707 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002708 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002709
deadbeef293e9262017-01-11 12:28:30 -08002710 // The simplest (and most future-compatible) way to tell if the config was
2711 // modified in an invalid way is to copy each property we do support
2712 // modifying, then use operator==. There are far more properties we don't
2713 // support modifying than those we do, and more could be added.
2714 RTCConfiguration modified_config = configuration_;
2715 modified_config.servers = configuration.servers;
2716 modified_config.type = configuration.type;
2717 modified_config.ice_candidate_pool_size =
2718 configuration.ice_candidate_pool_size;
2719 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002720 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002721 modified_config.ice_check_interval_strong_connectivity =
2722 configuration.ice_check_interval_strong_connectivity;
2723 modified_config.ice_check_interval_weak_connectivity =
2724 configuration.ice_check_interval_weak_connectivity;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002725 modified_config.stun_candidate_keepalive_interval =
2726 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002727 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002728 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002729 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002730 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002731 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2732 }
2733
Steve Anton038834f2017-07-14 15:59:59 -07002734 // Validate the modified configuration.
2735 RTCError validate_error = ValidateConfiguration(modified_config);
2736 if (!validate_error.ok()) {
2737 return SafeSetError(std::move(validate_error), error);
2738 }
2739
deadbeef293e9262017-01-11 12:28:30 -08002740 // Note that this isn't possible through chromium, since it's an unsigned
2741 // short in WebIDL.
2742 if (configuration.ice_candidate_pool_size < 0 ||
2743 configuration.ice_candidate_pool_size > UINT16_MAX) {
2744 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2745 }
2746
2747 // Parse ICE servers before hopping to network thread.
2748 cricket::ServerAddresses stun_servers;
2749 std::vector<cricket::RelayServerConfig> turn_servers;
2750 RTCErrorType parse_error =
2751 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2752 if (parse_error != RTCErrorType::NONE) {
2753 return SafeSetError(parse_error, error);
2754 }
2755
2756 // In theory this shouldn't fail.
2757 if (!network_thread()->Invoke<bool>(
2758 RTC_FROM_HERE,
2759 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2760 stun_servers, turn_servers, modified_config.type,
2761 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002762 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002763 modified_config.turn_customizer,
2764 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002765 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002766 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2767 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002768
deadbeefd1a38b52016-12-10 13:15:33 -08002769 // As described in JSEP, calling setConfiguration with new ICE servers or
2770 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2771 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002772 if (modified_config.servers != configuration_.servers ||
2773 modified_config.type != configuration_.type ||
2774 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002775 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002776 }
skvladd1f5fda2017-02-03 16:54:05 -08002777
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002778 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002779
deadbeef293e9262017-01-11 12:28:30 -08002780 configuration_ = modified_config;
2781 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002782}
2783
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784bool PeerConnection::AddIceCandidate(
2785 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002786 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002787 if (IsClosed()) {
2788 return false;
2789 }
Steve Antond25da372017-11-06 14:50:29 -08002790
2791 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002792 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002793 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002794 return false;
2795 }
2796
2797 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002798 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002799 return false;
2800 }
2801
2802 bool valid = false;
2803 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2804 if (!valid) {
2805 return false;
2806 }
2807
2808 // Add this candidate to the remote session description.
2809 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002810 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002811 return false;
2812 }
2813
2814 if (ready) {
2815 return UseCandidate(ice_candidate);
2816 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002817 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002818 return true;
2819 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820}
2821
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002822bool PeerConnection::RemoveIceCandidates(
2823 const std::vector<cricket::Candidate>& candidates) {
2824 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002825 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002826 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002827 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002828 return false;
2829 }
2830
2831 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002832 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002833 return false;
2834 }
2835
2836 size_t number_removed =
2837 mutable_remote_description()->RemoveCandidates(candidates);
2838 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002839 RTC_LOG(LS_ERROR)
2840 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002841 "Requested "
2842 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002843 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002844 }
2845
2846 // Remove the candidates from the transport controller.
2847 std::string error;
2848 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2849 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002850 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002851 }
2852 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002853}
2854
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002855void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002856 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002857 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002858
Steve Anton75737c02017-11-06 10:37:17 -08002859 if (transport_controller()) {
2860 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002861 }
2862
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002863 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002864 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002865 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002866 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002867 uma_observer_->IncrementEnumCounter(
2868 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2869 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002870 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002871 uma_observer_->IncrementEnumCounter(
2872 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2873 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002874 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002875 // Send information about the requested SDP semantics.
2876 switch (configuration_.sdp_semantics) {
2877 case SdpSemantics::kDefault:
2878 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2879 kSdpSemanticRequestDefault,
2880 kSdpSemanticRequestMax);
2881
2882 break;
2883 case SdpSemantics::kPlanB:
2884 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2885 kSdpSemanticRequestPlanB,
2886 kSdpSemanticRequestMax);
2887 break;
2888 case SdpSemantics::kUnifiedPlan:
2889 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2890 kSdpSemanticRequestUnifiedPlan,
2891 kSdpSemanticRequestMax);
2892 break;
2893 default:
2894 RTC_NOTREACHED();
2895 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002896 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002897}
2898
zstein4b979802017-06-02 14:37:37 -07002899RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002900 if (!worker_thread()->IsCurrent()) {
2901 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002902 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2903 }
2904
2905 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2906 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2907 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2908 if (has_min && *bitrate.min_bitrate_bps < 0) {
2909 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2910 "min_bitrate_bps <= 0");
2911 }
2912 if (has_current) {
2913 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2914 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2915 "current_bitrate_bps < min_bitrate_bps");
2916 } else if (*bitrate.current_bitrate_bps < 0) {
2917 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2918 "curent_bitrate_bps < 0");
2919 }
2920 }
2921 if (has_max) {
2922 if (has_current &&
2923 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2924 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2925 "max_bitrate_bps < current_bitrate_bps");
2926 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2927 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2928 "max_bitrate_bps < min_bitrate_bps");
2929 } else if (*bitrate.max_bitrate_bps < 0) {
2930 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2931 "max_bitrate_bps < 0");
2932 }
2933 }
2934
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002935 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002936 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2937 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2938 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2939
2940 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002941 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002942
2943 return RTCError::OK();
2944}
2945
Alex Narest78609d52017-10-20 10:37:47 +02002946void PeerConnection::SetBitrateAllocationStrategy(
2947 std::unique_ptr<rtc::BitrateAllocationStrategy>
2948 bitrate_allocation_strategy) {
2949 rtc::Thread* worker_thread = factory_->worker_thread();
2950 if (!worker_thread->IsCurrent()) {
2951 rtc::BitrateAllocationStrategy* strategy_raw =
2952 bitrate_allocation_strategy.release();
2953 auto functor = [this, strategy_raw]() {
2954 call_->SetBitrateAllocationStrategy(
2955 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2956 };
2957 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2958 return;
2959 }
2960 RTC_DCHECK(call_.get());
2961 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2962}
2963
henrika5f6bf242017-11-01 11:06:56 +01002964void PeerConnection::SetAudioPlayout(bool playout) {
2965 if (!worker_thread()->IsCurrent()) {
2966 worker_thread()->Invoke<void>(
2967 RTC_FROM_HERE,
2968 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2969 return;
2970 }
2971 auto audio_state =
2972 factory_->channel_manager()->media_engine()->GetAudioState();
2973 audio_state->SetPlayout(playout);
2974}
2975
2976void PeerConnection::SetAudioRecording(bool recording) {
2977 if (!worker_thread()->IsCurrent()) {
2978 worker_thread()->Invoke<void>(
2979 RTC_FROM_HERE,
2980 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2981 return;
2982 }
2983 auto audio_state =
2984 factory_->channel_manager()->media_engine()->GetAudioState();
2985 audio_state->SetRecording(recording);
2986}
2987
Steve Anton8c0f7a72017-10-03 10:03:10 -07002988std::unique_ptr<rtc::SSLCertificate>
2989PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002990 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2991 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002992 return nullptr;
2993 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002994 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002995}
2996
Zhi Huang70b820f2018-01-27 14:16:15 -08002997std::unique_ptr<rtc::SSLCertChain>
2998PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002999 auto audio_transceiver = GetFirstAudioTransceiver();
3000 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003001 return nullptr;
3002 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003003 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003004 audio_transceiver->internal()->channel()->transport_name());
3005}
3006
3007rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3008PeerConnection::GetFirstAudioTransceiver() const {
3009 for (auto transceiver : transceivers_) {
3010 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3011 return transceiver;
3012 }
3013 }
3014 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003015}
3016
ivoc14d5dbe2016-07-04 07:06:55 -07003017bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3018 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003019 // TODO(eladalon): It would be better to not allow negative values into PC.
3020 const size_t max_size = (max_size_bytes < 0)
3021 ? RtcEventLog::kUnlimitedOutput
3022 : rtc::saturated_cast<size_t>(max_size_bytes);
3023 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003024 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3025 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003026}
3027
Bjorn Tereliusde939432017-11-20 17:38:14 +01003028bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3029 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003030 // TODO(eladalon): In C++14, this can be done with a lambda.
3031 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003032 bool operator()() {
3033 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3034 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003035 PeerConnection* const pc;
3036 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003037 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003038 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003039 return worker_thread()->Invoke<bool>(
3040 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003041}
3042
3043void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003044 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003045 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3046}
3047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003049 return pending_local_description_ ? pending_local_description_.get()
3050 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003051}
3052
3053const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003054 return pending_remote_description_ ? pending_remote_description_.get()
3055 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056}
3057
deadbeeffe4a8a42016-12-20 17:56:17 -08003058const SessionDescriptionInterface* PeerConnection::current_local_description()
3059 const {
Steve Anton75737c02017-11-06 10:37:17 -08003060 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003061}
3062
3063const SessionDescriptionInterface* PeerConnection::current_remote_description()
3064 const {
Steve Anton75737c02017-11-06 10:37:17 -08003065 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003066}
3067
3068const SessionDescriptionInterface* PeerConnection::pending_local_description()
3069 const {
Steve Anton75737c02017-11-06 10:37:17 -08003070 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003071}
3072
3073const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3074 const {
Steve Anton75737c02017-11-06 10:37:17 -08003075 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003076}
3077
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003079 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 // Update stats here so that we have the most recent stats for tracks and
3081 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003082 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083
Steve Anton75737c02017-11-06 10:37:17 -08003084 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003085
Steve Anton8af21862017-12-15 11:20:13 -08003086 for (auto transceiver : transceivers_) {
3087 transceiver->Stop();
3088 }
3089 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003090
Qingsi Wang93a84392018-01-30 17:13:09 -08003091 // The event log is used in the transport controller, which must be outlived
3092 // by the former. CreateOffer by the peer connection is implemented
3093 // asynchronously and if the peer connection is closed without resetting the
3094 // WebRTC session description factory, the session description factory would
3095 // call the transport controller.
3096 webrtc_session_desc_factory_.reset();
3097 transport_controller_.reset();
3098
deadbeef42a42632017-03-10 15:18:00 -08003099 network_thread()->Invoke<void>(
3100 RTC_FROM_HERE,
3101 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3102 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003103
Steve Anton978b8762017-09-29 12:15:02 -07003104 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003105 call_.reset();
3106 // The event log must outlive call (and any other object that uses it).
3107 event_log_.reset();
3108 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003109}
3110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003111void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003113 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3114 SetSessionDescriptionMsg* param =
3115 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3116 param->observer->OnSuccess();
3117 delete param;
3118 break;
3119 }
3120 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3121 SetSessionDescriptionMsg* param =
3122 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003123 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003124 delete param;
3125 break;
3126 }
deadbeefab9b2d12015-10-14 11:33:11 -07003127 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3128 CreateSessionDescriptionMsg* param =
3129 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003130 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003131 delete param;
3132 break;
3133 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134 case MSG_GETSTATS: {
3135 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003136 StatsReports reports;
3137 stats_->GetStats(param->track, &reports);
3138 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139 delete param;
3140 break;
3141 }
deadbeefbd292462015-12-14 18:15:29 -08003142 case MSG_FREE_DATACHANNELS: {
3143 sctp_data_channels_to_free_.clear();
3144 break;
3145 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003147 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148 break;
3149 }
3150}
3151
Steve Antonafb0bb72018-02-20 11:35:37 -08003152cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3153 RTC_DCHECK(!IsUnifiedPlan());
3154 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3155 GetAudioTransceiver()->internal()->channel());
3156 if (voice_channel) {
3157 return voice_channel->media_channel();
3158 } else {
3159 return nullptr;
3160 }
3161}
3162
3163cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3164 RTC_DCHECK(!IsUnifiedPlan());
3165 auto* video_channel = static_cast<cricket::VideoChannel*>(
3166 GetVideoTransceiver()->internal()->channel());
3167 if (video_channel) {
3168 return video_channel->media_channel();
3169 } else {
3170 return nullptr;
3171 }
3172}
3173
Steve Anton4171afb2017-11-20 10:20:22 -08003174void PeerConnection::CreateAudioReceiver(
3175 MediaStreamInterface* stream,
3176 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003177 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3178 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003179 auto* audio_receiver = new AudioRtpReceiver(
3180 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003181 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003182 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3183 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3184 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003185 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003186 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187}
3188
Steve Anton4171afb2017-11-20 10:20:22 -08003189void PeerConnection::CreateVideoReceiver(
3190 MediaStreamInterface* stream,
3191 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003192 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3193 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003194 auto* video_receiver = new VideoRtpReceiver(
3195 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003196 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003197 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3198 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3199 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003200 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003201 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202}
3203
deadbeef70ab1a12015-09-28 16:53:55 -07003204// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3205// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003206rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003207 const RtpSenderInfo& remote_sender_info) {
3208 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3209 if (!receiver) {
3210 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3211 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003212 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003213 }
Steve Anton4171afb2017-11-20 10:20:22 -08003214 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3215 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3216 } else {
3217 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3218 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003219 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003220}
3221
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003222void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3223 MediaStreamInterface* stream) {
3224 RTC_DCHECK(!IsClosed());
3225 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003226 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003227 // We already have a sender for this track, so just change the stream_id
3228 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003229 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003230 return;
3231 }
3232
3233 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003234 auto new_sender =
3235 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003236 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003237 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003238 // If the sender has already been configured in SDP, we call SetSsrc,
3239 // which will connect the sender to the underlying transport. This can
3240 // occur if a local session description that contains the ID of the sender
3241 // is set before AddStream is called. It can also occur if the local
3242 // session description is not changed and RemoveStream is called, and
3243 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003244 const RtpSenderInfo* sender_info =
3245 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3246 if (sender_info) {
3247 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003248 }
3249}
3250
3251// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3252// indefinitely, when we have unified plan SDP.
3253void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3254 MediaStreamInterface* stream) {
3255 RTC_DCHECK(!IsClosed());
3256 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003257 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003258 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3259 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003260 return;
3261 }
Steve Anton4171afb2017-11-20 10:20:22 -08003262 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003263}
3264
3265void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3266 MediaStreamInterface* stream) {
3267 RTC_DCHECK(!IsClosed());
3268 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003269 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003270 // We already have a sender for this track, so just change the stream_id
3271 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003272 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003273 return;
3274 }
3275
3276 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003277 auto new_sender =
3278 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003279 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003280 GetVideoTransceiver()->internal()->AddSender(new_sender);
3281 const RtpSenderInfo* sender_info =
3282 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3283 if (sender_info) {
3284 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003285 }
3286}
3287
3288void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3289 MediaStreamInterface* stream) {
3290 RTC_DCHECK(!IsClosed());
3291 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003292 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003293 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3294 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003295 return;
3296 }
Steve Anton4171afb2017-11-20 10:20:22 -08003297 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003298}
3299
Steve Antonba818672017-11-06 10:21:57 -08003300void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003301 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003302 if (ice_connection_state_ == new_state) {
3303 return;
3304 }
3305
deadbeefcbecd352015-09-23 11:50:27 -07003306 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003307 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003308 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003309 return;
3310 }
Steve Antonba818672017-11-06 10:21:57 -08003311
Mirko Bonadei675513b2017-11-09 11:09:25 +01003312 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3313 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003314 RTC_DCHECK(ice_connection_state_ !=
3315 PeerConnectionInterface::kIceConnectionClosed);
3316
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003318 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319}
3320
3321void PeerConnection::OnIceGatheringChange(
3322 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003323 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 if (IsClosed()) {
3325 return;
3326 }
3327 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003328 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329}
3330
jbauch81bf7b02017-03-25 08:31:12 -07003331void PeerConnection::OnIceCandidate(
3332 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003333 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003334 if (IsClosed()) {
3335 return;
3336 }
jbauch81bf7b02017-03-25 08:31:12 -07003337 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338}
3339
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003340void PeerConnection::OnIceCandidatesRemoved(
3341 const std::vector<cricket::Candidate>& candidates) {
3342 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003343 if (IsClosed()) {
3344 return;
3345 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003346 observer_->OnIceCandidatesRemoved(candidates);
3347}
3348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349void PeerConnection::ChangeSignalingState(
3350 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003351 RTC_DCHECK(signaling_thread()->IsCurrent());
3352 if (signaling_state_ == signaling_state) {
3353 return;
3354 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003355 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3356 << GetSignalingStateString(signaling_state_)
3357 << " New state: "
3358 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003359 signaling_state_ = signaling_state;
3360 if (signaling_state == kClosed) {
3361 ice_connection_state_ = kIceConnectionClosed;
3362 observer_->OnIceConnectionChange(ice_connection_state_);
3363 if (ice_gathering_state_ != kIceGatheringComplete) {
3364 ice_gathering_state_ = kIceGatheringComplete;
3365 observer_->OnIceGatheringChange(ice_gathering_state_);
3366 }
3367 }
3368 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369}
3370
deadbeefeb459812015-12-15 19:24:43 -08003371void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3372 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003373 if (IsClosed()) {
3374 return;
3375 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003376 AddAudioTrack(track, stream);
3377 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003378}
3379
deadbeefeb459812015-12-15 19:24:43 -08003380void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3381 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003382 if (IsClosed()) {
3383 return;
3384 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003385 RemoveAudioTrack(track, stream);
3386 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003387}
3388
3389void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3390 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003391 if (IsClosed()) {
3392 return;
3393 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003394 AddVideoTrack(track, stream);
3395 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003396}
3397
3398void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3399 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003400 if (IsClosed()) {
3401 return;
3402 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003403 RemoveVideoTrack(track, stream);
3404 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003405}
3406
Henrik Boström31638672017-11-23 17:48:32 +01003407void PeerConnection::PostSetSessionDescriptionSuccess(
3408 SetSessionDescriptionObserver* observer) {
3409 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3410 signaling_thread()->Post(RTC_FROM_HERE, this,
3411 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3412}
3413
deadbeefab9b2d12015-10-14 11:33:11 -07003414void PeerConnection::PostSetSessionDescriptionFailure(
3415 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003416 RTCError&& error) {
3417 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003418 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003419 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003420 signaling_thread()->Post(RTC_FROM_HERE, this,
3421 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003422}
3423
3424void PeerConnection::PostCreateSessionDescriptionFailure(
3425 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003426 RTCError error) {
3427 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003428 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003429 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003430 signaling_thread()->Post(RTC_FROM_HERE, this,
3431 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003432}
3433
zhihuang1c378ed2017-08-17 14:10:50 -07003434void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003435 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003436 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003437 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003438
Steve Antondcc3c022017-12-22 16:02:54 -08003439 if (IsUnifiedPlan()) {
3440 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3441 } else {
3442 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3443 }
3444
Steve Antonfa2260d2017-12-28 16:38:23 -08003445 // Intentionally unset the data channel type for RTP data channel with the
3446 // second condition. Otherwise the RTP data channels would be successfully
3447 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3448 // when building with chromium. We want to leave RTP data channels broken, so
3449 // people won't try to use them.
3450 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3451 session_options->data_channel_type = data_channel_type();
3452 }
3453
Steve Antondcc3c022017-12-22 16:02:54 -08003454 // Apply ICE restart flag and renomination flag.
3455 for (auto& options : session_options->media_description_options) {
3456 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3457 options.transport_options.enable_ice_renomination =
3458 configuration_.enable_ice_renomination;
3459 }
3460
3461 session_options->rtcp_cname = rtcp_cname_;
3462 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003463 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003464}
3465
3466void PeerConnection::GetOptionsForPlanBOffer(
3467 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3468 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003469 // Figure out transceiver directional preferences.
3470 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3471 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3472
3473 // By default, generate sendrecv/recvonly m= sections.
3474 bool recv_audio = true;
3475 bool recv_video = true;
3476
3477 // By default, only offer a new m= section if we have media to send with it.
3478 bool offer_new_audio_description = send_audio;
3479 bool offer_new_video_description = send_video;
3480 bool offer_new_data_description = HasDataChannels();
3481
3482 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003483 if (offer_answer_options.offer_to_receive_audio !=
3484 RTCOfferAnswerOptions::kUndefined) {
3485 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003486 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003487 offer_new_audio_description ||
3488 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003489 }
Steve Antondcc3c022017-12-22 16:02:54 -08003490 if (offer_answer_options.offer_to_receive_video !=
3491 RTCOfferAnswerOptions::kUndefined) {
3492 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003493 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003494 offer_new_video_description ||
3495 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003496 }
3497
3498 rtc::Optional<size_t> audio_index;
3499 rtc::Optional<size_t> video_index;
3500 rtc::Optional<size_t> data_index;
3501 // If a current description exists, generate m= sections in the same order,
3502 // using the first audio/video/data section that appears and rejecting
3503 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003504 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003505 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003506 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003507 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3508 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3509 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003510 }
3511
zhihuang1c378ed2017-08-17 14:10:50 -07003512 // Add audio/video/data m= sections to the end if needed.
3513 if (!audio_index && offer_new_audio_description) {
3514 session_options->media_description_options.push_back(
3515 cricket::MediaDescriptionOptions(
3516 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003517 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3518 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003519 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003520 }
zhihuang1c378ed2017-08-17 14:10:50 -07003521 if (!video_index && offer_new_video_description) {
3522 session_options->media_description_options.push_back(
3523 cricket::MediaDescriptionOptions(
3524 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003525 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3526 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003527 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003528 }
zhihuang1c378ed2017-08-17 14:10:50 -07003529 if (!data_index && offer_new_data_description) {
3530 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003531 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003532 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003533 }
3534
3535 cricket::MediaDescriptionOptions* audio_media_description_options =
3536 !audio_index ? nullptr
3537 : &session_options->media_description_options[*audio_index];
3538 cricket::MediaDescriptionOptions* video_media_description_options =
3539 !video_index ? nullptr
3540 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003541
Steve Anton4171afb2017-11-20 10:20:22 -08003542 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003543 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003544}
3545
3546// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3547// and return a reference to it.
3548// Generated MIDs should be no more than 3 bytes long to take up less space in
3549// the RTP packet.
3550static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3551 RTC_DCHECK(used_mids);
3552 // We're boring: just generate MIDs 0, 1, 2, ...
3553 size_t i = 0;
3554 std::set<std::string>::iterator it;
3555 bool inserted;
3556 do {
3557 std::string mid = rtc::ToString(i++);
3558 auto insert_result = used_mids->insert(mid);
3559 it = insert_result.first;
3560 inserted = insert_result.second;
3561 } while (!inserted);
3562 return *it;
3563}
3564
3565static cricket::MediaDescriptionOptions
3566GetMediaDescriptionOptionsForTransceiver(
3567 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3568 transceiver,
3569 const std::string& mid) {
3570 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003571 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003572 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003573 // This behavior is specified in JSEP. The gist is that:
3574 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3575 // sendrecv.
3576 // 2. If the MSID is included, then it must be included in any subsequent
3577 // offer/answer exactly the same until the RtpTransceiver is stopped.
3578 if (!transceiver->stopped() &&
3579 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3580 transceiver->internal()->has_ever_been_used_to_send())) {
3581 cricket::SenderOptions sender_options;
3582 sender_options.track_id = transceiver->sender()->id();
3583 sender_options.stream_ids = transceiver->sender()->stream_ids();
3584 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3585 // set in the RTP parameters when the transceiver was added.
3586 sender_options.num_sim_layers = 1;
3587 media_description_options.sender_options.push_back(sender_options);
3588 }
Steve Antondcc3c022017-12-22 16:02:54 -08003589 return media_description_options;
3590}
3591
3592void PeerConnection::GetOptionsForUnifiedPlanOffer(
3593 const RTCOfferAnswerOptions& offer_answer_options,
3594 cricket::MediaSessionOptions* session_options) {
3595 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3596 // Offers) and 5.2.2 (Subsequent Offers).
3597 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3598 const ContentInfos& local_contents =
3599 (local_description() ? local_description()->description()->contents()
3600 : ContentInfos());
3601 const ContentInfos& remote_contents =
3602 (remote_description() ? remote_description()->description()->contents()
3603 : ContentInfos());
3604 // The mline indices that can be recycled. New transceivers should reuse these
3605 // slots first.
3606 std::queue<size_t> recycleable_mline_indices;
3607 // Track the MIDs used in previous offer/answer exchanges and the current
3608 // offer so that new, unique MIDs are generated.
3609 std::set<std::string> used_mids = seen_mids_;
3610 // First, go through each media section that exists in either the local or
3611 // remote description and generate a media section in this offer for the
3612 // associated transceiver. If a media section can be recycled, generate a
3613 // default, rejected media section here that can be later overwritten.
3614 for (size_t i = 0;
3615 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3616 // Either |local_content| or |remote_content| is non-null.
3617 const ContentInfo* local_content =
3618 (i < local_contents.size() ? &local_contents[i] : nullptr);
3619 const ContentInfo* remote_content =
3620 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3621 bool had_been_rejected = (local_content && local_content->rejected) ||
3622 (remote_content && remote_content->rejected);
3623 const std::string& mid =
3624 (local_content ? local_content->name : remote_content->name);
3625 cricket::MediaType media_type =
3626 (local_content ? local_content->media_description()->type()
3627 : remote_content->media_description()->type());
3628 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3629 media_type == cricket::MEDIA_TYPE_VIDEO) {
3630 auto transceiver = GetAssociatedTransceiver(mid);
3631 RTC_CHECK(transceiver);
3632 // A media section is considered eligible for recycling if it is marked as
3633 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003634 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003635 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003636 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3637 RtpTransceiverDirection::kInactive,
3638 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003639 recycleable_mline_indices.push(i);
3640 } else {
3641 session_options->media_description_options.push_back(
3642 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3643 // CreateOffer shouldn't really cause any state changes in
3644 // PeerConnection, but we need a way to match new transceivers to new
3645 // media sections in SetLocalDescription and JSEP specifies this is done
3646 // by recording the index of the media section generated for the
3647 // transceiver in the offer.
3648 transceiver->internal()->set_mline_index(i);
3649 }
3650 } else {
3651 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003652 RTC_CHECK(GetDataMid());
3653 if (had_been_rejected || mid != *GetDataMid()) {
3654 session_options->media_description_options.push_back(
3655 GetMediaDescriptionOptionsForRejectedData(mid));
3656 } else {
3657 session_options->media_description_options.push_back(
3658 GetMediaDescriptionOptionsForActiveData(mid));
3659 }
Steve Antondcc3c022017-12-22 16:02:54 -08003660 }
3661 }
3662 // Next, look for transceivers that are newly added (that is, are not stopped
3663 // and not associated). Reuse media sections marked as recyclable first,
3664 // otherwise append to the end of the offer. New media sections should be
3665 // added in the order they were added to the PeerConnection.
3666 for (auto transceiver : transceivers_) {
3667 if (transceiver->mid() || transceiver->stopped()) {
3668 continue;
3669 }
3670 size_t mline_index;
3671 if (!recycleable_mline_indices.empty()) {
3672 mline_index = recycleable_mline_indices.front();
3673 recycleable_mline_indices.pop();
3674 session_options->media_description_options[mline_index] =
3675 GetMediaDescriptionOptionsForTransceiver(transceiver,
3676 AllocateMid(&used_mids));
3677 } else {
3678 mline_index = session_options->media_description_options.size();
3679 session_options->media_description_options.push_back(
3680 GetMediaDescriptionOptionsForTransceiver(transceiver,
3681 AllocateMid(&used_mids)));
3682 }
3683 // See comment above for why CreateOffer changes the transceiver's state.
3684 transceiver->internal()->set_mline_index(mline_index);
3685 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003686 // Lastly, add a m-section if we have local data channels and an m section
3687 // does not already exist.
3688 if (!GetDataMid() && HasDataChannels()) {
3689 session_options->media_description_options.push_back(
3690 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3691 }
Steve Antondcc3c022017-12-22 16:02:54 -08003692}
3693
3694void PeerConnection::GetOptionsForAnswer(
3695 const RTCOfferAnswerOptions& offer_answer_options,
3696 cricket::MediaSessionOptions* session_options) {
3697 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3698
3699 if (IsUnifiedPlan()) {
3700 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3701 } else {
3702 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3703 }
3704
Steve Antonfa2260d2017-12-28 16:38:23 -08003705 // Intentionally unset the data channel type for RTP data channel. Otherwise
3706 // the RTP data channels would be successfully negotiated by default and the
3707 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3708 // We want to leave RTP data channels broken, so people won't try to use them.
3709 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3710 session_options->data_channel_type = data_channel_type();
3711 }
3712
Steve Antondcc3c022017-12-22 16:02:54 -08003713 // Apply ICE renomination flag.
3714 for (auto& options : session_options->media_description_options) {
3715 options.transport_options.enable_ice_renomination =
3716 configuration_.enable_ice_renomination;
3717 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003718
3719 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003720 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003721 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003722}
3723
Steve Antondcc3c022017-12-22 16:02:54 -08003724void PeerConnection::GetOptionsForPlanBAnswer(
3725 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003726 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003727 // Figure out transceiver directional preferences.
3728 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3729 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3730
3731 // By default, generate sendrecv/recvonly m= sections. The direction is also
3732 // restricted by the direction in the offer.
3733 bool recv_audio = true;
3734 bool recv_video = true;
3735
3736 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003737 if (offer_answer_options.offer_to_receive_audio !=
3738 RTCOfferAnswerOptions::kUndefined) {
3739 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003740 }
Steve Antondcc3c022017-12-22 16:02:54 -08003741 if (offer_answer_options.offer_to_receive_video !=
3742 RTCOfferAnswerOptions::kUndefined) {
3743 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003744 }
3745
3746 rtc::Optional<size_t> audio_index;
3747 rtc::Optional<size_t> video_index;
3748 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003749
3750 // Generate m= sections that match those in the offer.
3751 // Note that mediasession.cc will handle intersection our preferred
3752 // direction with the offered direction.
3753 GenerateMediaDescriptionOptions(
3754 remote_description(),
3755 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3756 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3757 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003758
3759 cricket::MediaDescriptionOptions* audio_media_description_options =
3760 !audio_index ? nullptr
3761 : &session_options->media_description_options[*audio_index];
3762 cricket::MediaDescriptionOptions* video_media_description_options =
3763 !video_index ? nullptr
3764 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003765
Steve Anton4171afb2017-11-20 10:20:22 -08003766 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003767 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003768}
zhihuangaf388472016-11-02 16:49:48 -07003769
Steve Antondcc3c022017-12-22 16:02:54 -08003770void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3771 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3772 cricket::MediaSessionOptions* session_options) {
3773 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3774 // Answers) and 5.3.2 (Subsequent Answers).
3775 RTC_DCHECK(remote_description());
3776 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3777 for (const ContentInfo& content :
3778 remote_description()->description()->contents()) {
3779 cricket::MediaType media_type = content.media_description()->type();
3780 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3781 media_type == cricket::MEDIA_TYPE_VIDEO) {
3782 auto transceiver = GetAssociatedTransceiver(content.name);
3783 RTC_CHECK(transceiver);
3784 session_options->media_description_options.push_back(
3785 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3786 } else {
3787 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003788 // Reject all data sections if data channels are disabled.
3789 // Reject a data section if it has already been rejected.
3790 // Reject all data sections except for the first one.
3791 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3792 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003793 session_options->media_description_options.push_back(
3794 GetMediaDescriptionOptionsForRejectedData(content.name));
3795 } else {
3796 session_options->media_description_options.push_back(
3797 GetMediaDescriptionOptionsForActiveData(content.name));
3798 }
Steve Antondcc3c022017-12-22 16:02:54 -08003799 }
3800 }
htaa2a49d92016-03-04 02:51:39 -08003801}
3802
zhihuang1c378ed2017-08-17 14:10:50 -07003803void PeerConnection::GenerateMediaDescriptionOptions(
3804 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003805 RtpTransceiverDirection audio_direction,
3806 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003807 rtc::Optional<size_t>* audio_index,
3808 rtc::Optional<size_t>* video_index,
3809 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003810 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003811 for (const cricket::ContentInfo& content :
3812 session_desc->description()->contents()) {
3813 if (IsAudioContent(&content)) {
3814 // If we already have an audio m= section, reject this extra one.
3815 if (*audio_index) {
3816 session_options->media_description_options.push_back(
3817 cricket::MediaDescriptionOptions(
3818 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003819 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003820 } else {
3821 session_options->media_description_options.push_back(
3822 cricket::MediaDescriptionOptions(
3823 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003824 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003825 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003826 }
3827 } else if (IsVideoContent(&content)) {
3828 // If we already have an video m= section, reject this extra one.
3829 if (*video_index) {
3830 session_options->media_description_options.push_back(
3831 cricket::MediaDescriptionOptions(
3832 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003833 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003834 } else {
3835 session_options->media_description_options.push_back(
3836 cricket::MediaDescriptionOptions(
3837 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003838 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003839 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003840 }
3841 } else {
3842 RTC_DCHECK(IsDataContent(&content));
3843 // If we already have an data m= section, reject this extra one.
3844 if (*data_index) {
3845 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003846 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003847 } else {
3848 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003849 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003850 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003851 }
3852 }
htaa2a49d92016-03-04 02:51:39 -08003853 }
deadbeefab9b2d12015-10-14 11:33:11 -07003854}
3855
Steve Antonfa2260d2017-12-28 16:38:23 -08003856cricket::MediaDescriptionOptions
3857PeerConnection::GetMediaDescriptionOptionsForActiveData(
3858 const std::string& mid) const {
3859 // Direction for data sections is meaningless, but legacy endpoints might
3860 // expect sendrecv.
3861 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3862 RtpTransceiverDirection::kSendRecv,
3863 /*stopped=*/false);
3864 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3865 return options;
3866}
3867
3868cricket::MediaDescriptionOptions
3869PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3870 const std::string& mid) const {
3871 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3872 RtpTransceiverDirection::kInactive,
3873 /*stopped=*/true);
3874 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3875 return options;
3876}
3877
3878rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3879 switch (data_channel_type_) {
3880 case cricket::DCT_RTP:
3881 if (!rtp_data_channel_) {
3882 return rtc::nullopt;
3883 }
3884 return rtp_data_channel_->content_name();
3885 case cricket::DCT_SCTP:
3886 return sctp_content_name_;
3887 default:
3888 return rtc::nullopt;
3889 }
3890}
3891
Steve Anton4171afb2017-11-20 10:20:22 -08003892void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3893 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3894 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003895 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003896}
3897
Steve Anton4171afb2017-11-20 10:20:22 -08003898void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003899 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003900 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003901 cricket::MediaType media_type,
3902 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003903 std::vector<RtpSenderInfo>* current_senders =
3904 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003905
Steve Anton4171afb2017-11-20 10:20:22 -08003906 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003907 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003908 for (auto sender_it = current_senders->begin();
3909 sender_it != current_senders->end();
3910 /* incremented manually */) {
3911 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003912 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003913 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3914 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003915 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003916 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003917 sender_exists) {
3918 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003919 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003920 OnRemoteSenderRemoved(info, media_type);
3921 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003922 }
3923 }
3924
Steve Anton4171afb2017-11-20 10:20:22 -08003925 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003926 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08003927 // |params.id| is the sender id and the stream id uses the first of
3928 // |params.stream_ids|.
3929 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
3930 const std::string& stream_id =
3931 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003932 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003933 uint32_t ssrc = params.first_ssrc();
3934
3935 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003936 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003937 if (!stream) {
3938 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003939 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08003940 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07003941 remote_streams_->AddStream(stream);
3942 new_streams->AddStream(stream);
3943 }
3944
Steve Anton4171afb2017-11-20 10:20:22 -08003945 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08003946 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003947 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08003948 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08003949 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003950 }
3951 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003952
Steve Anton4171afb2017-11-20 10:20:22 -08003953 // Add default sender if necessary.
3954 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003955 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003956 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08003957 if (!default_stream) {
3958 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003959 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08003960 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08003961 remote_streams_->AddStream(default_stream);
3962 new_streams->AddStream(default_stream);
3963 }
Steve Anton4171afb2017-11-20 10:20:22 -08003964 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3965 ? kDefaultAudioSenderId
3966 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08003967 const RtpSenderInfo* default_sender_info =
3968 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003969 if (!default_sender_info) {
3970 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08003971 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08003972 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003973 }
3974 }
deadbeefab9b2d12015-10-14 11:33:11 -07003975}
3976
Steve Anton4171afb2017-11-20 10:20:22 -08003977void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3978 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003979 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003980
3981 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003982 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003983 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003984 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003985 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003986 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003987 }
3988}
3989
Steve Anton4171afb2017-11-20 10:20:22 -08003990void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3991 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003992 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003993
Henrik Boström933d8b02017-10-10 10:05:16 -07003994 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003995 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003996 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3997 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003998 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003999 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004000 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004001 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004002 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004003 }
4004 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004005 // Stopping or destroying a VideoRtpReceiver will end the
4006 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004007 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004008 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004009 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004010 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004011 // There's no guarantee the track is still available, e.g. the track may
4012 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004013 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004014 }
4015 } else {
nisseede5da42017-01-12 05:15:36 -08004016 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004017 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004018 if (receiver) {
4019 observer_->OnRemoveTrack(receiver);
4020 }
deadbeefab9b2d12015-10-14 11:33:11 -07004021}
4022
4023void PeerConnection::UpdateEndedRemoteMediaStreams() {
4024 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4025 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4026 MediaStreamInterface* stream = remote_streams_->at(i);
4027 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4028 streams_to_remove.push_back(stream);
4029 }
4030 }
4031
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004032 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004033 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004034 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004035 }
4036}
4037
Steve Anton4171afb2017-11-20 10:20:22 -08004038void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004039 const std::vector<cricket::StreamParams>& streams,
4040 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004041 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004042
Seth Hampson845e8782018-03-02 11:34:10 -08004043 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004044 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004045 for (auto sender_it = current_senders->begin();
4046 sender_it != current_senders->end();
4047 /* incremented manually */) {
4048 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004049 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004050 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4051 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004052 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004053 OnLocalSenderRemoved(info, media_type);
4054 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004055 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004056 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004057 }
4058 }
4059
Steve Anton4171afb2017-11-20 10:20:22 -08004060 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004061 for (const cricket::StreamParams& params : streams) {
4062 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004063 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004064 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004065 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004066 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004067 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08004068 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004069 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004070 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004071 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004072 }
4073 }
4074}
4075
Steve Anton4171afb2017-11-20 10:20:22 -08004076void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4077 cricket::MediaType media_type) {
4078 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004079 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004080 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4081 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004082 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004083 return;
4084 }
4085
deadbeeffac06552015-11-25 11:26:01 -08004086 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004087 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004088 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004089 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004090 }
deadbeeffac06552015-11-25 11:26:01 -08004091
Seth Hampson845e8782018-03-02 11:34:10 -08004092 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004093 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004094}
4095
Steve Anton4171afb2017-11-20 10:20:22 -08004096void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4097 cricket::MediaType media_type) {
4098 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004099 if (!sender) {
4100 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004101 // SessionDescriptions has been renegotiated.
4102 return;
4103 }
deadbeeffac06552015-11-25 11:26:01 -08004104
4105 // A sender has been removed from the SessionDescription but it's still
4106 // associated with the PeerConnection. This only occurs if the SDP doesn't
4107 // match with the calls to CreateSender, AddStream and RemoveStream.
4108 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004110 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004111 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004112 }
deadbeeffac06552015-11-25 11:26:01 -08004113
Steve Anton4171afb2017-11-20 10:20:22 -08004114 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004115}
4116
4117void PeerConnection::UpdateLocalRtpDataChannels(
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 // |it->sync_label| is actually the data channel label. The reason is that
4124 // we use the same naming of data channels as we do for
4125 // MediaStreams and Tracks.
4126 // For MediaStreams, the sync_label is the MediaStream label and the
4127 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004128 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004129 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004130 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004131 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004132 continue;
4133 }
4134 // Set the SSRC the data channel should use for sending.
4135 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4136 existing_channels.push_back(data_channel_it->first);
4137 }
4138
4139 UpdateClosingRtpDataChannels(existing_channels, true);
4140}
4141
4142void PeerConnection::UpdateRemoteRtpDataChannels(
4143 const cricket::StreamParamsVec& streams) {
4144 std::vector<std::string> existing_channels;
4145
4146 // Find new and active data channels.
4147 for (const cricket::StreamParams& params : streams) {
4148 // The data channel label is either the mslabel or the SSRC if the mslabel
4149 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004150 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004151 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004152 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004153 auto data_channel_it = rtp_data_channels_.find(label);
4154 if (data_channel_it == rtp_data_channels_.end()) {
4155 // This is a new data channel.
4156 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4157 } else {
4158 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4159 }
4160 existing_channels.push_back(label);
4161 }
4162
4163 UpdateClosingRtpDataChannels(existing_channels, false);
4164}
4165
4166void PeerConnection::UpdateClosingRtpDataChannels(
4167 const std::vector<std::string>& active_channels,
4168 bool is_local_update) {
4169 auto it = rtp_data_channels_.begin();
4170 while (it != rtp_data_channels_.end()) {
4171 DataChannel* data_channel = it->second;
4172 if (std::find(active_channels.begin(), active_channels.end(),
4173 data_channel->label()) != active_channels.end()) {
4174 ++it;
4175 continue;
4176 }
4177
4178 if (is_local_update) {
4179 data_channel->SetSendSsrc(0);
4180 } else {
4181 data_channel->RemotePeerRequestClose();
4182 }
4183
4184 if (data_channel->state() == DataChannel::kClosed) {
4185 rtp_data_channels_.erase(it);
4186 it = rtp_data_channels_.begin();
4187 } else {
4188 ++it;
4189 }
4190 }
4191}
4192
4193void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4194 uint32_t remote_ssrc) {
4195 rtc::scoped_refptr<DataChannel> channel(
4196 InternalCreateDataChannel(label, nullptr));
4197 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004198 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004199 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004200 return;
4201 }
4202 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004203 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4204 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004205 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004206}
4207
4208rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4209 const std::string& label,
4210 const InternalDataChannelInit* config) {
4211 if (IsClosed()) {
4212 return nullptr;
4213 }
Steve Anton75737c02017-11-06 10:37:17 -08004214 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004215 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004216 << "InternalCreateDataChannel: Data is not supported in this call.";
4217 return nullptr;
4218 }
4219 InternalDataChannelInit new_config =
4220 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004221 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004222 if (new_config.id < 0) {
4223 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004224 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004225 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004226 RTC_LOG(LS_ERROR)
4227 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004228 return nullptr;
4229 }
4230 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004231 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004232 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004233 return nullptr;
4234 }
4235 }
4236
Steve Anton75737c02017-11-06 10:37:17 -08004237 rtc::scoped_refptr<DataChannel> channel(
4238 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004239 if (!channel) {
4240 sid_allocator_.ReleaseSid(new_config.id);
4241 return nullptr;
4242 }
4243
4244 if (channel->data_channel_type() == cricket::DCT_RTP) {
4245 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004246 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4247 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004248 return nullptr;
4249 }
4250 rtp_data_channels_[channel->label()] = channel;
4251 } else {
4252 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4253 sctp_data_channels_.push_back(channel);
4254 channel->SignalClosed.connect(this,
4255 &PeerConnection::OnSctpDataChannelClosed);
4256 }
4257
Steve Anton2d8609c2018-01-23 16:38:46 -08004258 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004259 return channel;
4260}
4261
4262bool PeerConnection::HasDataChannels() const {
4263 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4264}
4265
4266void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4267 for (const auto& channel : sctp_data_channels_) {
4268 if (channel->id() < 0) {
4269 int sid;
4270 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004271 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004272 continue;
4273 }
4274 channel->SetSctpSid(sid);
4275 }
4276 }
4277}
4278
4279void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004280 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004281 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4282 ++it) {
4283 if (it->get() == channel) {
4284 if (channel->id() >= 0) {
4285 sid_allocator_.ReleaseSid(channel->id());
4286 }
deadbeefbd292462015-12-14 18:15:29 -08004287 // Since this method is triggered by a signal from the DataChannel,
4288 // we can't free it directly here; we need to free it asynchronously.
4289 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004290 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004291 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4292 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004293 return;
4294 }
4295 }
4296}
4297
deadbeefab9b2d12015-10-14 11:33:11 -07004298void PeerConnection::OnDataChannelDestroyed() {
4299 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4300 // DataChannel may callback to us and try to modify the list.
4301 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4302 temp_rtp_dcs.swap(rtp_data_channels_);
4303 for (const auto& kv : temp_rtp_dcs) {
4304 kv.second->OnTransportChannelDestroyed();
4305 }
4306
4307 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4308 temp_sctp_dcs.swap(sctp_data_channels_);
4309 for (const auto& channel : temp_sctp_dcs) {
4310 channel->OnTransportChannelDestroyed();
4311 }
4312}
4313
4314void PeerConnection::OnDataChannelOpenMessage(
4315 const std::string& label,
4316 const InternalDataChannelInit& config) {
4317 rtc::scoped_refptr<DataChannel> channel(
4318 InternalCreateDataChannel(label, &config));
4319 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004320 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004321 return;
4322 }
4323
deadbeefa601f5c2016-06-06 14:27:39 -07004324 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4325 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004326 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004327}
4328
Steve Anton4171afb2017-11-20 10:20:22 -08004329rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4330PeerConnection::GetAudioTransceiver() const {
4331 // This method only works with Plan B SDP, where there is a single
4332 // audio/video transceiver.
4333 RTC_DCHECK(!IsUnifiedPlan());
4334 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004335 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004336 return transceiver;
4337 }
4338 }
4339 RTC_NOTREACHED();
4340 return nullptr;
4341}
4342
4343rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4344PeerConnection::GetVideoTransceiver() const {
4345 // This method only works with Plan B SDP, where there is a single
4346 // audio/video transceiver.
4347 RTC_DCHECK(!IsUnifiedPlan());
4348 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004349 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004350 return transceiver;
4351 }
4352 }
4353 RTC_NOTREACHED();
4354 return nullptr;
4355}
4356
4357// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4358// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004359bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004360 switch (type) {
4361 case cricket::MEDIA_TYPE_AUDIO:
4362 return !GetAudioTransceiver()->internal()->senders().empty();
4363 case cricket::MEDIA_TYPE_VIDEO:
4364 return !GetVideoTransceiver()->internal()->senders().empty();
4365 case cricket::MEDIA_TYPE_DATA:
4366 return false;
4367 }
4368 RTC_NOTREACHED();
4369 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004370}
4371
Steve Anton4171afb2017-11-20 10:20:22 -08004372rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4373PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4374 for (auto transceiver : transceivers_) {
4375 for (auto sender : transceiver->internal()->senders()) {
4376 if (sender->track() == track) {
4377 return sender;
4378 }
4379 }
4380 }
4381 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004382}
4383
Steve Anton4171afb2017-11-20 10:20:22 -08004384rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4385PeerConnection::FindSenderById(const std::string& sender_id) const {
4386 for (auto transceiver : transceivers_) {
4387 for (auto sender : transceiver->internal()->senders()) {
4388 if (sender->id() == sender_id) {
4389 return sender;
4390 }
4391 }
4392 }
4393 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004394}
4395
Steve Anton4171afb2017-11-20 10:20:22 -08004396rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4397PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4398 for (auto transceiver : transceivers_) {
4399 for (auto receiver : transceiver->internal()->receivers()) {
4400 if (receiver->id() == receiver_id) {
4401 return receiver;
4402 }
4403 }
4404 }
4405 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004406}
4407
Steve Anton4171afb2017-11-20 10:20:22 -08004408std::vector<PeerConnection::RtpSenderInfo>*
4409PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4410 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4411 media_type == cricket::MEDIA_TYPE_VIDEO);
4412 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4413 ? &remote_audio_sender_infos_
4414 : &remote_video_sender_infos_;
4415}
4416
4417std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004418 cricket::MediaType media_type) {
4419 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4420 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004421 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4422 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004423}
4424
Steve Anton4171afb2017-11-20 10:20:22 -08004425const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4426 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Seth Hampson845e8782018-03-02 11:34:10 -08004427 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004428 const std::string sender_id) const {
4429 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson845e8782018-03-02 11:34:10 -08004430 if (sender_info.stream_id == stream_id &&
Steve Anton4171afb2017-11-20 10:20:22 -08004431 sender_info.sender_id == sender_id) {
4432 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004433 }
4434 }
4435 return nullptr;
4436}
4437
4438DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4439 for (const auto& channel : sctp_data_channels_) {
4440 if (channel->id() == sid) {
4441 return channel;
4442 }
4443 }
4444 return nullptr;
4445}
4446
deadbeef91dd5672016-05-18 16:55:30 -07004447bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004448 const RTCConfiguration& configuration) {
4449 cricket::ServerAddresses stun_servers;
4450 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004451 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4452 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004453 return false;
4454 }
4455
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004456 port_allocator_->Initialize();
4457
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004458 // To handle both internal and externally created port allocator, we will
4459 // enable BUNDLE here.
4460 int portallocator_flags = port_allocator_->flags();
4461 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004462 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4463 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004464 // If the disable-IPv6 flag was specified, we'll not override it
4465 // by experiment.
4466 if (configuration.disable_ipv6) {
4467 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004468 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4469 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004470 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4471 }
4472
zhihuangb09b3f92017-03-07 14:40:51 -08004473 if (configuration.disable_ipv6_on_wifi) {
4474 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004475 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004476 }
4477
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004478 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4479 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004480 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004481 }
4482
honghaiz60347052016-05-31 18:29:12 -07004483 if (configuration.candidate_network_policy ==
4484 kCandidateNetworkPolicyLowCost) {
4485 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004486 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004487 }
4488
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004489 if (configuration.disable_link_local_networks) {
4490 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4491 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4492 }
4493
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004494 port_allocator_->set_flags(portallocator_flags);
4495 // No step delay is used while allocating ports.
4496 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4497 port_allocator_->set_candidate_filter(
4498 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004499 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004500
4501 // Call this last since it may create pooled allocator sessions using the
4502 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004503 port_allocator_->SetConfiguration(
4504 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4505 configuration.prune_turn_ports, configuration.turn_customizer,
4506 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004507 return true;
4508}
4509
deadbeef91dd5672016-05-18 16:55:30 -07004510bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004511 const cricket::ServerAddresses& stun_servers,
4512 const std::vector<cricket::RelayServerConfig>& turn_servers,
4513 IceTransportsType type,
4514 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004515 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004516 webrtc::TurnCustomizer* turn_customizer,
4517 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004518 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004519 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004520 // Call this last since it may create pooled allocator sessions using the
4521 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004522 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004523 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004524 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004525}
4526
Steve Antonba818672017-11-06 10:21:57 -08004527cricket::ChannelManager* PeerConnection::channel_manager() const {
4528 return factory_->channel_manager();
4529}
4530
4531MetricsObserverInterface* PeerConnection::metrics_observer() const {
4532 return uma_observer_;
4533}
4534
Elad Alon99c3fe52017-10-13 16:29:40 +02004535bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004536 std::unique_ptr<RtcEventLogOutput> output,
4537 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004538 if (!event_log_) {
4539 return false;
4540 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004541 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004542}
4543
4544void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004545 if (event_log_) {
4546 event_log_->StopLogging();
4547 }
ivoc14d5dbe2016-07-04 07:06:55 -07004548}
nisseeaabdf62017-05-05 02:23:02 -07004549
Steve Anton75737c02017-11-06 10:37:17 -08004550cricket::BaseChannel* PeerConnection::GetChannel(
4551 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004552 for (auto transceiver : transceivers_) {
4553 cricket::BaseChannel* channel = transceiver->internal()->channel();
4554 if (channel && channel->content_name() == content_name) {
4555 return channel;
4556 }
Steve Anton75737c02017-11-06 10:37:17 -08004557 }
4558 if (rtp_data_channel() &&
4559 rtp_data_channel()->content_name() == content_name) {
4560 return rtp_data_channel();
4561 }
4562 return nullptr;
4563}
4564
4565bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4566 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004567 RTC_LOG(LS_INFO)
4568 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004569 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004570 return false;
4571 }
4572 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004573 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004574 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004575 return false;
4576 }
4577
4578 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4579}
4580
4581bool PeerConnection::GetSslRole(const std::string& content_name,
4582 rtc::SSLRole* role) {
4583 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004584 RTC_LOG(LS_INFO)
4585 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004586 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004587 return false;
4588 }
4589
4590 return transport_controller_->GetSslRole(GetTransportName(content_name),
4591 role);
4592}
4593
Steve Antonf8470812017-12-04 10:46:21 -08004594void PeerConnection::SetSessionError(SessionError error,
4595 const std::string& error_desc) {
4596 RTC_DCHECK_RUN_ON(signaling_thread());
4597 if (error != session_error_) {
4598 session_error_ = error;
4599 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004600 }
4601}
4602
Steve Anton3828c062017-12-06 10:34:51 -08004603RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004604 cricket::ContentSource source) {
4605 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004606
4607 // If there's already a pending error then no state transition should happen.
4608 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004609 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004610
4611 // If this is an answer then we know whether to BUNDLE or not. If both the
4612 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004613 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004614 const cricket::ContentGroup* local_bundle =
4615 local_description()->description()->GetGroupByName(
4616 cricket::GROUP_TYPE_BUNDLE);
4617 const cricket::ContentGroup* remote_bundle =
4618 remote_description()->description()->GetGroupByName(
4619 cricket::GROUP_TYPE_BUNDLE);
4620 if (local_bundle && remote_bundle) {
4621 // The answerer decides the transport to bundle on.
4622 const cricket::ContentGroup* answer_bundle =
4623 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4624 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004625 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4626 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004627 }
4628 }
Steve Anton75737c02017-11-06 10:37:17 -08004629 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004630
4631 // Only push down the transport description after potentially enabling BUNDLE;
4632 // we don't want to push down a description on a transport about to be
4633 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004634 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004635 if (!error.ok()) {
4636 return error;
4637 }
4638
4639 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004640 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004641 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004642 }
4643
4644 // Update the signaling state according to the specified state machine (see
4645 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004646 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004647 ChangeSignalingState(source == cricket::CS_LOCAL
4648 ? PeerConnectionInterface::kHaveLocalOffer
4649 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004650 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004651 ChangeSignalingState(source == cricket::CS_LOCAL
4652 ? PeerConnectionInterface::kHaveLocalPrAnswer
4653 : PeerConnectionInterface::kHaveRemotePrAnswer);
4654 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004655 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004656 ChangeSignalingState(PeerConnectionInterface::kStable);
4657 }
4658
4659 // Update internal objects according to the session description's media
4660 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004661 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004662 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004663 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004664 }
4665
Steve Anton8a006912017-12-04 15:25:56 -08004666 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004667}
4668
Steve Anton8a006912017-12-04 15:25:56 -08004669RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004670 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004671 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004672 const SessionDescriptionInterface* sdesc =
4673 (source == cricket::CS_LOCAL ? local_description()
4674 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004675 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004676
4677 // Push down the new SDP media section for each audio/video transceiver.
4678 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004679 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004680 FindMediaSectionForTransceiver(transceiver, sdesc);
4681 cricket::BaseChannel* channel = transceiver->internal()->channel();
4682 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004683 continue;
4684 }
4685 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004686 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004687 if (!content_desc) {
4688 continue;
4689 }
4690 std::string error;
4691 bool success =
4692 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004693 ? channel->SetLocalContent(content_desc, type, &error)
4694 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004695 if (!success) {
4696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4697 }
4698 }
4699
4700 // If using the RtpDataChannel, push down the new SDP section for it too.
4701 if (rtp_data_channel_) {
4702 const ContentInfo* data_content =
4703 cricket::GetFirstDataContent(sdesc->description());
4704 if (data_content && !data_content->rejected) {
4705 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004706 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004707 if (data_desc) {
4708 std::string error;
4709 bool success =
4710 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004711 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4712 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004713 &error);
4714 if (!success) {
4715 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4716 std::move(error));
4717 }
Steve Anton75737c02017-11-06 10:37:17 -08004718 }
4719 }
4720 }
Steve Antoned10bd92017-12-05 10:52:59 -08004721
Steve Anton75737c02017-11-06 10:37:17 -08004722 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4723 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4724 if (sctp_transport_ && local_description() && remote_description() &&
4725 cricket::GetFirstDataContent(local_description()->description()) &&
4726 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004727 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004728 RTC_FROM_HERE,
4729 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004730 if (!success) {
4731 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4732 "Failed to push down SCTP parameters.");
4733 }
Steve Anton75737c02017-11-06 10:37:17 -08004734 }
Steve Antoned10bd92017-12-05 10:52:59 -08004735
Steve Anton8a006912017-12-04 15:25:56 -08004736 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004737}
4738
4739bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4740 RTC_DCHECK(network_thread()->IsCurrent());
4741 RTC_DCHECK(local_description());
4742 RTC_DCHECK(remote_description());
4743 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4744 // When we support "max-message-size", that would also be pushed down here.
4745 return sctp_transport_->Start(
4746 GetSctpPort(local_description()->description()),
4747 GetSctpPort(remote_description()->description()));
4748}
4749
Steve Anton8a006912017-12-04 15:25:56 -08004750RTCError PeerConnection::PushdownTransportDescription(
4751 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004752 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004753 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004754
Steve Anton8a006912017-12-04 15:25:56 -08004755 const SessionDescriptionInterface* sdesc =
4756 (source == cricket::CS_LOCAL ? local_description()
4757 : remote_description());
4758 RTC_DCHECK(sdesc);
4759 for (const cricket::TransportInfo& tinfo :
4760 sdesc->description()->transport_infos()) {
4761 std::string error;
4762 bool success;
4763 if (source == cricket::CS_LOCAL) {
4764 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004765 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004766 } else {
4767 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004768 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004769 }
4770 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004771 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4772 "Failed to push down transport description for " +
4773 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004774 }
4775 }
4776
Steve Anton8a006912017-12-04 15:25:56 -08004777 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004778}
4779
4780bool PeerConnection::GetTransportDescription(
4781 const SessionDescription* description,
4782 const std::string& content_name,
4783 cricket::TransportDescription* tdesc) {
4784 if (!description || !tdesc) {
4785 return false;
4786 }
4787 const TransportInfo* transport_info =
4788 description->GetTransportInfoByName(content_name);
4789 if (!transport_info) {
4790 return false;
4791 }
4792 *tdesc = transport_info->description;
4793 return true;
4794}
4795
4796bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4797 const std::string* first_content_name = bundle.FirstContentName();
4798 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004799 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004800 return false;
4801 }
4802 const std::string& transport_name = *first_content_name;
4803
4804 auto maybe_set_transport = [this, bundle,
4805 transport_name](cricket::BaseChannel* ch) {
4806 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004807 return;
Steve Anton75737c02017-11-06 10:37:17 -08004808 }
4809
4810 std::string old_transport_name = ch->transport_name();
4811 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004812 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4813 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004814 return;
Steve Anton75737c02017-11-06 10:37:17 -08004815 }
4816
4817 cricket::DtlsTransportInternal* rtp_dtls_transport =
4818 transport_controller_->CreateDtlsTransport(
4819 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4820 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4821 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4822 if (need_rtcp) {
4823 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4824 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4825 }
4826
4827 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004828 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4829 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004830 transport_controller_->DestroyDtlsTransport(
4831 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4832 // If the channel needs rtcp, it means that the channel used to have a
4833 // rtcp transport which needs to be deleted now.
4834 if (need_rtcp) {
4835 transport_controller_->DestroyDtlsTransport(
4836 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4837 }
Steve Anton75737c02017-11-06 10:37:17 -08004838 };
4839
Steve Antoned10bd92017-12-05 10:52:59 -08004840 for (auto transceiver : transceivers_) {
4841 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004842 }
Steve Antoned10bd92017-12-05 10:52:59 -08004843 maybe_set_transport(rtp_data_channel_);
4844
Steve Anton75737c02017-11-06 10:37:17 -08004845 // For SCTP, transport creation/deletion happens here instead of in the
4846 // object itself.
4847 if (sctp_transport_) {
4848 RTC_DCHECK(sctp_transport_name_);
4849 RTC_DCHECK(sctp_content_name_);
4850 if (transport_name != *sctp_transport_name_ &&
4851 bundle.HasContentName(*sctp_content_name_)) {
4852 network_thread()->Invoke<void>(
4853 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4854 transport_name));
4855 }
4856 }
4857
4858 return true;
4859}
4860
Steve Anton75737c02017-11-06 10:37:17 -08004861cricket::IceConfig PeerConnection::ParseIceConfig(
4862 const PeerConnectionInterface::RTCConfiguration& config) const {
4863 cricket::ContinualGatheringPolicy gathering_policy;
4864 // TODO(honghaiz): Add the third continual gathering policy in
4865 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4866 switch (config.continual_gathering_policy) {
4867 case PeerConnectionInterface::GATHER_ONCE:
4868 gathering_policy = cricket::GATHER_ONCE;
4869 break;
4870 case PeerConnectionInterface::GATHER_CONTINUALLY:
4871 gathering_policy = cricket::GATHER_CONTINUALLY;
4872 break;
4873 default:
4874 RTC_NOTREACHED();
4875 gathering_policy = cricket::GATHER_ONCE;
4876 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004877
Steve Anton75737c02017-11-06 10:37:17 -08004878 cricket::IceConfig ice_config;
4879 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4880 ice_config.prioritize_most_likely_candidate_pairs =
4881 config.prioritize_most_likely_ice_candidate_pairs;
4882 ice_config.backup_connection_ping_interval =
4883 config.ice_backup_candidate_pair_ping_interval;
4884 ice_config.continual_gathering_policy = gathering_policy;
4885 ice_config.presume_writable_when_fully_relayed =
4886 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004887 ice_config.ice_check_interval_strong_connectivity =
4888 config.ice_check_interval_strong_connectivity;
4889 ice_config.ice_check_interval_weak_connectivity =
4890 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004891 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004892 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004893 ice_config.regather_all_networks_interval_range =
4894 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004895 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004896 return ice_config;
4897}
4898
Steve Anton75737c02017-11-06 10:37:17 -08004899bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4900 std::string* track_id) {
4901 if (!local_description()) {
4902 return false;
4903 }
4904 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4905 track_id);
4906}
4907
4908bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4909 std::string* track_id) {
4910 if (!remote_description()) {
4911 return false;
4912 }
4913 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4914 track_id);
4915}
4916
4917bool PeerConnection::SendData(const cricket::SendDataParams& params,
4918 const rtc::CopyOnWriteBuffer& payload,
4919 cricket::SendDataResult* result) {
4920 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004921 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004922 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004923 return false;
4924 }
4925 return rtp_data_channel_
4926 ? rtp_data_channel_->SendData(params, payload, result)
4927 : network_thread()->Invoke<bool>(
4928 RTC_FROM_HERE,
4929 Bind(&cricket::SctpTransportInternal::SendData,
4930 sctp_transport_.get(), params, payload, result));
4931}
4932
4933bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4934 if (!rtp_data_channel_ && !sctp_transport_) {
4935 // Don't log an error here, because DataChannels are expected to call
4936 // ConnectDataChannel in this state. It's the only way to initially tell
4937 // whether or not the underlying transport is ready.
4938 return false;
4939 }
4940 if (rtp_data_channel_) {
4941 rtp_data_channel_->SignalReadyToSendData.connect(
4942 webrtc_data_channel, &DataChannel::OnChannelReady);
4943 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4944 &DataChannel::OnDataReceived);
4945 } else {
4946 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4947 &DataChannel::OnChannelReady);
4948 SignalSctpDataReceived.connect(webrtc_data_channel,
4949 &DataChannel::OnDataReceived);
4950 SignalSctpStreamClosedRemotely.connect(
4951 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4952 }
4953 return true;
4954}
4955
4956void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4957 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004958 RTC_LOG(LS_ERROR)
4959 << "DisconnectDataChannel called when rtp_data_channel_ and "
4960 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004961 return;
4962 }
4963 if (rtp_data_channel_) {
4964 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4965 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4966 } else {
4967 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4968 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4969 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4970 }
4971}
4972
4973void PeerConnection::AddSctpDataStream(int sid) {
4974 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004975 RTC_LOG(LS_ERROR)
4976 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004977 return;
4978 }
4979 network_thread()->Invoke<void>(
4980 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4981 sctp_transport_.get(), sid));
4982}
4983
4984void PeerConnection::RemoveSctpDataStream(int sid) {
4985 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004987 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004988 return;
4989 }
4990 network_thread()->Invoke<void>(
4991 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4992 sctp_transport_.get(), sid));
4993}
4994
4995bool PeerConnection::ReadyToSendData() const {
4996 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4997 sctp_ready_to_send_data_;
4998}
4999
Qingsi Wang72a43a12018-02-20 16:03:18 -08005000cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5001 cricket::CandidateStatsList candidate_states_list;
5002 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5003 return candidate_states_list;
5004}
5005
Steve Anton5dfde182018-02-06 10:34:40 -08005006std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5007 const {
5008 std::map<std::string, std::string> transport_names_by_mid;
5009 for (auto transceiver : transceivers_) {
5010 cricket::BaseChannel* channel = transceiver->internal()->channel();
5011 if (channel) {
5012 transport_names_by_mid[channel->content_name()] =
5013 channel->transport_name();
5014 }
Steve Anton75737c02017-11-06 10:37:17 -08005015 }
Steve Anton5dfde182018-02-06 10:34:40 -08005016 if (rtp_data_channel_) {
5017 transport_names_by_mid[rtp_data_channel_->content_name()] =
5018 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005019 }
5020 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005021 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005022 }
Steve Anton5dfde182018-02-06 10:34:40 -08005023 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005024}
5025
Steve Anton5dfde182018-02-06 10:34:40 -08005026std::map<std::string, cricket::TransportStats>
5027PeerConnection::GetTransportStatsByNames(
5028 const std::set<std::string>& transport_names) {
5029 if (!network_thread()->IsCurrent()) {
5030 return network_thread()
5031 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5032 RTC_FROM_HERE,
5033 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005034 }
Steve Anton5dfde182018-02-06 10:34:40 -08005035 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5036 for (const std::string& transport_name : transport_names) {
5037 cricket::TransportStats transport_stats;
5038 bool success =
5039 transport_controller_->GetStats(transport_name, &transport_stats);
5040 if (success) {
5041 transport_stats_by_name[transport_name] = std::move(transport_stats);
5042 } else {
5043 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5044 << transport_name;
5045 }
5046 }
5047 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005048}
5049
5050bool PeerConnection::GetLocalCertificate(
5051 const std::string& transport_name,
5052 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5053 return transport_controller_->GetLocalCertificate(transport_name,
5054 certificate);
5055}
5056
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005057std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005058 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005059 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005060}
5061
5062cricket::DataChannelType PeerConnection::data_channel_type() const {
5063 return data_channel_type_;
5064}
5065
5066bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5067 return pending_ice_restarts_.find(content_name) !=
5068 pending_ice_restarts_.end();
5069}
5070
Steve Anton75737c02017-11-06 10:37:17 -08005071bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5072 return transport_controller_->NeedsIceRestart(content_name);
5073}
5074
5075void PeerConnection::OnCertificateReady(
5076 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5077 transport_controller_->SetLocalCertificate(certificate);
5078}
5079
5080void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005081 SetSessionError(SessionError::kTransport,
5082 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005083}
5084
5085void PeerConnection::OnTransportControllerConnectionState(
5086 cricket::IceConnectionState state) {
5087 switch (state) {
5088 case cricket::kIceConnectionConnecting:
5089 // If the current state is Connected or Completed, then there were
5090 // writable channels but now there are not, so the next state must
5091 // be Disconnected.
5092 // kIceConnectionConnecting is currently used as the default,
5093 // un-connected state by the TransportController, so its only use is
5094 // detecting disconnections.
5095 if (ice_connection_state_ ==
5096 PeerConnectionInterface::kIceConnectionConnected ||
5097 ice_connection_state_ ==
5098 PeerConnectionInterface::kIceConnectionCompleted) {
5099 SetIceConnectionState(
5100 PeerConnectionInterface::kIceConnectionDisconnected);
5101 }
5102 break;
5103 case cricket::kIceConnectionFailed:
5104 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5105 break;
5106 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005107 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005108 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005109 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5110 break;
5111 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005114 if (ice_connection_state_ !=
5115 PeerConnectionInterface::kIceConnectionConnected) {
5116 // If jumping directly from "checking" to "connected",
5117 // signal "connected" first.
5118 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5119 }
5120 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5121 if (metrics_observer()) {
5122 ReportTransportStats();
5123 }
5124 break;
5125 default:
5126 RTC_NOTREACHED();
5127 }
5128}
5129
5130void PeerConnection::OnTransportControllerCandidatesGathered(
5131 const std::string& transport_name,
5132 const cricket::Candidates& candidates) {
5133 RTC_DCHECK(signaling_thread()->IsCurrent());
5134 int sdp_mline_index;
5135 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005136 RTC_LOG(LS_ERROR)
5137 << "OnTransportControllerCandidatesGathered: content name "
5138 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005139 return;
5140 }
5141
5142 for (cricket::Candidates::const_iterator citer = candidates.begin();
5143 citer != candidates.end(); ++citer) {
5144 // Use transport_name as the candidate media id.
5145 std::unique_ptr<JsepIceCandidate> candidate(
5146 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5147 if (local_description()) {
5148 mutable_local_description()->AddCandidate(candidate.get());
5149 }
5150 OnIceCandidate(std::move(candidate));
5151 }
5152}
5153
5154void PeerConnection::OnTransportControllerCandidatesRemoved(
5155 const std::vector<cricket::Candidate>& candidates) {
5156 RTC_DCHECK(signaling_thread()->IsCurrent());
5157 // Sanity check.
5158 for (const cricket::Candidate& candidate : candidates) {
5159 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005161 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005162 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005163 return;
5164 }
5165 }
5166
5167 if (local_description()) {
5168 mutable_local_description()->RemoveCandidates(candidates);
5169 }
5170 OnIceCandidatesRemoved(candidates);
5171}
5172
5173void PeerConnection::OnTransportControllerDtlsHandshakeError(
5174 rtc::SSLHandshakeError error) {
5175 if (metrics_observer()) {
5176 metrics_observer()->IncrementEnumCounter(
5177 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5178 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5179 }
5180}
5181
Steve Antoned10bd92017-12-05 10:52:59 -08005182void PeerConnection::EnableSending() {
5183 for (auto transceiver : transceivers_) {
5184 cricket::BaseChannel* channel = transceiver->internal()->channel();
5185 if (channel && !channel->enabled()) {
5186 channel->Enable(true);
5187 }
Steve Anton75737c02017-11-06 10:37:17 -08005188 }
5189
Steve Anton4171afb2017-11-20 10:20:22 -08005190 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005191 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005192 }
Steve Anton75737c02017-11-06 10:37:17 -08005193}
5194
5195// Returns the media index for a local ice candidate given the content name.
5196bool PeerConnection::GetLocalCandidateMediaIndex(
5197 const std::string& content_name,
5198 int* sdp_mline_index) {
5199 if (!local_description() || !sdp_mline_index) {
5200 return false;
5201 }
5202
5203 bool content_found = false;
5204 const ContentInfos& contents = local_description()->description()->contents();
5205 for (size_t index = 0; index < contents.size(); ++index) {
5206 if (contents[index].name == content_name) {
5207 *sdp_mline_index = static_cast<int>(index);
5208 content_found = true;
5209 break;
5210 }
5211 }
5212 return content_found;
5213}
5214
5215bool PeerConnection::UseCandidatesInSessionDescription(
5216 const SessionDescriptionInterface* remote_desc) {
5217 if (!remote_desc) {
5218 return true;
5219 }
5220 bool ret = true;
5221
5222 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5223 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5224 for (size_t n = 0; n < candidates->count(); ++n) {
5225 const IceCandidateInterface* candidate = candidates->at(n);
5226 bool valid = false;
5227 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5228 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005229 RTC_LOG(LS_INFO)
5230 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005231 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005232 }
5233 continue;
5234 }
5235 ret = UseCandidate(candidate);
5236 if (!ret) {
5237 break;
5238 }
5239 }
5240 }
5241 return ret;
5242}
5243
5244bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5245 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5246 size_t remote_content_size =
5247 remote_description()->description()->contents().size();
5248 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005249 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005250 return false;
5251 }
5252
5253 cricket::ContentInfo content =
5254 remote_description()->description()->contents()[mediacontent_index];
5255 std::vector<cricket::Candidate> candidates;
5256 candidates.push_back(candidate->candidate());
5257 // Invoking BaseSession method to handle remote candidates.
5258 std::string error;
5259 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5260 &error)) {
5261 // Candidates successfully submitted for checking.
5262 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5263 ice_connection_state_ ==
5264 PeerConnectionInterface::kIceConnectionDisconnected) {
5265 // If state is New, then the session has just gotten its first remote ICE
5266 // candidates, so go to Checking.
5267 // If state is Disconnected, the session is re-using old candidates or
5268 // receiving additional ones, so go to Checking.
5269 // If state is Connected, stay Connected.
5270 // TODO(bemasc): If state is Connected, and the new candidates are for a
5271 // newly added transport, then the state actually _should_ move to
5272 // checking. Add a way to distinguish that case.
5273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5274 }
5275 // TODO(bemasc): If state is Completed, go back to Connected.
5276 } else {
5277 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005278 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005279 }
5280 }
5281 return true;
5282}
5283
5284void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005285 // Destroy video channel first since it may have a pointer to the
5286 // voice channel.
5287 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005288 if (!video_info || video_info->rejected) {
5289 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005290 }
5291
Steve Anton6fec8802017-12-04 10:37:29 -08005292 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5293 if (!audio_info || audio_info->rejected) {
5294 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005295 }
5296
5297 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5298 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005299 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005300 }
5301}
5302
Steve Antoneda6ccd2017-12-04 10:21:55 -08005303std::string PeerConnection::GetTransportNameForMediaSection(
5304 const std::string& mid,
5305 const cricket::ContentGroup* bundle_group) const {
5306 if (!bundle_group) {
5307 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005308 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005309 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005310 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005311 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005312 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005313 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005314 if (!bundle_group->HasContentName(mid)) {
5315 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5316 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005317 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005318 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5319 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005320}
5321
Steve Antondcc3c022017-12-22 16:02:54 -08005322RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5323 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005324 const cricket::ContentGroup* bundle_group = nullptr;
5325 if (configuration_.bundle_policy ==
5326 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005327 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005328 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005329 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5330 "max-bundle configured but session description "
5331 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005332 }
5333 }
Steve Antondcc3c022017-12-22 16:02:54 -08005334 return std::move(bundle_group);
5335}
5336
5337RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5338 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5339 if (!bundle_group_or_error.ok()) {
5340 return bundle_group_or_error.MoveError();
5341 }
5342 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005343
Steve Antoneda6ccd2017-12-04 10:21:55 -08005344 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005345 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005346 if (voice && !voice->rejected &&
5347 !GetAudioTransceiver()->internal()->channel()) {
5348 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5349 voice->name,
5350 GetTransportNameForMediaSection(voice->name, bundle_group));
5351 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005352 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5353 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005354 }
5355 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5356 }
5357
Steve Antondcc3c022017-12-22 16:02:54 -08005358 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005359 if (video && !video->rejected &&
5360 !GetVideoTransceiver()->internal()->channel()) {
5361 cricket::VideoChannel* video_channel = CreateVideoChannel(
5362 video->name,
5363 GetTransportNameForMediaSection(video->name, bundle_group));
5364 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005365 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5366 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005367 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005368 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005369 }
5370
Steve Antondcc3c022017-12-22 16:02:54 -08005371 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005372 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5373 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005374 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5375 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005376 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5377 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005378 }
5379 }
5380
Steve Anton8a006912017-12-04 15:25:56 -08005381 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005382}
5383
Steve Anton4171afb2017-11-20 10:20:22 -08005384// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005385cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5386 const std::string& mid,
5387 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005388 cricket::DtlsTransportInternal* rtp_dtls_transport =
5389 transport_controller_->CreateDtlsTransport(
5390 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5391 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5392 if (configuration_.rtcp_mux_policy !=
5393 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5394 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5395 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5396 }
5397
5398 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5399 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005400 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5401 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005402 if (!voice_channel) {
5403 transport_controller_->DestroyDtlsTransport(
5404 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5405 if (rtcp_dtls_transport) {
5406 transport_controller_->DestroyDtlsTransport(
5407 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5408 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005409 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005410 }
Steve Anton75737c02017-11-06 10:37:17 -08005411 voice_channel->SignalRtcpMuxFullyActive.connect(
5412 this, &PeerConnection::DestroyRtcpTransport_n);
5413 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5414 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005415 voice_channel->SignalSentPacket.connect(this,
5416 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005417
Steve Antoneda6ccd2017-12-04 10:21:55 -08005418 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005419}
5420
Steve Anton4171afb2017-11-20 10:20:22 -08005421// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005422cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5423 const std::string& mid,
5424 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005425 cricket::DtlsTransportInternal* rtp_dtls_transport =
5426 transport_controller_->CreateDtlsTransport(
5427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5428 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5429 if (configuration_.rtcp_mux_policy !=
5430 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5431 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5432 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5433 }
5434
5435 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5436 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005437 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5438 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005439
5440 if (!video_channel) {
5441 transport_controller_->DestroyDtlsTransport(
5442 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5443 if (rtcp_dtls_transport) {
5444 transport_controller_->DestroyDtlsTransport(
5445 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5446 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005447 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005448 }
Steve Anton75737c02017-11-06 10:37:17 -08005449 video_channel->SignalRtcpMuxFullyActive.connect(
5450 this, &PeerConnection::DestroyRtcpTransport_n);
5451 video_channel->SignalDtlsSrtpSetupFailure.connect(
5452 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005453 video_channel->SignalSentPacket.connect(this,
5454 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005455
Steve Antoneda6ccd2017-12-04 10:21:55 -08005456 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005457}
5458
Steve Antoneda6ccd2017-12-04 10:21:55 -08005459bool PeerConnection::CreateDataChannel(const std::string& mid,
5460 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005461 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5462 if (sctp) {
5463 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005464 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005465 << "Trying to create SCTP transport, but didn't compile with "
5466 "SCTP support (HAVE_SCTP)";
5467 return false;
5468 }
5469 if (!network_thread()->Invoke<bool>(
5470 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005471 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005472 return false;
5473 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005474 for (const auto& channel : sctp_data_channels_) {
5475 channel->OnTransportChannelCreated();
5476 }
Steve Anton75737c02017-11-06 10:37:17 -08005477 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005478 cricket::DtlsTransportInternal* rtp_dtls_transport =
5479 transport_controller_->CreateDtlsTransport(
5480 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5481 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5482 if (configuration_.rtcp_mux_policy !=
5483 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5484 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5485 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5486 }
5487
5488 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5489 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005490 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005491
5492 if (!rtp_data_channel_) {
5493 transport_controller_->DestroyDtlsTransport(
5494 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5495 if (rtcp_dtls_transport) {
5496 transport_controller_->DestroyDtlsTransport(
5497 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5498 }
5499 return false;
5500 }
5501
5502 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5503 this, &PeerConnection::DestroyRtcpTransport_n);
5504 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5505 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5506 rtp_data_channel_->SignalSentPacket.connect(
5507 this, &PeerConnection::OnSentPacket_w);
5508 }
5509
Steve Anton75737c02017-11-06 10:37:17 -08005510 return true;
5511}
5512
5513Call::Stats PeerConnection::GetCallStats() {
5514 if (!worker_thread()->IsCurrent()) {
5515 return worker_thread()->Invoke<Call::Stats>(
5516 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5517 }
5518 if (call_) {
5519 return call_->GetStats();
5520 } else {
5521 return Call::Stats();
5522 }
5523}
5524
Steve Anton75737c02017-11-06 10:37:17 -08005525bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5526 const std::string& transport_name) {
5527 RTC_DCHECK(network_thread()->IsCurrent());
5528 RTC_DCHECK(sctp_factory_);
5529 cricket::DtlsTransportInternal* tc =
5530 transport_controller_->CreateDtlsTransport_n(
5531 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5532 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5533 RTC_DCHECK(sctp_transport_);
5534 sctp_invoker_.reset(new rtc::AsyncInvoker());
5535 sctp_transport_->SignalReadyToSendData.connect(
5536 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5537 sctp_transport_->SignalDataReceived.connect(
5538 this, &PeerConnection::OnSctpTransportDataReceived_n);
5539 sctp_transport_->SignalStreamClosedRemotely.connect(
5540 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005541 sctp_transport_name_ = transport_name;
5542 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005543 return true;
5544}
5545
5546void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5547 RTC_DCHECK(network_thread()->IsCurrent());
5548 RTC_DCHECK(sctp_transport_);
5549 RTC_DCHECK(sctp_transport_name_);
5550 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005551 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005552 cricket::DtlsTransportInternal* tc =
5553 transport_controller_->CreateDtlsTransport_n(
5554 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5555 sctp_transport_->SetTransportChannel(tc);
5556 transport_controller_->DestroyDtlsTransport_n(
5557 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5558}
5559
5560void PeerConnection::DestroySctpTransport_n() {
5561 RTC_DCHECK(network_thread()->IsCurrent());
5562 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005563 transport_controller_->DestroyDtlsTransport_n(
5564 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005565 sctp_content_name_.reset();
5566 sctp_transport_name_.reset();
5567 sctp_invoker_.reset(nullptr);
5568 sctp_ready_to_send_data_ = false;
5569}
5570
5571void PeerConnection::OnSctpTransportReadyToSendData_n() {
5572 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5573 RTC_DCHECK(network_thread()->IsCurrent());
5574 // Note: Cannot use rtc::Bind here because it will grab a reference to
5575 // PeerConnection and potentially cause PeerConnection to live longer than
5576 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5577 // be destroyed before PeerConnection is destroyed, and at that point all
5578 // pending tasks will be cleared.
5579 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5580 OnSctpTransportReadyToSendData_s(true);
5581 });
5582}
5583
5584void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5585 RTC_DCHECK(signaling_thread()->IsCurrent());
5586 sctp_ready_to_send_data_ = ready;
5587 SignalSctpReadyToSendData(ready);
5588}
5589
5590void PeerConnection::OnSctpTransportDataReceived_n(
5591 const cricket::ReceiveDataParams& params,
5592 const rtc::CopyOnWriteBuffer& payload) {
5593 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5594 RTC_DCHECK(network_thread()->IsCurrent());
5595 // Note: Cannot use rtc::Bind here because it will grab a reference to
5596 // PeerConnection and potentially cause PeerConnection to live longer than
5597 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5598 // be destroyed before PeerConnection is destroyed, and at that point all
5599 // pending tasks will be cleared.
5600 sctp_invoker_->AsyncInvoke<void>(
5601 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5602 OnSctpTransportDataReceived_s(params, payload);
5603 });
5604}
5605
5606void PeerConnection::OnSctpTransportDataReceived_s(
5607 const cricket::ReceiveDataParams& params,
5608 const rtc::CopyOnWriteBuffer& payload) {
5609 RTC_DCHECK(signaling_thread()->IsCurrent());
5610 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5611 // Received OPEN message; parse and signal that a new data channel should
5612 // be created.
5613 std::string label;
5614 InternalDataChannelInit config;
5615 config.id = params.ssrc;
5616 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005617 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5618 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005619 return;
5620 }
5621 config.open_handshake_role = InternalDataChannelInit::kAcker;
5622 OnDataChannelOpenMessage(label, config);
5623 } else {
5624 // Otherwise just forward the signal.
5625 SignalSctpDataReceived(params, payload);
5626 }
5627}
5628
5629void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5630 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5631 RTC_DCHECK(network_thread()->IsCurrent());
5632 sctp_invoker_->AsyncInvoke<void>(
5633 RTC_FROM_HERE, signaling_thread(),
5634 rtc::Bind(&sigslot::signal1<int>::operator(),
5635 &SignalSctpStreamClosedRemotely, sid));
5636}
5637
5638// Returns false if bundle is enabled and rtcp_mux is disabled.
5639bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5640 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5641 if (!bundle_enabled)
5642 return true;
5643
5644 const cricket::ContentGroup* bundle_group =
5645 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5646 RTC_DCHECK(bundle_group != NULL);
5647
5648 const cricket::ContentInfos& contents = desc->contents();
5649 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5650 citer != contents.end(); ++citer) {
5651 const cricket::ContentInfo* content = (&*citer);
5652 RTC_DCHECK(content != NULL);
5653 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005654 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005655 if (!HasRtcpMuxEnabled(content))
5656 return false;
5657 }
5658 }
5659 // RTCP-MUX is enabled in all the contents.
5660 return true;
5661}
5662
5663bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005664 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005665}
5666
Steve Anton8a006912017-12-04 15:25:56 -08005667RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005668 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005669 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005670 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005671 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005672 }
5673
5674 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005676 }
5677
Steve Anton3828c062017-12-06 10:34:51 -08005678 SdpType type = sdesc->GetType();
5679 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5680 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005681 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005682 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005683 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005684 }
5685
5686 // Verify crypto settings.
5687 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005688 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5689 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005690 RTCError crypto_error =
5691 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005692 if (!crypto_error.ok()) {
5693 return crypto_error;
5694 }
Steve Anton75737c02017-11-06 10:37:17 -08005695 }
5696
5697 // Verify ice-ufrag and ice-pwd.
5698 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5700 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702
5703 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5705 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005706 }
5707
5708 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5709 // m-lines that do not rtcp-mux enabled.
5710
5711 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005712 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005713 // With an answer we want to compare the new answer session description with
5714 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005715 const cricket::SessionDescription* offer_desc =
5716 (source == cricket::CS_LOCAL) ? remote_description()->description()
5717 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005718 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5719 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5720 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005721 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5722 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005723 }
5724 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005725 // The re-offers should respect the order of m= sections in current
5726 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005727 // With a re-offer, either the current local or current remote descriptions
5728 // could be the most up to date, so we would like to check against both of
5729 // them if they exist. It could be the case that one of them has a 0 port
5730 // for a media section, but the other does not. This is important to check
5731 // against in the case that we are recycling an m= section.
5732 const cricket::SessionDescription* current_desc = nullptr;
5733 const cricket::SessionDescription* secondary_current_desc = nullptr;
5734 if (local_description()) {
5735 current_desc = local_description()->description();
5736 if (remote_description()) {
5737 secondary_current_desc = remote_description()->description();
5738 }
5739 } else if (remote_description()) {
5740 current_desc = remote_description()->description();
5741 }
Steve Anton75737c02017-11-06 10:37:17 -08005742 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005743 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5744 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5746 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005747 }
5748 }
5749
Steve Anton8a006912017-12-04 15:25:56 -08005750 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005751}
5752
Steve Anton3828c062017-12-06 10:34:51 -08005753bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005754 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005755 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005756 return (state == PeerConnectionInterface::kStable) ||
5757 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005758 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005759 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005760 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5761 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5762 }
5763}
5764
Steve Anton3828c062017-12-06 10:34:51 -08005765bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005766 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005767 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005768 return (state == PeerConnectionInterface::kStable) ||
5769 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005770 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005771 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005772 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5773 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5774 }
5775}
5776
Steve Antonf8470812017-12-04 10:46:21 -08005777const char* PeerConnection::SessionErrorToString(SessionError error) const {
5778 switch (error) {
5779 case SessionError::kNone:
5780 return "ERROR_NONE";
5781 case SessionError::kContent:
5782 return "ERROR_CONTENT";
5783 case SessionError::kTransport:
5784 return "ERROR_TRANSPORT";
5785 }
5786 RTC_NOTREACHED();
5787 return "";
5788}
5789
Steve Anton75737c02017-11-06 10:37:17 -08005790std::string PeerConnection::GetSessionErrorMsg() {
5791 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005792 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5793 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005794 return desc.str();
5795}
5796
Steve Anton8e20f172018-03-06 10:55:04 -08005797void PeerConnection::ReportSdpFormatReceived(
5798 const SessionDescriptionInterface& remote_offer) {
5799 if (!uma_observer_) {
5800 return;
5801 }
5802 int num_audio_mlines = 0;
5803 int num_video_mlines = 0;
5804 int num_audio_tracks = 0;
5805 int num_video_tracks = 0;
5806 for (const ContentInfo& content : remote_offer.description()->contents()) {
5807 cricket::MediaType media_type = content.media_description()->type();
5808 int num_tracks = std::max(
5809 1, static_cast<int>(content.media_description()->streams().size()));
5810 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5811 num_audio_mlines += 1;
5812 num_audio_tracks += num_tracks;
5813 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5814 num_video_mlines += 1;
5815 num_video_tracks += num_tracks;
5816 }
5817 }
5818 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5819 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5820 format = kSdpFormatReceivedComplexUnifiedPlan;
5821 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5822 format = kSdpFormatReceivedComplexPlanB;
5823 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5824 format = kSdpFormatReceivedSimple;
5825 }
5826 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5827 kSdpFormatReceivedMax);
5828}
5829
Steve Anton0ffaaa22018-02-23 10:31:30 -08005830void PeerConnection::ReportNegotiatedSdpSemantics(
5831 const SessionDescriptionInterface& answer) {
5832 if (!uma_observer_) {
5833 return;
5834 }
5835 switch (answer.description()->msid_signaling()) {
5836 case 0:
5837 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5838 kSdpSemanticNegotiatedNone,
5839 kSdpSemanticNegotiatedMax);
5840 break;
5841 case cricket::kMsidSignalingMediaSection:
5842 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5843 kSdpSemanticNegotiatedUnifiedPlan,
5844 kSdpSemanticNegotiatedMax);
5845 break;
5846 case cricket::kMsidSignalingSsrcAttribute:
5847 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5848 kSdpSemanticNegotiatedPlanB,
5849 kSdpSemanticNegotiatedMax);
5850 break;
5851 case cricket::kMsidSignalingMediaSection |
5852 cricket::kMsidSignalingSsrcAttribute:
5853 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5854 kSdpSemanticNegotiatedMixed,
5855 kSdpSemanticNegotiatedMax);
5856 break;
5857 default:
5858 RTC_NOTREACHED();
5859 }
5860}
5861
Steve Anton75737c02017-11-06 10:37:17 -08005862// We need to check the local/remote description for the Transport instead of
5863// the session, because a new Transport added during renegotiation may have
5864// them unset while the session has them set from the previous negotiation.
5865// Not doing so may trigger the auto generation of transport description and
5866// mess up DTLS identity information, ICE credential, etc.
5867bool PeerConnection::ReadyToUseRemoteCandidate(
5868 const IceCandidateInterface* candidate,
5869 const SessionDescriptionInterface* remote_desc,
5870 bool* valid) {
5871 *valid = true;
5872
5873 const SessionDescriptionInterface* current_remote_desc =
5874 remote_desc ? remote_desc : remote_description();
5875
5876 if (!current_remote_desc) {
5877 return false;
5878 }
5879
5880 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5881 size_t remote_content_size =
5882 current_remote_desc->description()->contents().size();
5883 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005884 RTC_LOG(LS_ERROR)
5885 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5886 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005887
5888 *valid = false;
5889 return false;
5890 }
5891
5892 cricket::ContentInfo content =
5893 current_remote_desc->description()->contents()[mediacontent_index];
5894
5895 const std::string transport_name = GetTransportName(content.name);
5896 if (transport_name.empty()) {
5897 return false;
5898 }
5899 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5900}
5901
5902bool PeerConnection::SrtpRequired() const {
5903 return dtls_enabled_ ||
5904 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5905}
5906
5907void PeerConnection::OnTransportControllerGatheringState(
5908 cricket::IceGatheringState state) {
5909 RTC_DCHECK(signaling_thread()->IsCurrent());
5910 if (state == cricket::kIceGatheringGathering) {
5911 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5912 } else if (state == cricket::kIceGatheringComplete) {
5913 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5914 }
5915}
5916
5917void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005918 std::map<std::string, std::set<cricket::MediaType>>
5919 media_types_by_transport_name;
5920 for (auto transceiver : transceivers_) {
5921 if (transceiver->internal()->channel()) {
5922 const std::string& transport_name =
5923 transceiver->internal()->channel()->transport_name();
5924 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005925 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005926 }
Steve Anton75737c02017-11-06 10:37:17 -08005927 }
5928 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005929 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5930 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005931 }
5932 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005933 media_types_by_transport_name[*sctp_transport_name_].insert(
5934 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005935 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005936 for (const auto& entry : media_types_by_transport_name) {
5937 const std::string& transport_name = entry.first;
5938 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005939 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005940 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005941 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005942 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005943 }
5944 }
5945}
5946// Walk through the ConnectionInfos to gather best connection usage
5947// for IPv4 and IPv6.
5948void PeerConnection::ReportBestConnectionState(
5949 const cricket::TransportStats& stats) {
5950 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005951 for (const cricket::TransportChannelStats& channel_stats :
5952 stats.channel_stats) {
5953 for (const cricket::ConnectionInfo& connection_info :
5954 channel_stats.connection_infos) {
5955 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005956 continue;
5957 }
5958
5959 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005960 const cricket::Candidate& local = connection_info.local_candidate;
5961 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005962
5963 // Increment the counter for IceCandidatePairType.
5964 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5965 (local.type() == RELAY_PORT_TYPE &&
5966 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5967 type = kEnumCounterIceCandidatePairTypeTcp;
5968 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5969 type = kEnumCounterIceCandidatePairTypeUdp;
5970 } else {
5971 RTC_CHECK(0);
5972 }
5973 metrics_observer()->IncrementEnumCounter(
5974 type, GetIceCandidatePairCounter(local, remote),
5975 kIceCandidatePairMax);
5976
5977 // Increment the counter for IP type.
5978 if (local.address().family() == AF_INET) {
5979 metrics_observer()->IncrementEnumCounter(
5980 kEnumCounterAddressFamily, kBestConnections_IPv4,
5981 kPeerConnectionAddressFamilyCounter_Max);
5982
5983 } else if (local.address().family() == AF_INET6) {
5984 metrics_observer()->IncrementEnumCounter(
5985 kEnumCounterAddressFamily, kBestConnections_IPv6,
5986 kPeerConnectionAddressFamilyCounter_Max);
5987 } else {
5988 RTC_CHECK(0);
5989 }
5990
5991 return;
5992 }
5993 }
5994}
5995
5996void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005997 const cricket::TransportStats& stats,
5998 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005999 RTC_DCHECK(metrics_observer());
6000 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6001 return;
6002 }
6003
6004 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6005 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6006 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6007 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6008 return;
6009 }
6010
Steve Antonc7b964c2018-02-01 14:39:45 -08006011 for (cricket::MediaType media_type : media_types) {
6012 PeerConnectionEnumCounterType srtp_counter_type;
6013 PeerConnectionEnumCounterType ssl_counter_type;
6014 switch (media_type) {
6015 case cricket::MEDIA_TYPE_AUDIO:
6016 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6017 ssl_counter_type = kEnumCounterAudioSslCipher;
6018 break;
6019 case cricket::MEDIA_TYPE_VIDEO:
6020 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6021 ssl_counter_type = kEnumCounterVideoSslCipher;
6022 break;
6023 case cricket::MEDIA_TYPE_DATA:
6024 srtp_counter_type = kEnumCounterDataSrtpCipher;
6025 ssl_counter_type = kEnumCounterDataSslCipher;
6026 break;
6027 default:
6028 RTC_NOTREACHED();
6029 continue;
6030 }
6031 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6032 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6033 srtp_crypto_suite);
6034 }
6035 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6036 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6037 ssl_cipher_suite);
6038 }
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
6040}
6041
6042void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6043 RTC_DCHECK(worker_thread()->IsCurrent());
6044 RTC_DCHECK(call_);
6045 call_->OnSentPacket(sent_packet);
6046}
6047
6048const std::string PeerConnection::GetTransportName(
6049 const std::string& content_name) {
6050 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006051 if (channel) {
6052 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006053 }
Steve Anton6fec8802017-12-04 10:37:29 -08006054 if (sctp_transport_) {
6055 RTC_DCHECK(sctp_content_name_);
6056 RTC_DCHECK(sctp_transport_name_);
6057 if (content_name == *sctp_content_name_) {
6058 return *sctp_transport_name_;
6059 }
6060 }
6061 // Return an empty string if failed to retrieve the transport name.
6062 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006063}
6064
6065void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6066 RTC_DCHECK(network_thread()->IsCurrent());
6067 transport_controller_->DestroyDtlsTransport_n(
6068 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6069}
6070
Steve Anton6fec8802017-12-04 10:37:29 -08006071void PeerConnection::DestroyTransceiverChannel(
6072 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6073 transceiver) {
6074 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006075
Steve Anton6fec8802017-12-04 10:37:29 -08006076 cricket::BaseChannel* channel = transceiver->internal()->channel();
6077 if (channel) {
6078 transceiver->internal()->SetChannel(nullptr);
6079 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006080 }
6081}
6082
6083void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006084 if (rtp_data_channel_) {
6085 OnDataChannelDestroyed();
6086 DestroyBaseChannel(rtp_data_channel_);
6087 rtp_data_channel_ = nullptr;
6088 }
6089
6090 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6091 // grab a reference to this PeerConnection. If this is called from the
6092 // PeerConnection destructor, the RefCountedObject vtable will have already
6093 // been destroyed (since it is a subclass of PeerConnection) and using
6094 // rtc::Bind will cause "Pure virtual function called" error to appear.
6095
6096 if (sctp_transport_) {
6097 OnDataChannelDestroyed();
6098 network_thread()->Invoke<void>(RTC_FROM_HERE,
6099 [this] { DestroySctpTransport_n(); });
6100 }
6101}
6102
6103void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6104 RTC_DCHECK(channel);
6105 RTC_DCHECK(channel->rtp_dtls_transport());
6106
6107 // Need to cache these before destroying the base channel so that we do not
6108 // access uninitialized memory.
6109 const std::string transport_name =
6110 channel->rtp_dtls_transport()->transport_name();
6111 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6112
6113 switch (channel->media_type()) {
6114 case cricket::MEDIA_TYPE_AUDIO:
6115 channel_manager()->DestroyVoiceChannel(
6116 static_cast<cricket::VoiceChannel*>(channel));
6117 break;
6118 case cricket::MEDIA_TYPE_VIDEO:
6119 channel_manager()->DestroyVideoChannel(
6120 static_cast<cricket::VideoChannel*>(channel));
6121 break;
6122 case cricket::MEDIA_TYPE_DATA:
6123 channel_manager()->DestroyRtpDataChannel(
6124 static_cast<cricket::RtpDataChannel*>(channel));
6125 break;
6126 default:
6127 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6128 break;
6129 }
6130
6131 // |channel| can no longer be used.
6132
Steve Anton75737c02017-11-06 10:37:17 -08006133 transport_controller_->DestroyDtlsTransport(
6134 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6135 if (need_to_delete_rtcp) {
6136 transport_controller_->DestroyDtlsTransport(
6137 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6138 }
6139}
6140
Harald Alvestrand89061872018-01-02 14:08:34 +01006141void PeerConnection::ClearStatsCache() {
6142 if (stats_collector_) {
6143 stats_collector_->ClearCachedStatsReport();
6144 }
6145}
6146
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006147} // namespace webrtc