blob: db6cad699577c9adab93af4c2bbf81b120175dd1 [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
deadbeefab9b2d12015-10-14 11:33:11 -070096static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
127 std::string error;
128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
145 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
385// Checks that each non-rejected content has SDES crypto keys or a DTLS
386// fingerprint, unless it's in a BUNDLE group, in which case only the
387// BUNDLE-tag section (first media section/description in the BUNDLE group)
388// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
389// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
390// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100391RTCError VerifyCrypto(const SessionDescription* desc,
392 bool dtls_enabled,
393 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 const cricket::ContentGroup* bundle =
395 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800396 for (const cricket::ContentInfo& content_info : desc->contents()) {
397 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 continue;
399 }
Steve Anton8a006912017-12-04 15:25:56 -0800400 const std::string& mid = content_info.name;
401 if (bundle && bundle->HasContentName(mid) &&
402 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800403 // This isn't the first media section in the BUNDLE group, so it's not
404 // required to have crypto attributes, since only the crypto attributes
405 // from the first section actually get used.
406 continue;
407 }
408
409 // If the content isn't rejected or bundled into another m= section, crypto
410 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800411 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800412 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800413 if (!media || !tinfo) {
414 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800416 }
417 if (dtls_enabled) {
418 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG(LS_WARNING)
420 << "Session description must have DTLS fingerprint if "
421 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800422 return RTCError(RTCErrorType::INVALID_PARAMETER,
423 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800424 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100425 if (uma_observer) {
426 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
427 webrtc::kEnumCounterKeyProtocolDtls,
428 webrtc::kEnumCounterKeyProtocolMax);
429 }
Steve Anton75737c02017-11-06 10:37:17 -0800430 } else {
431 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800433 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800434 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800435 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100436 if (uma_observer) {
437 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
438 webrtc::kEnumCounterKeyProtocolSdes,
439 webrtc::kEnumCounterKeyProtocolMax);
440 }
Steve Anton75737c02017-11-06 10:37:17 -0800441 }
442 }
Steve Anton8a006912017-12-04 15:25:56 -0800443 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800444}
445
446// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
447// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
448// media section/description in the BUNDLE group) needs a ufrag and pwd.
449bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
450 const cricket::ContentGroup* bundle =
451 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800452 for (const cricket::ContentInfo& content_info : desc->contents()) {
453 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800454 continue;
455 }
Steve Anton8a006912017-12-04 15:25:56 -0800456 const std::string& mid = content_info.name;
457 if (bundle && bundle->HasContentName(mid) &&
458 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800459 // This isn't the first media section in the BUNDLE group, so it's not
460 // required to have ufrag/password, since only the ufrag/password from
461 // the first section actually get used.
462 continue;
463 }
464
465 // If the content isn't rejected or bundled into another m= section,
466 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800467 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800468 if (!tinfo) {
469 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100470 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800471 return false;
472 }
473 if (tinfo->description.ice_ufrag.empty() ||
474 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800476 return false;
477 }
478 }
479 return true;
480}
481
482bool GetTrackIdBySsrc(const SessionDescription* session_description,
483 uint32_t ssrc,
484 std::string* track_id) {
485 RTC_DCHECK(track_id != NULL);
486
Steve Antonb1c1de12017-12-21 15:14:30 -0800487 const cricket::AudioContentDescription* audio_desc =
488 cricket::GetFirstAudioContentDescription(session_description);
489 if (audio_desc) {
490 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (found) {
492 *track_id = found->id;
493 return true;
494 }
495 }
496
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const cricket::VideoContentDescription* video_desc =
498 cricket::GetFirstVideoContentDescription(session_description);
499 if (video_desc) {
500 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800501 if (found) {
502 *track_id = found->id;
503 return true;
504 }
505 }
506 return false;
507}
508
509// Get the SCTP port out of a SessionDescription.
510// Return -1 if not found.
511int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800512 const cricket::DataContentDescription* data_desc =
513 GetFirstDataContentDescription(session_description);
514 RTC_DCHECK(data_desc);
515 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 return -1;
517 }
Steve Anton75737c02017-11-06 10:37:17 -0800518 std::string value;
519 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
520 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800521 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 if (!codec.Matches(match_pattern)) {
523 continue;
524 }
525 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
526 return rtc::FromString<int>(value);
527 }
528 }
529 return -1;
530}
531
Steve Anton75737c02017-11-06 10:37:17 -0800532// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
533bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
534 const SessionDescriptionInterface* new_desc,
535 const std::string& content_name) {
536 if (!old_desc) {
537 return false;
538 }
539 const SessionDescription* new_sd = new_desc->description();
540 const SessionDescription* old_sd = old_desc->description();
541 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
542 if (!cinfo || cinfo->rejected) {
543 return false;
544 }
545 // If the content isn't rejected, check if ufrag and password has changed.
546 const cricket::TransportDescription* new_transport_desc =
547 new_sd->GetTransportDescriptionByName(content_name);
548 const cricket::TransportDescription* old_transport_desc =
549 old_sd->GetTransportDescriptionByName(content_name);
550 if (!new_transport_desc || !old_transport_desc) {
551 // No transport description exists. This is not an ICE restart.
552 return false;
553 }
554 if (cricket::IceCredentialsChanged(
555 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
556 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
558 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800559 return true;
560 }
561 return false;
562}
563
564} // namespace
565
Henrik Boström31638672017-11-23 17:48:32 +0100566// Upon completion, posts a task to execute the callback of the
567// SetSessionDescriptionObserver asynchronously on the same thread. At this
568// point, the state of the peer connection might no longer reflect the effects
569// of the SetRemoteDescription operation, as the peer connection could have been
570// modified during the post.
571// TODO(hbos): Remove this class once we remove the version of
572// PeerConnectionInterface::SetRemoteDescription() that takes a
573// SetSessionDescriptionObserver as an argument.
574class PeerConnection::SetRemoteDescriptionObserverAdapter
575 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
576 public:
577 SetRemoteDescriptionObserverAdapter(
578 rtc::scoped_refptr<PeerConnection> pc,
579 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
580 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
581
582 // SetRemoteDescriptionObserverInterface implementation.
583 void OnSetRemoteDescriptionComplete(RTCError error) override {
584 if (error.ok())
585 pc_->PostSetSessionDescriptionSuccess(wrapper_);
586 else
587 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
588 }
589
590 private:
591 rtc::scoped_refptr<PeerConnection> pc_;
592 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
593};
594
deadbeef293e9262017-01-11 12:28:30 -0800595bool PeerConnectionInterface::RTCConfiguration::operator==(
596 const PeerConnectionInterface::RTCConfiguration& o) const {
597 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700598 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800599 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000600 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700601 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800602 BundlePolicy bundle_policy;
603 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700604 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
605 int ice_candidate_pool_size;
606 bool disable_ipv6;
607 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700608 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100609 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700610 bool enable_rtp_data_channel;
611 rtc::Optional<int> screencast_min_bitrate;
612 rtc::Optional<bool> combined_audio_video_bwe;
613 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800614 TcpCandidatePolicy tcp_candidate_policy;
615 CandidateNetworkPolicy candidate_network_policy;
616 int audio_jitter_buffer_max_packets;
617 bool audio_jitter_buffer_fast_accelerate;
618 int ice_connection_receiving_timeout;
619 int ice_backup_candidate_pair_ping_interval;
620 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800621 bool prioritize_most_likely_ice_candidate_pairs;
622 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800623 bool prune_turn_ports;
624 bool presume_writable_when_fully_relayed;
625 bool enable_ice_renomination;
626 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800627 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700628 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200629 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800630 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800631 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800632 };
633 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
634 "Did you add something to RTCConfiguration and forget to "
635 "update operator==?");
636 return type == o.type && servers == o.servers &&
637 bundle_policy == o.bundle_policy &&
638 rtcp_mux_policy == o.rtcp_mux_policy &&
639 tcp_candidate_policy == o.tcp_candidate_policy &&
640 candidate_network_policy == o.candidate_network_policy &&
641 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
642 audio_jitter_buffer_fast_accelerate ==
643 o.audio_jitter_buffer_fast_accelerate &&
644 ice_connection_receiving_timeout ==
645 o.ice_connection_receiving_timeout &&
646 ice_backup_candidate_pair_ping_interval ==
647 o.ice_backup_candidate_pair_ping_interval &&
648 continual_gathering_policy == o.continual_gathering_policy &&
649 certificates == o.certificates &&
650 prioritize_most_likely_ice_candidate_pairs ==
651 o.prioritize_most_likely_ice_candidate_pairs &&
652 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800653 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700654 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100655 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800656 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800657 screencast_min_bitrate == o.screencast_min_bitrate &&
658 combined_audio_video_bwe == o.combined_audio_video_bwe &&
659 enable_dtls_srtp == o.enable_dtls_srtp &&
660 ice_candidate_pool_size == o.ice_candidate_pool_size &&
661 prune_turn_ports == o.prune_turn_ports &&
662 presume_writable_when_fully_relayed ==
663 o.presume_writable_when_fully_relayed &&
664 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800665 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700666 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200667 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800668 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800669 sdp_semantics == o.sdp_semantics &&
670 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800671}
672
673bool PeerConnectionInterface::RTCConfiguration::operator!=(
674 const PeerConnectionInterface::RTCConfiguration& o) const {
675 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800676}
677
zhihuang8f65cdf2016-05-06 18:40:30 -0700678// Generate a RTCP CNAME when a PeerConnection is created.
679std::string GenerateRtcpCname() {
680 std::string cname;
681 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100682 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800683 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700684 }
685 return cname;
686}
687
zhihuang1c378ed2017-08-17 14:10:50 -0700688bool ValidateOfferAnswerOptions(
689 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
690 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
691 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700692}
693
zhihuang1c378ed2017-08-17 14:10:50 -0700694// From |rtc_options|, fill parts of |session_options| shared by all generated
695// m= sections (in other words, nothing that involves a map/array).
696void ExtractSharedMediaSessionOptions(
697 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
698 cricket::MediaSessionOptions* session_options) {
699 session_options->vad_enabled = rtc_options.voice_activity_detection;
700 session_options->bundle_enabled = rtc_options.use_rtp_mux;
701}
zhihuanga77e6bb2017-08-14 18:17:48 -0700702
zhihuang1c378ed2017-08-17 14:10:50 -0700703bool ConvertConstraintsToOfferAnswerOptions(
704 const MediaConstraintsInterface* constraints,
705 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700706 if (!constraints) {
707 return true;
708 }
zhihuang1c378ed2017-08-17 14:10:50 -0700709
710 bool value = false;
711 size_t mandatory_constraints_satisfied = 0;
712
713 if (FindConstraint(constraints,
714 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
715 &mandatory_constraints_satisfied)) {
716 offer_answer_options->offer_to_receive_audio =
717 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
718 kOfferToReceiveMediaTrue
719 : 0;
720 }
721
722 if (FindConstraint(constraints,
723 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
724 &mandatory_constraints_satisfied)) {
725 offer_answer_options->offer_to_receive_video =
726 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
727 kOfferToReceiveMediaTrue
728 : 0;
729 }
730 if (FindConstraint(constraints,
731 MediaConstraintsInterface::kVoiceActivityDetection, &value,
732 &mandatory_constraints_satisfied)) {
733 offer_answer_options->voice_activity_detection = value;
734 }
735 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
736 &mandatory_constraints_satisfied)) {
737 offer_answer_options->use_rtp_mux = value;
738 }
739 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
740 &value, &mandatory_constraints_satisfied)) {
741 offer_answer_options->ice_restart = value;
742 }
743
deadbeefab9b2d12015-10-14 11:33:11 -0700744 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
745}
746
zhihuang38ede132017-06-15 12:52:32 -0700747PeerConnection::PeerConnection(PeerConnectionFactory* factory,
748 std::unique_ptr<RtcEventLog> event_log,
749 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700751 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700752 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700753 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700754 remote_streams_(StreamCollection::Create()),
755 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
757PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100758 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800759 RTC_DCHECK_RUN_ON(signaling_thread());
760
Steve Anton8af21862017-12-15 11:20:13 -0800761 // Need to stop transceivers before destroying the stats collector because
762 // AudioRtpSender has a reference to the StatsCollector it will update when
763 // stopping.
764 for (auto transceiver : transceivers_) {
765 transceiver->Stop();
766 }
Steve Anton4171afb2017-11-20 10:20:22 -0800767
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700768 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800769 if (stats_collector_) {
770 stats_collector_->WaitForPendingRequest();
771 stats_collector_ = nullptr;
772 }
Steve Anton75737c02017-11-06 10:37:17 -0800773
Steve Anton8af21862017-12-15 11:20:13 -0800774 // Don't destroy BaseChannels until after stats has been cleaned up so that
775 // the last stats request can still read from the channels.
776 DestroyAllChannels();
777
Mirko Bonadei675513b2017-11-09 11:09:25 +0100778 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800779
780 webrtc_session_desc_factory_.reset();
781 sctp_invoker_.reset();
782 sctp_factory_.reset();
783 transport_controller_.reset();
784
deadbeef91dd5672016-05-18 16:55:30 -0700785 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700786 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700787 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700788 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700789 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700790 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800791 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700792 event_log_.reset();
793 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794}
795
Steve Anton8af21862017-12-15 11:20:13 -0800796void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800797 // Destroy video channels first since they may have a pointer to a voice
798 // channel.
799 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800800 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800801 DestroyTransceiverChannel(transceiver);
802 }
803 }
804 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800805 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800806 DestroyTransceiverChannel(transceiver);
807 }
808 }
809 DestroyDataChannel();
810}
811
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000813 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700814 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200815 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800816 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100817 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700818
819 RTCError config_error = ValidateConfiguration(configuration);
820 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100821 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700822 return false;
823 }
824
deadbeef293e9262017-01-11 12:28:30 -0800825 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100826 RTC_LOG(LS_ERROR)
827 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100828 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800829 return false;
830 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200831
deadbeef653b8e02015-11-11 12:55:10 -0800832 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800833 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100834 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100835 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800836 return false;
837 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000838 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800839 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800840
deadbeef91dd5672016-05-18 16:55:30 -0700841 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700843 if (!network_thread()->Invoke<bool>(
844 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
845 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 return false;
847 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848
Steve Anton75737c02017-11-06 10:37:17 -0800849 // RFC 3264: The numeric value of the session id and version in the
850 // o line MUST be representable with a "64 bit signed integer".
851 // Due to this constraint session id |session_id_| is max limited to
852 // LLONG_MAX.
853 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
854 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800855 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
856 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800857 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
858 transport_controller_->SignalConnectionState.connect(
859 this, &PeerConnection::OnTransportControllerConnectionState);
860 transport_controller_->SignalGatheringState.connect(
861 this, &PeerConnection::OnTransportControllerGatheringState);
862 transport_controller_->SignalCandidatesGathered.connect(
863 this, &PeerConnection::OnTransportControllerCandidatesGathered);
864 transport_controller_->SignalCandidatesRemoved.connect(
865 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
866 transport_controller_->SignalDtlsHandshakeError.connect(
867 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
868
869 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700870
deadbeefab9b2d12015-10-14 11:33:11 -0700871 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700872 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873
Steve Antonba818672017-11-06 10:21:57 -0800874 configuration_ = configuration;
875
Steve Anton75737c02017-11-06 10:37:17 -0800876 const PeerConnectionFactoryInterface::Options& options = factory_->options();
877
878 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
879
880 // Obtain a certificate from RTCConfiguration if any were provided (optional).
881 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
882 if (!configuration.certificates.empty()) {
883 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
884 // just picking the first one. The decision should be made based on the DTLS
885 // handshake. The DTLS negotiations need to know about all certificates.
886 certificate = configuration.certificates[0];
887 }
888
Steve Antond25da372017-11-06 14:50:29 -0800889 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800890
891 if (options.disable_encryption) {
892 dtls_enabled_ = false;
893 } else {
894 // Enable DTLS by default if we have an identity store or a certificate.
895 dtls_enabled_ = (cert_generator || certificate);
896 // |configuration| can override the default |dtls_enabled_| value.
897 if (configuration.enable_dtls_srtp) {
898 dtls_enabled_ = *(configuration.enable_dtls_srtp);
899 }
900 }
901
902 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
903 // It takes precendence over the disable_sctp_data_channels
904 // PeerConnectionFactoryInterface::Options.
905 if (configuration.enable_rtp_data_channel) {
906 data_channel_type_ = cricket::DCT_RTP;
907 } else {
908 // DTLS has to be enabled to use SCTP.
909 if (!options.disable_sctp_data_channels && dtls_enabled_) {
910 data_channel_type_ = cricket::DCT_SCTP;
911 }
912 }
913
914 video_options_.screencast_min_bitrate_kbps =
915 configuration.screencast_min_bitrate;
916 audio_options_.combined_audio_video_bwe =
917 configuration.combined_audio_video_bwe;
918
919 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100920 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800921
922 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100923 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800924
925 // Whether the certificate generator/certificate is null or not determines
926 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
927 // the right instructions by clearing the variables if needed.
928 if (!dtls_enabled_) {
929 cert_generator.reset();
930 certificate = nullptr;
931 } else if (certificate) {
932 // Favor generated certificate over the certificate generator.
933 cert_generator.reset();
934 }
935
936 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
937 signaling_thread(), channel_manager(), this, session_id(),
938 std::move(cert_generator), certificate));
939 webrtc_session_desc_factory_->SignalCertificateReady.connect(
940 this, &PeerConnection::OnCertificateReady);
941
942 if (options.disable_encryption) {
943 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
944 }
945
946 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
947 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948
Steve Anton4171afb2017-11-20 10:20:22 -0800949 // Add default audio/video transceivers for Plan B SDP.
950 if (!IsUnifiedPlan()) {
951 transceivers_.push_back(
952 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
953 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
954 transceivers_.push_back(
955 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
956 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
957 }
958
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 return true;
960}
961
Steve Anton038834f2017-07-14 15:59:59 -0700962RTCError PeerConnection::ValidateConfiguration(
963 const RTCConfiguration& config) const {
964 if (config.ice_regather_interval_range &&
965 config.continual_gathering_policy == GATHER_ONCE) {
966 return RTCError(RTCErrorType::INVALID_PARAMETER,
967 "ice_regather_interval_range specified but continual "
968 "gathering policy is GATHER_ONCE");
969 }
970 return RTCError::OK();
971}
972
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000973rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700975 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976}
977
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000978rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700980 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000981}
982
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000983bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100984 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 if (IsClosed()) {
986 return false;
987 }
deadbeefab9b2d12015-10-14 11:33:11 -0700988 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 return false;
990 }
deadbeefab9b2d12015-10-14 11:33:11 -0700991
992 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800993 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
994 observer->SignalAudioTrackAdded.connect(this,
995 &PeerConnection::OnAudioTrackAdded);
996 observer->SignalAudioTrackRemoved.connect(
997 this, &PeerConnection::OnAudioTrackRemoved);
998 observer->SignalVideoTrackAdded.connect(this,
999 &PeerConnection::OnVideoTrackAdded);
1000 observer->SignalVideoTrackRemoved.connect(
1001 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001002 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001003
deadbeefab9b2d12015-10-14 11:33:11 -07001004 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001005 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001006 }
1007 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001008 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001009 }
1010
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001011 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 observer_->OnRenegotiationNeeded();
1013 return true;
1014}
1015
1016void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001017 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001018 if (!IsClosed()) {
1019 for (const auto& track : local_stream->GetAudioTracks()) {
1020 RemoveAudioTrack(track.get(), local_stream);
1021 }
1022 for (const auto& track : local_stream->GetVideoTracks()) {
1023 RemoveVideoTrack(track.get(), local_stream);
1024 }
deadbeefab9b2d12015-10-14 11:33:11 -07001025 }
deadbeefab9b2d12015-10-14 11:33:11 -07001026 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001027 stream_observers_.erase(
1028 std::remove_if(
1029 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001030 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001031 return observer->stream()->label().compare(local_stream->label()) ==
1032 0;
1033 }),
1034 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001035
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036 if (IsClosed()) {
1037 return;
1038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 observer_->OnRenegotiationNeeded();
1040}
1041
deadbeefe1f9d832016-01-14 15:35:42 -08001042rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1043 MediaStreamTrackInterface* track,
1044 std::vector<MediaStreamInterface*> streams) {
1045 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001046 std::vector<std::string> stream_labels;
1047 for (auto* stream : streams) {
1048 if (!stream) {
1049 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1050 return nullptr;
1051 }
1052 stream_labels.push_back(stream->label());
1053 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001054 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001055 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001056 return nullptr;
1057 }
Steve Antonf9381f02017-12-14 10:23:57 -08001058 return sender_or_error.MoveValue();
1059}
1060
Steve Anton2d6c76a2018-01-05 17:10:52 -08001061RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001062 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1063 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001064 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001065 if (!track) {
1066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1067 }
1068 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1069 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1071 "Track has invalid kind: " + track->kind());
1072 }
1073 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1074 if (stream_labels.size() > 1u) {
1075 LOG_AND_RETURN_ERROR(
1076 RTCErrorType::UNSUPPORTED_OPERATION,
1077 "AddTrack with more than one stream is not currently supported.");
1078 }
1079 if (IsClosed()) {
1080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1081 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001082 }
Steve Anton4171afb2017-11-20 10:20:22 -08001083 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001084 LOG_AND_RETURN_ERROR(
1085 RTCErrorType::INVALID_PARAMETER,
1086 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001087 }
Steve Antonf9381f02017-12-14 10:23:57 -08001088 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1089 // one stream. AddTrackInternal will return an error if there is more than one
1090 // stream, but if the caller specifies none then we need to generate a random
1091 // stream label.
1092 std::vector<std::string> adjusted_stream_labels = stream_labels;
1093 if (stream_labels.empty()) {
1094 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1095 }
1096 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1097 auto sender_or_error =
1098 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1099 : AddTrackPlanB(track, adjusted_stream_labels));
1100 if (sender_or_error.ok()) {
1101 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001102 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001103 }
1104 return sender_or_error;
1105}
deadbeefe1f9d832016-01-14 15:35:42 -08001106
Steve Antonf9381f02017-12-14 10:23:57 -08001107RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1108PeerConnection::AddTrackPlanB(
1109 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1110 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001111 cricket::MediaType media_type =
1112 (track->kind() == MediaStreamTrackInterface::kAudioKind
1113 ? cricket::MEDIA_TYPE_AUDIO
1114 : cricket::MEDIA_TYPE_VIDEO);
1115 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001116 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton56bae8d2018-02-14 16:07:42 -08001117 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001118 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001119 const RtpSenderInfo* sender_info =
1120 FindSenderInfo(local_audio_sender_infos_,
1121 new_sender->internal()->stream_id(), track->id());
1122 if (sender_info) {
1123 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001124 }
Steve Antonf9381f02017-12-14 10:23:57 -08001125 } else {
1126 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton56bae8d2018-02-14 16:07:42 -08001127 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001128 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001129 const RtpSenderInfo* sender_info =
1130 FindSenderInfo(local_video_sender_infos_,
1131 new_sender->internal()->stream_id(), track->id());
1132 if (sender_info) {
1133 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001134 }
deadbeefe1f9d832016-01-14 15:35:42 -08001135 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001136 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001137}
deadbeefe1f9d832016-01-14 15:35:42 -08001138
Steve Antonf9381f02017-12-14 10:23:57 -08001139RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1140PeerConnection::AddTrackUnifiedPlan(
1141 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1142 const std::vector<std::string>& stream_labels) {
1143 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1144 if (transceiver) {
1145 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1146 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1147 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1148 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1149 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001150 transceiver->sender()->SetTrack(track);
1151 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001152 } else {
1153 cricket::MediaType media_type =
1154 (track->kind() == MediaStreamTrackInterface::kAudioKind
1155 ? cricket::MEDIA_TYPE_AUDIO
1156 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001157 auto sender = CreateSender(media_type, track, stream_labels);
1158 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1159 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001160 transceiver->internal()->set_created_by_addtrack(true);
1161 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1162 }
Steve Antonf9381f02017-12-14 10:23:57 -08001163 return transceiver->sender();
1164}
1165
1166rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1167PeerConnection::FindFirstTransceiverForAddedTrack(
1168 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1169 RTC_DCHECK(track);
1170 for (auto transceiver : transceivers_) {
1171 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001172 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001173 track->kind() &&
1174 !transceiver->internal()->has_ever_been_used_to_send()) {
1175 return transceiver;
1176 }
1177 }
1178 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001179}
1180
1181bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1182 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001183 return RemoveTrackInternal(sender).ok();
1184}
1185
1186RTCError PeerConnection::RemoveTrackInternal(
1187 rtc::scoped_refptr<RtpSenderInterface> sender) {
1188 if (!sender) {
1189 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1190 }
deadbeefe1f9d832016-01-14 15:35:42 -08001191 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001192 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1193 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
Steve Antonf9381f02017-12-14 10:23:57 -08001195 if (IsUnifiedPlan()) {
1196 auto transceiver = FindTransceiverBySender(sender);
1197 if (!transceiver || !sender->track()) {
1198 return RTCError::OK();
1199 }
1200 sender->SetTrack(nullptr);
1201 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1202 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1203 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1204 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1205 }
Steve Anton4171afb2017-11-20 10:20:22 -08001206 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001207 bool removed;
1208 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1209 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1210 } else {
1211 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1212 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1213 }
1214 if (!removed) {
1215 LOG_AND_RETURN_ERROR(
1216 RTCErrorType::INVALID_PARAMETER,
1217 "Couldn't find sender " + sender->id() + " to remove.");
1218 }
Steve Anton4171afb2017-11-20 10:20:22 -08001219 }
deadbeefe1f9d832016-01-14 15:35:42 -08001220 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001221 return RTCError::OK();
1222}
1223
1224rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1225PeerConnection::FindTransceiverBySender(
1226 rtc::scoped_refptr<RtpSenderInterface> sender) {
1227 for (auto transceiver : transceivers_) {
1228 if (transceiver->sender() == sender) {
1229 return transceiver;
1230 }
1231 }
1232 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001233}
1234
Steve Anton9158ef62017-11-27 13:01:52 -08001235RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1236PeerConnection::AddTransceiver(
1237 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1238 return AddTransceiver(track, RtpTransceiverInit());
1239}
1240
1241RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1242PeerConnection::AddTransceiver(
1243 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1244 const RtpTransceiverInit& init) {
1245 if (!IsUnifiedPlan()) {
1246 LOG_AND_RETURN_ERROR(
1247 RTCErrorType::INTERNAL_ERROR,
1248 "AddTransceiver only supported when Unified Plan is enabled.");
1249 }
1250 if (!track) {
1251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1252 }
1253 cricket::MediaType media_type;
1254 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1255 media_type = cricket::MEDIA_TYPE_AUDIO;
1256 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1257 media_type = cricket::MEDIA_TYPE_VIDEO;
1258 } else {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1260 "Track kind is not audio or video");
1261 }
1262 return AddTransceiver(media_type, track, init);
1263}
1264
1265RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1266PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1267 return AddTransceiver(media_type, RtpTransceiverInit());
1268}
1269
1270RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1271PeerConnection::AddTransceiver(cricket::MediaType media_type,
1272 const RtpTransceiverInit& init) {
1273 if (!IsUnifiedPlan()) {
1274 LOG_AND_RETURN_ERROR(
1275 RTCErrorType::INTERNAL_ERROR,
1276 "AddTransceiver only supported when Unified Plan is enabled.");
1277 }
1278 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1279 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1281 "media type is not audio or video");
1282 }
1283 return AddTransceiver(media_type, nullptr, init);
1284}
1285
1286RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1287PeerConnection::AddTransceiver(
1288 cricket::MediaType media_type,
1289 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001290 const RtpTransceiverInit& init,
1291 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001292 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1293 media_type == cricket::MEDIA_TYPE_VIDEO));
1294 if (track) {
1295 RTC_DCHECK_EQ(media_type,
1296 (track->kind() == MediaStreamTrackInterface::kAudioKind
1297 ? cricket::MEDIA_TYPE_AUDIO
1298 : cricket::MEDIA_TYPE_VIDEO));
1299 }
1300
1301 // TODO(bugs.webrtc.org/7600): Verify init.
1302
Steve Anton02ee47c2018-01-10 16:26:06 -08001303 if (init.stream_labels.size() > 1u) {
1304 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1305 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001306 }
1307
Steve Anton02ee47c2018-01-10 16:26:06 -08001308 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1309 ? init.stream_labels[0]
1310 : rtc::CreateRandomUuid()};
1311
1312 auto sender = CreateSender(media_type, track, stream_labels);
1313 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1314 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1315 transceiver->internal()->set_direction(init.direction);
1316
Steve Anton22da89f2018-01-25 13:58:07 -08001317 if (fire_callback) {
1318 observer_->OnRenegotiationNeeded();
1319 }
Steve Antonf9381f02017-12-14 10:23:57 -08001320
1321 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1322}
1323
Steve Anton02ee47c2018-01-10 16:26:06 -08001324rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1325PeerConnection::CreateSender(
1326 cricket::MediaType media_type,
1327 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1328 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001329 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001330 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1331 RTC_DCHECK(!track ||
1332 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1333 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1334 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001335 new AudioRtpSender(worker_thread(),
1336 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001337 stream_labels, stats_.get()));
1338 } else {
1339 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1340 RTC_DCHECK(!track ||
1341 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1342 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1343 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001344 new VideoRtpSender(worker_thread(),
1345 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001346 stream_labels));
1347 }
1348 sender->internal()->set_stream_ids(stream_labels);
1349 return sender;
1350}
1351
1352rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1353PeerConnection::CreateReceiver(cricket::MediaType media_type,
1354 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001355 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1356 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001357 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001358 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001359 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001360 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001361 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001362 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001363 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1364 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001365 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001366 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001367 return receiver;
1368}
1369
1370rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1371PeerConnection::CreateAndAddTransceiver(
1372 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1373 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1374 receiver) {
1375 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1376 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001377 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001379}
1380
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001381rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001382 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001383 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001384 if (IsClosed()) {
1385 return nullptr;
1386 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001388 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001389 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 }
Steve Anton4171afb2017-11-20 10:20:22 -08001391 auto track_sender = FindSenderForTrack(track);
1392 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001393 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001394 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 }
1396
Steve Anton4171afb2017-11-20 10:20:22 -08001397 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398}
1399
deadbeeffac06552015-11-25 11:26:01 -08001400rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001401 const std::string& kind,
1402 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001403 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001404 if (IsClosed()) {
1405 return nullptr;
1406 }
Steve Anton4171afb2017-11-20 10:20:22 -08001407
Steve Anton02ee47c2018-01-10 16:26:06 -08001408 std::vector<std::string> stream_labels;
1409 if (!stream_id.empty()) {
1410 stream_labels.push_back(stream_id);
1411 }
1412
Steve Anton4171afb2017-11-20 10:20:22 -08001413 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001414 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001415 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001416 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1417 stream_labels, stats_.get());
Steve Anton56bae8d2018-02-14 16:07:42 -08001418 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001419 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001421 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001422 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001423 auto* video_sender =
1424 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Steve Anton56bae8d2018-02-14 16:07:42 -08001425 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001426 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001427 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001428 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001429 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001430 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001431 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001432 }
Steve Anton4171afb2017-11-20 10:20:22 -08001433
deadbeefe1f9d832016-01-14 15:35:42 -08001434 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001435}
1436
deadbeef70ab1a12015-09-28 16:53:55 -07001437std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1438 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001439 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001440 for (auto sender : GetSendersInternal()) {
1441 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001442 }
1443 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001444}
1445
Steve Anton4171afb2017-11-20 10:20:22 -08001446std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1447PeerConnection::GetSendersInternal() const {
1448 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1449 all_senders;
1450 for (auto transceiver : transceivers_) {
1451 auto senders = transceiver->internal()->senders();
1452 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1453 }
1454 return all_senders;
1455}
1456
deadbeef70ab1a12015-09-28 16:53:55 -07001457std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1458PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001459 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001460 for (const auto& receiver : GetReceiversInternal()) {
1461 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001462 }
1463 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001464}
1465
Steve Anton4171afb2017-11-20 10:20:22 -08001466std::vector<
1467 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1468PeerConnection::GetReceiversInternal() const {
1469 std::vector<
1470 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1471 all_receivers;
1472 for (auto transceiver : transceivers_) {
1473 auto receivers = transceiver->internal()->receivers();
1474 all_receivers.insert(all_receivers.end(), receivers.begin(),
1475 receivers.end());
1476 }
1477 return all_receivers;
1478}
1479
Steve Anton9158ef62017-11-27 13:01:52 -08001480std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1481PeerConnection::GetTransceivers() const {
1482 RTC_DCHECK(IsUnifiedPlan());
1483 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1484 for (auto transceiver : transceivers_) {
1485 all_transceivers.push_back(transceiver);
1486 }
1487 return all_transceivers;
1488}
1489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001491 MediaStreamTrackInterface* track,
1492 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001493 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001494 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001495 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001496 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497 return false;
1498 }
1499
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001500 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001501 // The StatsCollector is used to tell if a track is valid because it may
1502 // remember tracks that the PeerConnection previously removed.
1503 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1505 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001506 return false;
1507 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001508 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001509 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 return true;
1511}
1512
hbos74e1a4f2016-09-15 23:33:01 -07001513void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1514 RTC_DCHECK(stats_collector_);
1515 stats_collector_->GetStatsReport(callback);
1516}
1517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1519 return signaling_state_;
1520}
1521
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522PeerConnectionInterface::IceConnectionState
1523PeerConnection::ice_connection_state() {
1524 return ice_connection_state_;
1525}
1526
1527PeerConnectionInterface::IceGatheringState
1528PeerConnection::ice_gathering_state() {
1529 return ice_gathering_state_;
1530}
1531
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001532rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533PeerConnection::CreateDataChannel(
1534 const std::string& label,
1535 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001536 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001537
deadbeefab9b2d12015-10-14 11:33:11 -07001538 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001539
kwibergd1fe2812016-04-27 06:47:29 -07001540 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001541 if (config) {
1542 internal_config.reset(new InternalDataChannelInit(*config));
1543 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001544 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001545 InternalCreateDataChannel(label, internal_config.get()));
1546 if (!channel.get()) {
1547 return nullptr;
1548 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001550 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1551 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001552 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001553 observer_->OnRenegotiationNeeded();
1554 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001555
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556 return DataChannelProxy::Create(signaling_thread(), channel.get());
1557}
1558
1559void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1560 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001561 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001562
zhihuang1c378ed2017-08-17 14:10:50 -07001563 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1564 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1565 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1566 // compares the mandatory fields parsed with the mandatory fields added in the
1567 // |constraints| and some downstream applications might create offers with
1568 // mandatory fields which would not be parsed in the helper method. For
1569 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1570 // |constraints| as a mandatory field but it is not parsed.
1571 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001572
zhihuang1c378ed2017-08-17 14:10:50 -07001573 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001574}
1575
1576void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1577 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001578 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001579
nisse7ce109a2017-01-31 00:57:56 -08001580 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001582 return;
1583 }
deadbeefab9b2d12015-10-14 11:33:11 -07001584
Steve Anton8d3444d2017-10-20 15:30:51 -07001585 if (IsClosed()) {
1586 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001587 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001588 PostCreateSessionDescriptionFailure(observer, error);
1589 return;
1590 }
1591
zhihuang1c378ed2017-08-17 14:10:50 -07001592 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001593 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001594 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001595 PostCreateSessionDescriptionFailure(observer, error);
1596 return;
1597 }
1598
Steve Anton22da89f2018-01-25 13:58:07 -08001599 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1600 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1601 if (IsUnifiedPlan()) {
1602 RTCError error = HandleLegacyOfferOptions(options);
1603 if (!error.ok()) {
1604 PostCreateSessionDescriptionFailure(observer, error.message());
1605 return;
1606 }
1607 }
1608
zhihuang1c378ed2017-08-17 14:10:50 -07001609 cricket::MediaSessionOptions session_options;
1610 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001611 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612}
1613
Steve Anton22da89f2018-01-25 13:58:07 -08001614RTCError PeerConnection::HandleLegacyOfferOptions(
1615 const RTCOfferAnswerOptions& options) {
1616 RTC_DCHECK(IsUnifiedPlan());
1617
1618 if (options.offer_to_receive_audio == 0) {
1619 RemoveRecvDirectionFromReceivingTransceiversOfType(
1620 cricket::MEDIA_TYPE_AUDIO);
1621 } else if (options.offer_to_receive_audio == 1) {
1622 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1623 } else if (options.offer_to_receive_audio > 1) {
1624 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1625 "offer_to_receive_audio > 1 is not supported.");
1626 }
1627
1628 if (options.offer_to_receive_video == 0) {
1629 RemoveRecvDirectionFromReceivingTransceiversOfType(
1630 cricket::MEDIA_TYPE_VIDEO);
1631 } else if (options.offer_to_receive_video == 1) {
1632 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1633 } else if (options.offer_to_receive_video > 1) {
1634 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1635 "offer_to_receive_video > 1 is not supported.");
1636 }
1637
1638 return RTCError::OK();
1639}
1640
1641void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1642 cricket::MediaType media_type) {
1643 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1644 transceiver->internal()->set_direction(
1645 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1646 }
1647}
1648
1649void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1650 cricket::MediaType media_type) {
1651 if (GetReceivingTransceiversOfType(media_type).empty()) {
1652 RtpTransceiverInit init;
1653 init.direction = RtpTransceiverDirection::kRecvOnly;
1654 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1655 }
1656}
1657
1658std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1659PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1660 std::vector<
1661 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1662 receiving_transceivers;
1663 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001664 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001665 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1666 receiving_transceivers.push_back(transceiver);
1667 }
1668 }
1669 return receiving_transceivers;
1670}
1671
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672void PeerConnection::CreateAnswer(
1673 CreateSessionDescriptionObserver* observer,
1674 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001675 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001676
nisse7ce109a2017-01-31 00:57:56 -08001677 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001678 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679 return;
1680 }
deadbeefab9b2d12015-10-14 11:33:11 -07001681
zhihuang1c378ed2017-08-17 14:10:50 -07001682 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1683 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1684 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001685 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001686 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001687 PostCreateSessionDescriptionFailure(observer, error);
1688 return;
1689 }
1690
Steve Anton8d3444d2017-10-20 15:30:51 -07001691 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001692}
1693
1694void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1695 const RTCOfferAnswerOptions& options) {
1696 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001697 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001698 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001699 return;
1700 }
1701
Steve Antondffead82018-02-06 10:31:29 -08001702 if (!(signaling_state_ == kHaveRemoteOffer ||
1703 signaling_state_ == kHaveLocalPrAnswer)) {
1704 std::string error =
1705 "PeerConnection cannot create an answer in a state other than "
1706 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001707 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001708 PostCreateSessionDescriptionFailure(observer, error);
1709 return;
1710 }
1711
Steve Antondffead82018-02-06 10:31:29 -08001712 // The remote description should be set if we're in the right state.
1713 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001714
Steve Anton22da89f2018-01-25 13:58:07 -08001715 if (IsUnifiedPlan()) {
1716 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1717 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1718 "supported with Unified Plan semantics. Use the "
1719 "RtpTransceiver API instead.";
1720 }
1721 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1722 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1723 "supported with Unified Plan semantics. Use the "
1724 "RtpTransceiver API instead.";
1725 }
1726 }
1727
htaa2a49d92016-03-04 02:51:39 -08001728 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001729 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001730
Steve Antond25da372017-11-06 14:50:29 -08001731 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001732}
1733
1734void PeerConnection::SetLocalDescription(
1735 SetSessionDescriptionObserver* observer,
1736 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001737 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001738
nisse7ce109a2017-01-31 00:57:56 -08001739 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 return;
1742 }
Steve Anton8a006912017-12-04 15:25:56 -08001743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 if (!desc) {
1745 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1746 return;
1747 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001748
Steve Antona3a92c22017-12-07 10:27:41 -08001749 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001750
Steve Anton8a006912017-12-04 15:25:56 -08001751 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1752 // |desc| may be destroyed at this point.
1753
1754 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001755 std::ostringstream oss;
1756 oss << "Failed to set local " << SdpTypeToString(type)
1757 << " sdp: " << error.message();
1758 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001759 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1760 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001761 return;
1762 }
Steve Anton8a006912017-12-04 15:25:56 -08001763 RTC_DCHECK(local_description());
1764
1765 PostSetSessionDescriptionSuccess(observer);
1766
1767 // According to JSEP, after setLocalDescription, changing the candidate pool
1768 // size is not allowed, and changing the set of ICE servers will not result
1769 // in new candidates being gathered.
1770 port_allocator_->FreezeCandidatePool();
1771
1772 // MaybeStartGathering needs to be called after posting
1773 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1774 // before signaling that SetLocalDescription completed.
1775 transport_controller_->MaybeStartGathering();
1776
Steve Antona3a92c22017-12-07 10:27:41 -08001777 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001778 // TODO(deadbeef): We already had to hop to the network thread for
1779 // MaybeStartGathering...
1780 network_thread()->Invoke<void>(
1781 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1782 port_allocator_.get()));
1783 }
1784}
1785
1786RTCError PeerConnection::ApplyLocalDescription(
1787 std::unique_ptr<SessionDescriptionInterface> desc) {
1788 RTC_DCHECK_RUN_ON(signaling_thread());
1789 RTC_DCHECK(desc);
1790
1791 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1792 if (!error.ok()) {
1793 return error;
1794 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796 // Update stats here so that we have the most recent stats for tracks and
1797 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001798 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001799
1800 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001801 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001802 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001803 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001804 if (*initial_offerer_) {
1805 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1806 } else {
1807 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1808 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 }
Steve Anton8a006912017-12-04 15:25:56 -08001810
Steve Antondcc3c022017-12-22 16:02:54 -08001811 // Take a reference to the old local description since it's used below to
1812 // compare against the new local description. When setting the new local
1813 // description, grab ownership of the replaced session description in case it
1814 // is the same as |old_local_description|, to keep it alive for the duration
1815 // of the method.
1816 const SessionDescriptionInterface* old_local_description =
1817 local_description();
1818 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001819 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001820 replaced_local_description = pending_local_description_
1821 ? std::move(pending_local_description_)
1822 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001823 current_local_description_ = std::move(desc);
1824 pending_local_description_ = nullptr;
1825 current_remote_description_ = std::move(pending_remote_description_);
1826 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001827 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001828 pending_local_description_ = std::move(desc);
1829 }
1830 // The session description to apply now must be accessed by
1831 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001832 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001833
Steve Antondcc3c022017-12-22 16:02:54 -08001834 if (IsUnifiedPlan()) {
1835 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001836 cricket::CS_LOCAL, *local_description(), old_local_description,
1837 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001838 if (!error.ok()) {
1839 return error;
1840 }
Steve Antondcc3c022017-12-22 16:02:54 -08001841 for (auto transceiver : transceivers_) {
1842 const ContentInfo* content =
1843 FindMediaSectionForTransceiver(transceiver, local_description());
1844 if (!content) {
1845 continue;
1846 }
1847 const MediaContentDescription* media_desc = content->media_description();
1848 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1849 transceiver->internal()->set_current_direction(media_desc->direction());
1850 }
1851 if (content->rejected && !transceiver->stopped()) {
1852 transceiver->Stop();
1853 }
1854 }
1855 } else {
1856 // Transport and Media channels will be created only when offer is set.
1857 if (type == SdpType::kOffer) {
1858 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1859 // description is applied. Restore back to old description.
1860 RTCError error = CreateChannels(*local_description()->description());
1861 if (!error.ok()) {
1862 return error;
1863 }
1864 }
Steve Anton8a006912017-12-04 15:25:56 -08001865
Steve Antondcc3c022017-12-22 16:02:54 -08001866 // Remove unused channels if MediaContentDescription is rejected.
1867 RemoveUnusedChannels(local_description()->description());
1868 }
Steve Anton8a006912017-12-04 15:25:56 -08001869
Steve Anton3828c062017-12-06 10:34:51 -08001870 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001871 if (!error.ok()) {
1872 return error;
1873 }
Steve Antondcc3c022017-12-22 16:02:54 -08001874
Steve Anton8a006912017-12-04 15:25:56 -08001875 if (remote_description()) {
1876 // Now that we have a local description, we can push down remote candidates.
1877 UseCandidatesInSessionDescription(remote_description());
1878 }
1879
1880 pending_ice_restarts_.clear();
1881 if (session_error() != SessionError::kNone) {
1882 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1883 }
1884
deadbeefab9b2d12015-10-14 11:33:11 -07001885 // If setting the description decided our SSL role, allocate any necessary
1886 // SCTP sids.
1887 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001888 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001889 AllocateSctpSids(role);
1890 }
1891
Steve Antond3679212018-01-17 17:41:02 -08001892 if (IsUnifiedPlan()) {
1893 for (auto transceiver : transceivers_) {
1894 const ContentInfo* content =
1895 FindMediaSectionForTransceiver(transceiver, local_description());
1896 if (!content) {
1897 continue;
1898 }
1899 if (content->rejected && !transceiver->stopped()) {
1900 transceiver->Stop();
1901 }
Steve Anton74255ff2018-01-24 18:32:57 -08001902 const auto& streams = content->media_description()->streams();
1903 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001904 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001905 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001906 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001907 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001908 }
1909 }
1910 } else {
1911 // Plan B semantics.
1912
Steve Antondcc3c022017-12-22 16:02:54 -08001913 // Update state and SSRC of local MediaStreams and DataChannels based on the
1914 // local session description.
1915 const cricket::ContentInfo* audio_content =
1916 GetFirstAudioContent(local_description()->description());
1917 if (audio_content) {
1918 if (audio_content->rejected) {
1919 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1920 } else {
1921 const cricket::AudioContentDescription* audio_desc =
1922 audio_content->media_description()->as_audio();
1923 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1924 }
deadbeeffaac4972015-11-12 15:33:07 -08001925 }
deadbeefab9b2d12015-10-14 11:33:11 -07001926
Steve Antondcc3c022017-12-22 16:02:54 -08001927 const cricket::ContentInfo* video_content =
1928 GetFirstVideoContent(local_description()->description());
1929 if (video_content) {
1930 if (video_content->rejected) {
1931 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1932 } else {
1933 const cricket::VideoContentDescription* video_desc =
1934 video_content->media_description()->as_video();
1935 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1936 }
deadbeeffaac4972015-11-12 15:33:07 -08001937 }
deadbeefab9b2d12015-10-14 11:33:11 -07001938 }
1939
1940 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001941 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001942 if (data_content) {
1943 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001944 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001945 if (rtc::starts_with(data_desc->protocol().data(),
1946 cricket::kMediaProtocolRtpPrefix)) {
1947 UpdateLocalRtpDataChannels(data_desc->streams());
1948 }
1949 }
1950
Steve Anton8a006912017-12-04 15:25:56 -08001951 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952}
1953
1954void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001955 SetSessionDescriptionObserver* observer,
1956 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001957 SetRemoteDescription(
1958 std::unique_ptr<SessionDescriptionInterface>(desc),
1959 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1960 new SetRemoteDescriptionObserverAdapter(this, observer)));
1961}
1962
1963void PeerConnection::SetRemoteDescription(
1964 std::unique_ptr<SessionDescriptionInterface> desc,
1965 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001966 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001967
nisse7ce109a2017-01-31 00:57:56 -08001968 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001969 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return;
1971 }
Steve Anton8a006912017-12-04 15:25:56 -08001972
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001974 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001975 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 return;
1977 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001978
Steve Antona3a92c22017-12-07 10:27:41 -08001979 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001980
1981 RTCError error = ApplyRemoteDescription(std::move(desc));
1982 // |desc| may be destroyed at this point.
1983
1984 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001985 std::ostringstream oss;
1986 oss << "Failed to set remote " << SdpTypeToString(type)
1987 << " sdp: " << error.message();
1988 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001989 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001990 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001991 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001992 return;
1993 }
1994
Steve Antona3a92c22017-12-07 10:27:41 -08001995 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001996 // TODO(deadbeef): We already had to hop to the network thread for
1997 // MaybeStartGathering...
1998 network_thread()->Invoke<void>(
1999 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2000 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002001 // Make UMA notes about what was agreed to.
2002 if (uma_observer_) {
2003 switch (remote_description()->description()->msid_signaling()) {
2004 case 0:
2005 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2006 kSdpSemanticNegotiatedNone,
2007 kSdpSemanticNegotiatedMax);
2008 break;
2009 case cricket::kMsidSignalingMediaSection:
2010 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2011 kSdpSemanticNegotiatedUnifiedPlan,
2012 kSdpSemanticNegotiatedMax);
2013 break;
2014 case cricket::kMsidSignalingSsrcAttribute:
2015 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2016 kSdpSemanticNegotiatedPlanB,
2017 kSdpSemanticNegotiatedMax);
2018 break;
2019 case cricket::kMsidSignalingMediaSection |
2020 cricket::kMsidSignalingSsrcAttribute:
2021 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2022 kSdpSemanticNegotiatedMixed,
2023 kSdpSemanticNegotiatedMax);
2024 break;
2025 default:
2026 RTC_NOTREACHED();
2027 }
2028 }
Steve Anton8a006912017-12-04 15:25:56 -08002029 }
2030
2031 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2032}
2033
2034RTCError PeerConnection::ApplyRemoteDescription(
2035 std::unique_ptr<SessionDescriptionInterface> desc) {
2036 RTC_DCHECK_RUN_ON(signaling_thread());
2037 RTC_DCHECK(desc);
2038
2039 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
2040 if (!error.ok()) {
2041 return error;
2042 }
2043
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 // Update stats here so that we have the most recent stats for tracks and
2045 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002046 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002047
Steve Antondcc3c022017-12-22 16:02:54 -08002048 // Take a reference to the old remote description since it's used below to
2049 // compare against the new remote description. When setting the new remote
2050 // description, grab ownership of the replaced session description in case it
2051 // is the same as |old_remote_description|, to keep it alive for the duration
2052 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002053 const SessionDescriptionInterface* old_remote_description =
2054 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002055 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002056 SdpType type = desc->GetType();
2057 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002058 replaced_remote_description = pending_remote_description_
2059 ? std::move(pending_remote_description_)
2060 : std::move(current_remote_description_);
2061 current_remote_description_ = std::move(desc);
2062 pending_remote_description_ = nullptr;
2063 current_local_description_ = std::move(pending_local_description_);
2064 } else {
2065 replaced_remote_description = std::move(pending_remote_description_);
2066 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 }
Steve Anton8a006912017-12-04 15:25:56 -08002068 // The session description to apply now must be accessed by
2069 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002070 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002071
Steve Anton8a006912017-12-04 15:25:56 -08002072 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002073 if (IsUnifiedPlan()) {
2074 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002075 cricket::CS_REMOTE, *remote_description(), local_description(),
2076 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002077 if (!error.ok()) {
2078 return error;
2079 }
Steve Antondcc3c022017-12-22 16:02:54 -08002080 } else {
2081 if (type == SdpType::kOffer) {
2082 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2083 // description is applied. Restore back to old description.
2084 RTCError error = CreateChannels(*remote_description()->description());
2085 if (!error.ok()) {
2086 return error;
2087 }
2088 }
Steve Anton8a006912017-12-04 15:25:56 -08002089
Steve Antondcc3c022017-12-22 16:02:54 -08002090 // Remove unused channels if MediaContentDescription is rejected.
2091 RemoveUnusedChannels(remote_description()->description());
2092 }
Steve Anton8a006912017-12-04 15:25:56 -08002093
2094 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2095 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002096 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002097 if (!error.ok()) {
2098 return error;
2099 }
2100
2101 if (local_description() &&
2102 !UseCandidatesInSessionDescription(remote_description())) {
2103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2104 }
2105
2106 if (old_remote_description) {
2107 for (const cricket::ContentInfo& content :
2108 old_remote_description->description()->contents()) {
2109 // Check if this new SessionDescription contains new ICE ufrag and
2110 // password that indicates the remote peer requests an ICE restart.
2111 // TODO(deadbeef): When we start storing both the current and pending
2112 // remote description, this should reset pending_ice_restarts and compare
2113 // against the current description.
2114 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2115 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002116 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002117 pending_ice_restarts_.insert(content.name);
2118 }
2119 } else {
2120 // We retain all received candidates only if ICE is not restarted.
2121 // When ICE is restarted, all previous candidates belong to an old
2122 // generation and should not be kept.
2123 // TODO(deadbeef): This goes against the W3C spec which says the remote
2124 // description should only contain candidates from the last set remote
2125 // description plus any candidates added since then. We should remove
2126 // this once we're sure it won't break anything.
2127 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2128 old_remote_description, content.name, mutable_remote_description());
2129 }
2130 }
2131 }
2132
2133 if (session_error() != SessionError::kNone) {
2134 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2135 }
2136
2137 // Set the the ICE connection state to connecting since the connection may
2138 // become writable with peer reflexive candidates before any remote candidate
2139 // is signaled.
2140 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2141 // is to have a new signal the indicates a change in checking state from the
2142 // transport and expose a new checking() member from transport that can be
2143 // read to determine the current checking state. The existing SignalConnecting
2144 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002145 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002146 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2147 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2148 }
2149
deadbeefab9b2d12015-10-14 11:33:11 -07002150 // If setting the description decided our SSL role, allocate any necessary
2151 // SCTP sids.
2152 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002153 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002154 AllocateSctpSids(role);
2155 }
2156
Steve Antondcc3c022017-12-22 16:02:54 -08002157 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002158 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002159 for (auto transceiver : transceivers_) {
2160 const ContentInfo* content =
2161 FindMediaSectionForTransceiver(transceiver, remote_description());
2162 if (!content) {
2163 continue;
2164 }
2165 const MediaContentDescription* media_desc = content->media_description();
2166 RtpTransceiverDirection local_direction =
2167 RtpTransceiverDirectionReversed(media_desc->direction());
2168 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2169 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2170 // transceiver's current direction is neither sendrecv nor recvonly,
2171 // process the addition of a remote track for the media description.
2172 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2173 (!transceiver->current_direction() ||
2174 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002175 *transceiver->current_direction())) &&
2176 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002177 const std::string& sync_label = media_desc->streams()[0].sync_label;
2178 rtc::scoped_refptr<MediaStreamInterface> stream =
2179 remote_streams_->find(sync_label);
2180 if (!stream) {
2181 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2182 MediaStream::Create(sync_label));
2183 remote_streams_->AddStream(stream);
2184 }
2185 transceiver->internal()->receiver_internal()->SetStreams({stream});
2186 TrackEvent track_event;
2187 track_event.receiver = transceiver->receiver();
2188 track_event.streams = transceiver->receiver()->streams();
2189 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002190 }
2191 // If direction is sendonly or inactive, and transceiver's current
2192 // direction is neither sendonly nor inactive, process the removal of a
2193 // remote track for the media description.
2194 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002195 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002196 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002197 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002198 }
2199 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2200 transceiver->internal()->set_current_direction(local_direction);
2201 }
2202 if (content->rejected && !transceiver->stopped()) {
2203 transceiver->Stop();
2204 }
Steve Anton74255ff2018-01-24 18:32:57 -08002205 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002206 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002207 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002208 }
Steve Antondcc3c022017-12-22 16:02:54 -08002209 }
Steve Antonef65ef12018-01-10 17:15:20 -08002210 for (auto event : track_events) {
2211 observer_->OnAddTrack(event.receiver, event.streams);
2212 }
Steve Antondcc3c022017-12-22 16:02:54 -08002213 }
2214
Henrik Boströmfdb92012017-11-09 19:55:44 +01002215 const cricket::ContentInfo* audio_content =
2216 GetFirstAudioContent(remote_description()->description());
2217 const cricket::ContentInfo* video_content =
2218 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002219 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002220 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002221 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002222 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002223 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002224 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002225
2226 // Check if the descriptions include streams, just in case the peer supports
2227 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002228 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002229 (audio_desc && !audio_desc->streams().empty()) ||
2230 (video_desc && !video_desc->streams().empty())) {
2231 remote_peer_supports_msid_ = true;
2232 }
deadbeefab9b2d12015-10-14 11:33:11 -07002233
2234 // We wait to signal new streams until we finish processing the description,
2235 // since only at that point will new streams have all their tracks.
2236 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2237
Steve Antondcc3c022017-12-22 16:02:54 -08002238 if (!IsUnifiedPlan()) {
2239 // TODO(steveanton): When removing RTP senders/receivers in response to a
2240 // rejected media section, there is some cleanup logic that expects the
2241 // voice/ video channel to still be set. But in this method the voice/video
2242 // channel would have been destroyed by the SetRemoteDescription caller
2243 // above so the cleanup that relies on them fails to run. The RemoveSenders
2244 // calls should be moved to right before the DestroyChannel calls to fix
2245 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002246
Steve Antondcc3c022017-12-22 16:02:54 -08002247 // Find all audio rtp streams and create corresponding remote AudioTracks
2248 // and MediaStreams.
2249 if (audio_content) {
2250 if (audio_content->rejected) {
2251 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2252 } else {
2253 bool default_audio_track_needed =
2254 !remote_peer_supports_msid_ &&
2255 RtpTransceiverDirectionHasSend(audio_desc->direction());
2256 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2257 default_audio_track_needed, audio_desc->type(),
2258 new_streams);
2259 }
deadbeeffaac4972015-11-12 15:33:07 -08002260 }
deadbeefab9b2d12015-10-14 11:33:11 -07002261
Steve Antondcc3c022017-12-22 16:02:54 -08002262 // Find all video rtp streams and create corresponding remote VideoTracks
2263 // and MediaStreams.
2264 if (video_content) {
2265 if (video_content->rejected) {
2266 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2267 } else {
2268 bool default_video_track_needed =
2269 !remote_peer_supports_msid_ &&
2270 RtpTransceiverDirectionHasSend(video_desc->direction());
2271 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2272 default_video_track_needed, video_desc->type(),
2273 new_streams);
2274 }
deadbeeffaac4972015-11-12 15:33:07 -08002275 }
deadbeefab9b2d12015-10-14 11:33:11 -07002276
Steve Antondcc3c022017-12-22 16:02:54 -08002277 // Update the DataChannels with the information from the remote peer.
2278 if (data_desc) {
2279 if (rtc::starts_with(data_desc->protocol().data(),
2280 cricket::kMediaProtocolRtpPrefix)) {
2281 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2282 }
deadbeefab9b2d12015-10-14 11:33:11 -07002283 }
deadbeefab9b2d12015-10-14 11:33:11 -07002284
Steve Antondcc3c022017-12-22 16:02:54 -08002285 // Iterate new_streams and notify the observer about new MediaStreams.
2286 for (size_t i = 0; i < new_streams->count(); ++i) {
2287 MediaStreamInterface* new_stream = new_streams->at(i);
2288 stats_->AddStream(new_stream);
2289 observer_->OnAddStream(
2290 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2291 }
deadbeefab9b2d12015-10-14 11:33:11 -07002292
Steve Antondcc3c022017-12-22 16:02:54 -08002293 UpdateEndedRemoteMediaStreams();
2294 }
deadbeefab9b2d12015-10-14 11:33:11 -07002295
Steve Anton8a006912017-12-04 15:25:56 -08002296 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002297}
2298
Steve Antondcc3c022017-12-22 16:02:54 -08002299RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2300 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002301 const SessionDescriptionInterface& new_session,
2302 const SessionDescriptionInterface* old_local_description,
2303 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002304 RTC_DCHECK(IsUnifiedPlan());
2305
Steve Anton7464fca2018-01-19 11:10:37 -08002306 const cricket::ContentGroup* bundle_group = nullptr;
2307 if (new_session.GetType() == SdpType::kOffer) {
2308 auto bundle_group_or_error =
2309 GetEarlyBundleGroup(*new_session.description());
2310 if (!bundle_group_or_error.ok()) {
2311 return bundle_group_or_error.MoveError();
2312 }
2313 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002314 }
Steve Antondcc3c022017-12-22 16:02:54 -08002315
Steve Antondcc3c022017-12-22 16:02:54 -08002316 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002317 for (size_t i = 0; i < new_contents.size(); ++i) {
2318 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002319 cricket::MediaType media_type = new_content.media_description()->type();
2320 seen_mids_.insert(new_content.name);
2321 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2322 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002323 const cricket::ContentInfo* old_local_content = nullptr;
2324 if (old_local_description &&
2325 i < old_local_description->description()->contents().size()) {
2326 old_local_content =
2327 &old_local_description->description()->contents()[i];
2328 }
2329 const cricket::ContentInfo* old_remote_content = nullptr;
2330 if (old_remote_description &&
2331 i < old_remote_description->description()->contents().size()) {
2332 old_remote_content =
2333 &old_remote_description->description()->contents()[i];
2334 }
Steve Antondcc3c022017-12-22 16:02:54 -08002335 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002336 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2337 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002338 if (!transceiver_or_error.ok()) {
2339 return transceiver_or_error.MoveError();
2340 }
2341 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002342 RTCError error =
2343 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2344 if (!error.ok()) {
2345 return error;
2346 }
2347 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002348 if (GetDataMid() && new_content.name != *GetDataMid()) {
2349 // Ignore all but the first data section.
2350 continue;
2351 }
2352 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2353 if (!error.ok()) {
2354 return error;
2355 }
Steve Antondcc3c022017-12-22 16:02:54 -08002356 } else {
2357 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2358 "Unknown section type.");
2359 }
2360 }
2361
2362 return RTCError::OK();
2363}
2364
2365RTCError PeerConnection::UpdateTransceiverChannel(
2366 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2367 transceiver,
2368 const cricket::ContentInfo& content,
2369 const cricket::ContentGroup* bundle_group) {
2370 RTC_DCHECK(IsUnifiedPlan());
2371 RTC_DCHECK(transceiver);
2372 cricket::BaseChannel* channel = transceiver->internal()->channel();
2373 if (content.rejected) {
2374 if (channel) {
2375 transceiver->internal()->SetChannel(nullptr);
2376 DestroyBaseChannel(channel);
2377 }
2378 } else {
2379 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002380 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002381 channel = CreateVoiceChannel(
2382 content.name,
2383 GetTransportNameForMediaSection(content.name, bundle_group));
2384 } else {
Steve Anton69470252018-02-09 11:43:08 -08002385 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002386 channel = CreateVideoChannel(
2387 content.name,
2388 GetTransportNameForMediaSection(content.name, bundle_group));
2389 }
2390 if (!channel) {
2391 LOG_AND_RETURN_ERROR(
2392 RTCErrorType::INTERNAL_ERROR,
2393 "Failed to create channel for mid=" + content.name);
2394 }
2395 transceiver->internal()->SetChannel(channel);
2396 }
2397 }
2398 return RTCError::OK();
2399}
2400
Steve Antonfa2260d2017-12-28 16:38:23 -08002401RTCError PeerConnection::UpdateDataChannel(
2402 cricket::ContentSource source,
2403 const cricket::ContentInfo& content,
2404 const cricket::ContentGroup* bundle_group) {
2405 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002406 // If data channels are disabled, ignore this media section. CreateAnswer
2407 // will take care of rejecting it.
2408 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002409 }
2410 if (content.rejected) {
2411 DestroyDataChannel();
2412 } else {
2413 if (!rtp_data_channel_ && !sctp_transport_) {
2414 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2415 content.name, bundle_group))) {
2416 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2417 "Failed to create data channel.");
2418 }
2419 }
2420 if (source == cricket::CS_REMOTE) {
2421 const MediaContentDescription* data_desc = content.media_description();
2422 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2423 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2424 }
2425 }
2426 }
2427 return RTCError::OK();
2428}
2429
Steve Antondcc3c022017-12-22 16:02:54 -08002430RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2431PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002432 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002433 size_t mline_index,
2434 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002435 const ContentInfo* old_local_content,
2436 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002437 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002438 // If this is an offer then the m= section might be recycled. If the m=
2439 // section is being recycled (defined as: rejected in the current local or
2440 // remote description and not rejected in new description), dissociate the
2441 // currently associated RtpTransceiver by setting its mid property to null,
2442 // and discard the mapping between the transceiver and its m= section index.
2443 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2444 old_remote_content)) {
2445 // We want to dissociate the transceiver that has the rejected mid.
2446 const std::string& old_mid =
2447 (old_local_content && old_local_content->rejected)
2448 ? old_local_content->name
2449 : old_remote_content->name;
2450 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002451 if (old_transceiver) {
2452 old_transceiver->internal()->set_mid(rtc::nullopt);
2453 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2454 }
2455 }
2456 const MediaContentDescription* media_desc = content.media_description();
2457 auto transceiver = GetAssociatedTransceiver(content.name);
2458 if (source == cricket::CS_LOCAL) {
2459 // Find the RtpTransceiver that corresponds to this m= section, using the
2460 // mapping between transceivers and m= section indices established when
2461 // creating the offer.
2462 if (!transceiver) {
2463 transceiver = GetTransceiverByMLineIndex(mline_index);
2464 }
2465 if (!transceiver) {
2466 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2467 "Unknown transceiver");
2468 }
2469 } else {
2470 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2471 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2472 // of the same type...
2473 if (!transceiver &&
2474 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2475 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2476 }
2477 // If no RtpTransceiver was found in the previous step, create one with a
2478 // recvonly direction.
2479 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002480 auto sender =
2481 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002482 std::string receiver_id;
2483 if (!media_desc->streams().empty()) {
2484 receiver_id = media_desc->streams()[0].id;
2485 } else {
2486 receiver_id = rtc::CreateRandomUuid();
2487 }
2488 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002489 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002490 transceiver->internal()->set_direction(
2491 RtpTransceiverDirection::kRecvOnly);
2492 }
2493 }
2494 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002495 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002496 LOG_AND_RETURN_ERROR(
2497 RTCErrorType::INVALID_PARAMETER,
2498 "Transceiver type does not match media description type.");
2499 }
2500 // Associate the found or created RtpTransceiver with the m= section by
2501 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2502 // section, and establish a mapping between the transceiver and the index of
2503 // the m= section.
2504 transceiver->internal()->set_mid(content.name);
2505 transceiver->internal()->set_mline_index(mline_index);
2506 return std::move(transceiver);
2507}
2508
2509rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2510PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2511 RTC_DCHECK(IsUnifiedPlan());
2512 for (auto transceiver : transceivers_) {
2513 if (transceiver->mid() == mid) {
2514 return transceiver;
2515 }
2516 }
2517 return nullptr;
2518}
2519
2520rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2521PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2522 RTC_DCHECK(IsUnifiedPlan());
2523 for (auto transceiver : transceivers_) {
2524 if (transceiver->internal()->mline_index() == mline_index) {
2525 return transceiver;
2526 }
2527 }
2528 return nullptr;
2529}
2530
2531rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2532PeerConnection::FindAvailableTransceiverToReceive(
2533 cricket::MediaType media_type) const {
2534 RTC_DCHECK(IsUnifiedPlan());
2535 // From JSEP section 5.10 (Applying a Remote Description):
2536 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2537 // the same type that were added to the PeerConnection by addTrack and are not
2538 // associated with any m= section and are not stopped, find the first such
2539 // RtpTransceiver.
2540 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002541 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002542 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2543 !transceiver->stopped()) {
2544 return transceiver;
2545 }
2546 }
2547 return nullptr;
2548}
2549
Steve Antoned10bd92017-12-05 10:52:59 -08002550const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2551 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2552 transceiver,
2553 const SessionDescriptionInterface* sdesc) const {
2554 RTC_DCHECK(transceiver);
2555 RTC_DCHECK(sdesc);
2556 if (IsUnifiedPlan()) {
2557 if (!transceiver->internal()->mid()) {
2558 // This transceiver is not associated with a media section yet.
2559 return nullptr;
2560 }
2561 return sdesc->description()->GetContentByName(
2562 *transceiver->internal()->mid());
2563 } else {
2564 // Plan B only allows at most one audio and one video section, so use the
2565 // first media section of that type.
2566 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002567 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002568 }
2569}
2570
deadbeef46c73892016-11-16 19:42:04 -08002571PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2572 return configuration_;
2573}
2574
deadbeef293e9262017-01-11 12:28:30 -08002575bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2576 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002577 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002578
Steve Anton75737c02017-11-06 10:37:17 -08002579 if (local_description() && configuration.ice_candidate_pool_size !=
2580 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002581 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2582 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002583 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002584 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002585
deadbeef293e9262017-01-11 12:28:30 -08002586 // The simplest (and most future-compatible) way to tell if the config was
2587 // modified in an invalid way is to copy each property we do support
2588 // modifying, then use operator==. There are far more properties we don't
2589 // support modifying than those we do, and more could be added.
2590 RTCConfiguration modified_config = configuration_;
2591 modified_config.servers = configuration.servers;
2592 modified_config.type = configuration.type;
2593 modified_config.ice_candidate_pool_size =
2594 configuration.ice_candidate_pool_size;
2595 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002596 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002597 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002598 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002599 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002600 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002601 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2602 }
2603
Steve Anton038834f2017-07-14 15:59:59 -07002604 // Validate the modified configuration.
2605 RTCError validate_error = ValidateConfiguration(modified_config);
2606 if (!validate_error.ok()) {
2607 return SafeSetError(std::move(validate_error), error);
2608 }
2609
deadbeef293e9262017-01-11 12:28:30 -08002610 // Note that this isn't possible through chromium, since it's an unsigned
2611 // short in WebIDL.
2612 if (configuration.ice_candidate_pool_size < 0 ||
2613 configuration.ice_candidate_pool_size > UINT16_MAX) {
2614 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2615 }
2616
2617 // Parse ICE servers before hopping to network thread.
2618 cricket::ServerAddresses stun_servers;
2619 std::vector<cricket::RelayServerConfig> turn_servers;
2620 RTCErrorType parse_error =
2621 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2622 if (parse_error != RTCErrorType::NONE) {
2623 return SafeSetError(parse_error, error);
2624 }
2625
2626 // In theory this shouldn't fail.
2627 if (!network_thread()->Invoke<bool>(
2628 RTC_FROM_HERE,
2629 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2630 stun_servers, turn_servers, modified_config.type,
2631 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002632 modified_config.prune_turn_ports,
2633 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002635 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2636 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002637
deadbeefd1a38b52016-12-10 13:15:33 -08002638 // As described in JSEP, calling setConfiguration with new ICE servers or
2639 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2640 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002641 if (modified_config.servers != configuration_.servers ||
2642 modified_config.type != configuration_.type ||
2643 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002644 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002645 }
skvladd1f5fda2017-02-03 16:54:05 -08002646
2647 if (modified_config.ice_check_min_interval !=
2648 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002649 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002650 }
2651
deadbeef293e9262017-01-11 12:28:30 -08002652 configuration_ = modified_config;
2653 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002654}
2655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656bool PeerConnection::AddIceCandidate(
2657 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002658 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002659 if (IsClosed()) {
2660 return false;
2661 }
Steve Antond25da372017-11-06 14:50:29 -08002662
2663 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002664 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002665 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002666 return false;
2667 }
2668
2669 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002670 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002671 return false;
2672 }
2673
2674 bool valid = false;
2675 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2676 if (!valid) {
2677 return false;
2678 }
2679
2680 // Add this candidate to the remote session description.
2681 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002682 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002683 return false;
2684 }
2685
2686 if (ready) {
2687 return UseCandidate(ice_candidate);
2688 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002689 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002690 return true;
2691 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002692}
2693
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002694bool PeerConnection::RemoveIceCandidates(
2695 const std::vector<cricket::Candidate>& candidates) {
2696 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002697 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002698 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002699 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002700 return false;
2701 }
2702
2703 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002704 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002705 return false;
2706 }
2707
2708 size_t number_removed =
2709 mutable_remote_description()->RemoveCandidates(candidates);
2710 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002711 RTC_LOG(LS_ERROR)
2712 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002713 "Requested "
2714 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002715 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002716 }
2717
2718 // Remove the candidates from the transport controller.
2719 std::string error;
2720 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2721 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002722 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002723 }
2724 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002725}
2726
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002727void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002728 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002729 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002730
Steve Anton75737c02017-11-06 10:37:17 -08002731 if (transport_controller()) {
2732 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002733 }
2734
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002735 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002736 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002737 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002738 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002739 uma_observer_->IncrementEnumCounter(
2740 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2741 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002742 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002743 uma_observer_->IncrementEnumCounter(
2744 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2745 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002746 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002747 // Send information about the requested SDP semantics.
2748 switch (configuration_.sdp_semantics) {
2749 case SdpSemantics::kDefault:
2750 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2751 kSdpSemanticRequestDefault,
2752 kSdpSemanticRequestMax);
2753
2754 break;
2755 case SdpSemantics::kPlanB:
2756 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2757 kSdpSemanticRequestPlanB,
2758 kSdpSemanticRequestMax);
2759 break;
2760 case SdpSemantics::kUnifiedPlan:
2761 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2762 kSdpSemanticRequestUnifiedPlan,
2763 kSdpSemanticRequestMax);
2764 break;
2765 default:
2766 RTC_NOTREACHED();
2767 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002768 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002769}
2770
zstein4b979802017-06-02 14:37:37 -07002771RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002772 if (!worker_thread()->IsCurrent()) {
2773 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002774 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2775 }
2776
2777 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2778 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2779 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2780 if (has_min && *bitrate.min_bitrate_bps < 0) {
2781 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2782 "min_bitrate_bps <= 0");
2783 }
2784 if (has_current) {
2785 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2786 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2787 "current_bitrate_bps < min_bitrate_bps");
2788 } else if (*bitrate.current_bitrate_bps < 0) {
2789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2790 "curent_bitrate_bps < 0");
2791 }
2792 }
2793 if (has_max) {
2794 if (has_current &&
2795 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2796 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2797 "max_bitrate_bps < current_bitrate_bps");
2798 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2800 "max_bitrate_bps < min_bitrate_bps");
2801 } else if (*bitrate.max_bitrate_bps < 0) {
2802 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2803 "max_bitrate_bps < 0");
2804 }
2805 }
2806
2807 Call::Config::BitrateConfigMask mask;
2808 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2809 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2810 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2811
2812 RTC_DCHECK(call_.get());
2813 call_->SetBitrateConfigMask(mask);
2814
2815 return RTCError::OK();
2816}
2817
Alex Narest78609d52017-10-20 10:37:47 +02002818void PeerConnection::SetBitrateAllocationStrategy(
2819 std::unique_ptr<rtc::BitrateAllocationStrategy>
2820 bitrate_allocation_strategy) {
2821 rtc::Thread* worker_thread = factory_->worker_thread();
2822 if (!worker_thread->IsCurrent()) {
2823 rtc::BitrateAllocationStrategy* strategy_raw =
2824 bitrate_allocation_strategy.release();
2825 auto functor = [this, strategy_raw]() {
2826 call_->SetBitrateAllocationStrategy(
2827 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2828 };
2829 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2830 return;
2831 }
2832 RTC_DCHECK(call_.get());
2833 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2834}
2835
henrika5f6bf242017-11-01 11:06:56 +01002836void PeerConnection::SetAudioPlayout(bool playout) {
2837 if (!worker_thread()->IsCurrent()) {
2838 worker_thread()->Invoke<void>(
2839 RTC_FROM_HERE,
2840 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2841 return;
2842 }
2843 auto audio_state =
2844 factory_->channel_manager()->media_engine()->GetAudioState();
2845 audio_state->SetPlayout(playout);
2846}
2847
2848void PeerConnection::SetAudioRecording(bool recording) {
2849 if (!worker_thread()->IsCurrent()) {
2850 worker_thread()->Invoke<void>(
2851 RTC_FROM_HERE,
2852 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2853 return;
2854 }
2855 auto audio_state =
2856 factory_->channel_manager()->media_engine()->GetAudioState();
2857 audio_state->SetRecording(recording);
2858}
2859
Steve Anton8c0f7a72017-10-03 10:03:10 -07002860std::unique_ptr<rtc::SSLCertificate>
2861PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002862 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002863 return nullptr;
2864 }
Steve Anton75737c02017-11-06 10:37:17 -08002865 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002866}
2867
Zhi Huang70b820f2018-01-27 14:16:15 -08002868std::unique_ptr<rtc::SSLCertChain>
2869PeerConnection::GetRemoteAudioSSLCertChain() {
2870 if (!voice_channel()) {
2871 return nullptr;
2872 }
2873
2874 return transport_controller_->GetRemoteSSLCertChain(
2875 voice_channel()->transport_name());
2876}
2877
ivoc14d5dbe2016-07-04 07:06:55 -07002878bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2879 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002880 // TODO(eladalon): It would be better to not allow negative values into PC.
2881 const size_t max_size = (max_size_bytes < 0)
2882 ? RtcEventLog::kUnlimitedOutput
2883 : rtc::saturated_cast<size_t>(max_size_bytes);
2884 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002885 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2886 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002887}
2888
Bjorn Tereliusde939432017-11-20 17:38:14 +01002889bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2890 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002891 // TODO(eladalon): In C++14, this can be done with a lambda.
2892 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002893 bool operator()() {
2894 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2895 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002896 PeerConnection* const pc;
2897 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002898 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002899 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002900 return worker_thread()->Invoke<bool>(
2901 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002902}
2903
2904void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002905 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002906 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2907}
2908
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002910 return pending_local_description_ ? pending_local_description_.get()
2911 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912}
2913
2914const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002915 return pending_remote_description_ ? pending_remote_description_.get()
2916 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917}
2918
deadbeeffe4a8a42016-12-20 17:56:17 -08002919const SessionDescriptionInterface* PeerConnection::current_local_description()
2920 const {
Steve Anton75737c02017-11-06 10:37:17 -08002921 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002922}
2923
2924const SessionDescriptionInterface* PeerConnection::current_remote_description()
2925 const {
Steve Anton75737c02017-11-06 10:37:17 -08002926 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002927}
2928
2929const SessionDescriptionInterface* PeerConnection::pending_local_description()
2930 const {
Steve Anton75737c02017-11-06 10:37:17 -08002931 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002932}
2933
2934const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2935 const {
Steve Anton75737c02017-11-06 10:37:17 -08002936 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002937}
2938
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002939void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002940 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941 // Update stats here so that we have the most recent stats for tracks and
2942 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002943 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944
Steve Anton75737c02017-11-06 10:37:17 -08002945 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002946
Steve Anton8af21862017-12-15 11:20:13 -08002947 for (auto transceiver : transceivers_) {
2948 transceiver->Stop();
2949 }
2950 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002951
Qingsi Wang93a84392018-01-30 17:13:09 -08002952 // The event log is used in the transport controller, which must be outlived
2953 // by the former. CreateOffer by the peer connection is implemented
2954 // asynchronously and if the peer connection is closed without resetting the
2955 // WebRTC session description factory, the session description factory would
2956 // call the transport controller.
2957 webrtc_session_desc_factory_.reset();
2958 transport_controller_.reset();
2959
deadbeef42a42632017-03-10 15:18:00 -08002960 network_thread()->Invoke<void>(
2961 RTC_FROM_HERE,
2962 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2963 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002964
Steve Anton978b8762017-09-29 12:15:02 -07002965 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002966 call_.reset();
2967 // The event log must outlive call (and any other object that uses it).
2968 event_log_.reset();
2969 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970}
2971
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002972void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002973 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002974 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2975 SetSessionDescriptionMsg* param =
2976 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2977 param->observer->OnSuccess();
2978 delete param;
2979 break;
2980 }
2981 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2982 SetSessionDescriptionMsg* param =
2983 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2984 param->observer->OnFailure(param->error);
2985 delete param;
2986 break;
2987 }
deadbeefab9b2d12015-10-14 11:33:11 -07002988 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2989 CreateSessionDescriptionMsg* param =
2990 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2991 param->observer->OnFailure(param->error);
2992 delete param;
2993 break;
2994 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 case MSG_GETSTATS: {
2996 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002997 StatsReports reports;
2998 stats_->GetStats(param->track, &reports);
2999 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 delete param;
3001 break;
3002 }
deadbeefbd292462015-12-14 18:15:29 -08003003 case MSG_FREE_DATACHANNELS: {
3004 sctp_data_channels_to_free_.clear();
3005 break;
3006 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003007 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003008 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003009 break;
3010 }
3011}
3012
Steve Anton4171afb2017-11-20 10:20:22 -08003013void PeerConnection::CreateAudioReceiver(
3014 MediaStreamInterface* stream,
3015 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003016 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3017 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003018 auto* audio_receiver = new AudioRtpReceiver(
3019 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton56bae8d2018-02-14 16:07:42 -08003020 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003021 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3022 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3023 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003024 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003025 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003026}
3027
Steve Anton4171afb2017-11-20 10:20:22 -08003028void PeerConnection::CreateVideoReceiver(
3029 MediaStreamInterface* stream,
3030 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003031 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3032 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003033 auto* video_receiver = new VideoRtpReceiver(
3034 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton56bae8d2018-02-14 16:07:42 -08003035 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003036 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3037 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3038 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003039 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003040 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041}
3042
deadbeef70ab1a12015-09-28 16:53:55 -07003043// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3044// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003045rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003046 const RtpSenderInfo& remote_sender_info) {
3047 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3048 if (!receiver) {
3049 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3050 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003051 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003052 }
Steve Anton4171afb2017-11-20 10:20:22 -08003053 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3054 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3055 } else {
3056 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3057 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003058 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059}
3060
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003061void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3062 MediaStreamInterface* stream) {
3063 RTC_DCHECK(!IsClosed());
3064 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003065 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003066 // We already have a sender for this track, so just change the stream_id
3067 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003068 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003069 return;
3070 }
3071
3072 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003073 auto new_sender =
3074 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton56bae8d2018-02-14 16:07:42 -08003075 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003076 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003077 // If the sender has already been configured in SDP, we call SetSsrc,
3078 // which will connect the sender to the underlying transport. This can
3079 // occur if a local session description that contains the ID of the sender
3080 // is set before AddStream is called. It can also occur if the local
3081 // session description is not changed and RemoveStream is called, and
3082 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003083 const RtpSenderInfo* sender_info =
3084 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3085 if (sender_info) {
3086 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003087 }
3088}
3089
3090// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3091// indefinitely, when we have unified plan SDP.
3092void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3093 MediaStreamInterface* stream) {
3094 RTC_DCHECK(!IsClosed());
3095 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003096 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003097 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3098 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003099 return;
3100 }
Steve Anton4171afb2017-11-20 10:20:22 -08003101 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003102}
3103
3104void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3105 MediaStreamInterface* stream) {
3106 RTC_DCHECK(!IsClosed());
3107 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003108 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003109 // We already have a sender for this track, so just change the stream_id
3110 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003111 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003112 return;
3113 }
3114
3115 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003116 auto new_sender =
3117 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton56bae8d2018-02-14 16:07:42 -08003118 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003119 GetVideoTransceiver()->internal()->AddSender(new_sender);
3120 const RtpSenderInfo* sender_info =
3121 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3122 if (sender_info) {
3123 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003124 }
3125}
3126
3127void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3128 MediaStreamInterface* stream) {
3129 RTC_DCHECK(!IsClosed());
3130 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003131 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003132 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3133 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003134 return;
3135 }
Steve Anton4171afb2017-11-20 10:20:22 -08003136 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003137}
3138
Steve Antonba818672017-11-06 10:21:57 -08003139void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003140 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003141 if (ice_connection_state_ == new_state) {
3142 return;
3143 }
3144
deadbeefcbecd352015-09-23 11:50:27 -07003145 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003146 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003147 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003148 return;
3149 }
Steve Antonba818672017-11-06 10:21:57 -08003150
Mirko Bonadei675513b2017-11-09 11:09:25 +01003151 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3152 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003153 RTC_DCHECK(ice_connection_state_ !=
3154 PeerConnectionInterface::kIceConnectionClosed);
3155
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003157 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003158}
3159
3160void PeerConnection::OnIceGatheringChange(
3161 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003162 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 if (IsClosed()) {
3164 return;
3165 }
3166 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003167 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168}
3169
jbauch81bf7b02017-03-25 08:31:12 -07003170void PeerConnection::OnIceCandidate(
3171 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003172 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003173 if (IsClosed()) {
3174 return;
3175 }
jbauch81bf7b02017-03-25 08:31:12 -07003176 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003177}
3178
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003179void PeerConnection::OnIceCandidatesRemoved(
3180 const std::vector<cricket::Candidate>& candidates) {
3181 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003182 if (IsClosed()) {
3183 return;
3184 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003185 observer_->OnIceCandidatesRemoved(candidates);
3186}
3187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003188void PeerConnection::ChangeSignalingState(
3189 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003190 RTC_DCHECK(signaling_thread()->IsCurrent());
3191 if (signaling_state_ == signaling_state) {
3192 return;
3193 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003194 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3195 << GetSignalingStateString(signaling_state_)
3196 << " New state: "
3197 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198 signaling_state_ = signaling_state;
3199 if (signaling_state == kClosed) {
3200 ice_connection_state_ = kIceConnectionClosed;
3201 observer_->OnIceConnectionChange(ice_connection_state_);
3202 if (ice_gathering_state_ != kIceGatheringComplete) {
3203 ice_gathering_state_ = kIceGatheringComplete;
3204 observer_->OnIceGatheringChange(ice_gathering_state_);
3205 }
3206 }
3207 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003208}
3209
deadbeefeb459812015-12-15 19:24:43 -08003210void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3211 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003212 if (IsClosed()) {
3213 return;
3214 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003215 AddAudioTrack(track, stream);
3216 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003217}
3218
deadbeefeb459812015-12-15 19:24:43 -08003219void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3220 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003221 if (IsClosed()) {
3222 return;
3223 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003224 RemoveAudioTrack(track, stream);
3225 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003226}
3227
3228void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3229 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003230 if (IsClosed()) {
3231 return;
3232 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003233 AddVideoTrack(track, stream);
3234 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003235}
3236
3237void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3238 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003239 if (IsClosed()) {
3240 return;
3241 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003242 RemoveVideoTrack(track, stream);
3243 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003244}
3245
Henrik Boström31638672017-11-23 17:48:32 +01003246void PeerConnection::PostSetSessionDescriptionSuccess(
3247 SetSessionDescriptionObserver* observer) {
3248 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3249 signaling_thread()->Post(RTC_FROM_HERE, this,
3250 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3251}
3252
deadbeefab9b2d12015-10-14 11:33:11 -07003253void PeerConnection::PostSetSessionDescriptionFailure(
3254 SetSessionDescriptionObserver* observer,
3255 const std::string& error) {
3256 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3257 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003258 signaling_thread()->Post(RTC_FROM_HERE, this,
3259 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003260}
3261
3262void PeerConnection::PostCreateSessionDescriptionFailure(
3263 CreateSessionDescriptionObserver* observer,
3264 const std::string& error) {
3265 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3266 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003267 signaling_thread()->Post(RTC_FROM_HERE, this,
3268 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003269}
3270
zhihuang1c378ed2017-08-17 14:10:50 -07003271void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003272 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003273 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003274 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003275
Steve Antondcc3c022017-12-22 16:02:54 -08003276 if (IsUnifiedPlan()) {
3277 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3278 } else {
3279 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3280 }
3281
Steve Antonfa2260d2017-12-28 16:38:23 -08003282 // Intentionally unset the data channel type for RTP data channel with the
3283 // second condition. Otherwise the RTP data channels would be successfully
3284 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3285 // when building with chromium. We want to leave RTP data channels broken, so
3286 // people won't try to use them.
3287 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3288 session_options->data_channel_type = data_channel_type();
3289 }
3290
Steve Antondcc3c022017-12-22 16:02:54 -08003291 // Apply ICE restart flag and renomination flag.
3292 for (auto& options : session_options->media_description_options) {
3293 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3294 options.transport_options.enable_ice_renomination =
3295 configuration_.enable_ice_renomination;
3296 }
3297
3298 session_options->rtcp_cname = rtcp_cname_;
3299 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003300 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003301}
3302
3303void PeerConnection::GetOptionsForPlanBOffer(
3304 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3305 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003306 // Figure out transceiver directional preferences.
3307 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3308 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3309
3310 // By default, generate sendrecv/recvonly m= sections.
3311 bool recv_audio = true;
3312 bool recv_video = true;
3313
3314 // By default, only offer a new m= section if we have media to send with it.
3315 bool offer_new_audio_description = send_audio;
3316 bool offer_new_video_description = send_video;
3317 bool offer_new_data_description = HasDataChannels();
3318
3319 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003320 if (offer_answer_options.offer_to_receive_audio !=
3321 RTCOfferAnswerOptions::kUndefined) {
3322 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003323 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003324 offer_new_audio_description ||
3325 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003326 }
Steve Antondcc3c022017-12-22 16:02:54 -08003327 if (offer_answer_options.offer_to_receive_video !=
3328 RTCOfferAnswerOptions::kUndefined) {
3329 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003330 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003331 offer_new_video_description ||
3332 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003333 }
3334
3335 rtc::Optional<size_t> audio_index;
3336 rtc::Optional<size_t> video_index;
3337 rtc::Optional<size_t> data_index;
3338 // If a current description exists, generate m= sections in the same order,
3339 // using the first audio/video/data section that appears and rejecting
3340 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003341 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003342 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003343 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003344 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3345 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3346 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003347 }
3348
zhihuang1c378ed2017-08-17 14:10:50 -07003349 // Add audio/video/data m= sections to the end if needed.
3350 if (!audio_index && offer_new_audio_description) {
3351 session_options->media_description_options.push_back(
3352 cricket::MediaDescriptionOptions(
3353 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003354 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3355 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003356 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003357 }
zhihuang1c378ed2017-08-17 14:10:50 -07003358 if (!video_index && offer_new_video_description) {
3359 session_options->media_description_options.push_back(
3360 cricket::MediaDescriptionOptions(
3361 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003362 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3363 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003364 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003365 }
zhihuang1c378ed2017-08-17 14:10:50 -07003366 if (!data_index && offer_new_data_description) {
3367 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003368 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003369 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003370 }
3371
3372 cricket::MediaDescriptionOptions* audio_media_description_options =
3373 !audio_index ? nullptr
3374 : &session_options->media_description_options[*audio_index];
3375 cricket::MediaDescriptionOptions* video_media_description_options =
3376 !video_index ? nullptr
3377 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003378
Steve Anton4171afb2017-11-20 10:20:22 -08003379 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003380 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003381}
3382
3383// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3384// and return a reference to it.
3385// Generated MIDs should be no more than 3 bytes long to take up less space in
3386// the RTP packet.
3387static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3388 RTC_DCHECK(used_mids);
3389 // We're boring: just generate MIDs 0, 1, 2, ...
3390 size_t i = 0;
3391 std::set<std::string>::iterator it;
3392 bool inserted;
3393 do {
3394 std::string mid = rtc::ToString(i++);
3395 auto insert_result = used_mids->insert(mid);
3396 it = insert_result.first;
3397 inserted = insert_result.second;
3398 } while (!inserted);
3399 return *it;
3400}
3401
3402static cricket::MediaDescriptionOptions
3403GetMediaDescriptionOptionsForTransceiver(
3404 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3405 transceiver,
3406 const std::string& mid) {
3407 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003408 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003409 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003410 // This behavior is specified in JSEP. The gist is that:
3411 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3412 // sendrecv.
3413 // 2. If the MSID is included, then it must be included in any subsequent
3414 // offer/answer exactly the same until the RtpTransceiver is stopped.
3415 if (!transceiver->stopped() &&
3416 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3417 transceiver->internal()->has_ever_been_used_to_send())) {
3418 cricket::SenderOptions sender_options;
3419 sender_options.track_id = transceiver->sender()->id();
3420 sender_options.stream_ids = transceiver->sender()->stream_ids();
3421 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3422 // set in the RTP parameters when the transceiver was added.
3423 sender_options.num_sim_layers = 1;
3424 media_description_options.sender_options.push_back(sender_options);
3425 }
Steve Antondcc3c022017-12-22 16:02:54 -08003426 return media_description_options;
3427}
3428
3429void PeerConnection::GetOptionsForUnifiedPlanOffer(
3430 const RTCOfferAnswerOptions& offer_answer_options,
3431 cricket::MediaSessionOptions* session_options) {
3432 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3433 // Offers) and 5.2.2 (Subsequent Offers).
3434 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3435 const ContentInfos& local_contents =
3436 (local_description() ? local_description()->description()->contents()
3437 : ContentInfos());
3438 const ContentInfos& remote_contents =
3439 (remote_description() ? remote_description()->description()->contents()
3440 : ContentInfos());
3441 // The mline indices that can be recycled. New transceivers should reuse these
3442 // slots first.
3443 std::queue<size_t> recycleable_mline_indices;
3444 // Track the MIDs used in previous offer/answer exchanges and the current
3445 // offer so that new, unique MIDs are generated.
3446 std::set<std::string> used_mids = seen_mids_;
3447 // First, go through each media section that exists in either the local or
3448 // remote description and generate a media section in this offer for the
3449 // associated transceiver. If a media section can be recycled, generate a
3450 // default, rejected media section here that can be later overwritten.
3451 for (size_t i = 0;
3452 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3453 // Either |local_content| or |remote_content| is non-null.
3454 const ContentInfo* local_content =
3455 (i < local_contents.size() ? &local_contents[i] : nullptr);
3456 const ContentInfo* remote_content =
3457 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3458 bool had_been_rejected = (local_content && local_content->rejected) ||
3459 (remote_content && remote_content->rejected);
3460 const std::string& mid =
3461 (local_content ? local_content->name : remote_content->name);
3462 cricket::MediaType media_type =
3463 (local_content ? local_content->media_description()->type()
3464 : remote_content->media_description()->type());
3465 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3466 media_type == cricket::MEDIA_TYPE_VIDEO) {
3467 auto transceiver = GetAssociatedTransceiver(mid);
3468 RTC_CHECK(transceiver);
3469 // A media section is considered eligible for recycling if it is marked as
3470 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003471 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003472 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003473 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3474 RtpTransceiverDirection::kInactive,
3475 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003476 recycleable_mline_indices.push(i);
3477 } else {
3478 session_options->media_description_options.push_back(
3479 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3480 // CreateOffer shouldn't really cause any state changes in
3481 // PeerConnection, but we need a way to match new transceivers to new
3482 // media sections in SetLocalDescription and JSEP specifies this is done
3483 // by recording the index of the media section generated for the
3484 // transceiver in the offer.
3485 transceiver->internal()->set_mline_index(i);
3486 }
3487 } else {
3488 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003489 RTC_CHECK(GetDataMid());
3490 if (had_been_rejected || mid != *GetDataMid()) {
3491 session_options->media_description_options.push_back(
3492 GetMediaDescriptionOptionsForRejectedData(mid));
3493 } else {
3494 session_options->media_description_options.push_back(
3495 GetMediaDescriptionOptionsForActiveData(mid));
3496 }
Steve Antondcc3c022017-12-22 16:02:54 -08003497 }
3498 }
3499 // Next, look for transceivers that are newly added (that is, are not stopped
3500 // and not associated). Reuse media sections marked as recyclable first,
3501 // otherwise append to the end of the offer. New media sections should be
3502 // added in the order they were added to the PeerConnection.
3503 for (auto transceiver : transceivers_) {
3504 if (transceiver->mid() || transceiver->stopped()) {
3505 continue;
3506 }
3507 size_t mline_index;
3508 if (!recycleable_mline_indices.empty()) {
3509 mline_index = recycleable_mline_indices.front();
3510 recycleable_mline_indices.pop();
3511 session_options->media_description_options[mline_index] =
3512 GetMediaDescriptionOptionsForTransceiver(transceiver,
3513 AllocateMid(&used_mids));
3514 } else {
3515 mline_index = session_options->media_description_options.size();
3516 session_options->media_description_options.push_back(
3517 GetMediaDescriptionOptionsForTransceiver(transceiver,
3518 AllocateMid(&used_mids)));
3519 }
3520 // See comment above for why CreateOffer changes the transceiver's state.
3521 transceiver->internal()->set_mline_index(mline_index);
3522 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003523 // Lastly, add a m-section if we have local data channels and an m section
3524 // does not already exist.
3525 if (!GetDataMid() && HasDataChannels()) {
3526 session_options->media_description_options.push_back(
3527 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3528 }
Steve Antondcc3c022017-12-22 16:02:54 -08003529}
3530
3531void PeerConnection::GetOptionsForAnswer(
3532 const RTCOfferAnswerOptions& offer_answer_options,
3533 cricket::MediaSessionOptions* session_options) {
3534 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3535
3536 if (IsUnifiedPlan()) {
3537 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3538 } else {
3539 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3540 }
3541
Steve Antonfa2260d2017-12-28 16:38:23 -08003542 // Intentionally unset the data channel type for RTP data channel. Otherwise
3543 // the RTP data channels would be successfully negotiated by default and the
3544 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3545 // We want to leave RTP data channels broken, so people won't try to use them.
3546 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3547 session_options->data_channel_type = data_channel_type();
3548 }
3549
Steve Antondcc3c022017-12-22 16:02:54 -08003550 // Apply ICE renomination flag.
3551 for (auto& options : session_options->media_description_options) {
3552 options.transport_options.enable_ice_renomination =
3553 configuration_.enable_ice_renomination;
3554 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003555
3556 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003557 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003558 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003559}
3560
Steve Antondcc3c022017-12-22 16:02:54 -08003561void PeerConnection::GetOptionsForPlanBAnswer(
3562 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003563 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003564 // Figure out transceiver directional preferences.
3565 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3566 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3567
3568 // By default, generate sendrecv/recvonly m= sections. The direction is also
3569 // restricted by the direction in the offer.
3570 bool recv_audio = true;
3571 bool recv_video = true;
3572
3573 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003574 if (offer_answer_options.offer_to_receive_audio !=
3575 RTCOfferAnswerOptions::kUndefined) {
3576 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003577 }
Steve Antondcc3c022017-12-22 16:02:54 -08003578 if (offer_answer_options.offer_to_receive_video !=
3579 RTCOfferAnswerOptions::kUndefined) {
3580 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003581 }
3582
3583 rtc::Optional<size_t> audio_index;
3584 rtc::Optional<size_t> video_index;
3585 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003586
3587 // Generate m= sections that match those in the offer.
3588 // Note that mediasession.cc will handle intersection our preferred
3589 // direction with the offered direction.
3590 GenerateMediaDescriptionOptions(
3591 remote_description(),
3592 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3593 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3594 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003595
3596 cricket::MediaDescriptionOptions* audio_media_description_options =
3597 !audio_index ? nullptr
3598 : &session_options->media_description_options[*audio_index];
3599 cricket::MediaDescriptionOptions* video_media_description_options =
3600 !video_index ? nullptr
3601 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003602
Steve Anton4171afb2017-11-20 10:20:22 -08003603 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003604 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003605}
zhihuangaf388472016-11-02 16:49:48 -07003606
Steve Antondcc3c022017-12-22 16:02:54 -08003607void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3608 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3609 cricket::MediaSessionOptions* session_options) {
3610 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3611 // Answers) and 5.3.2 (Subsequent Answers).
3612 RTC_DCHECK(remote_description());
3613 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3614 for (const ContentInfo& content :
3615 remote_description()->description()->contents()) {
3616 cricket::MediaType media_type = content.media_description()->type();
3617 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3618 media_type == cricket::MEDIA_TYPE_VIDEO) {
3619 auto transceiver = GetAssociatedTransceiver(content.name);
3620 RTC_CHECK(transceiver);
3621 session_options->media_description_options.push_back(
3622 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3623 } else {
3624 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003625 // Reject all data sections if data channels are disabled.
3626 // Reject a data section if it has already been rejected.
3627 // Reject all data sections except for the first one.
3628 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3629 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003630 session_options->media_description_options.push_back(
3631 GetMediaDescriptionOptionsForRejectedData(content.name));
3632 } else {
3633 session_options->media_description_options.push_back(
3634 GetMediaDescriptionOptionsForActiveData(content.name));
3635 }
Steve Antondcc3c022017-12-22 16:02:54 -08003636 }
3637 }
htaa2a49d92016-03-04 02:51:39 -08003638}
3639
zhihuang1c378ed2017-08-17 14:10:50 -07003640void PeerConnection::GenerateMediaDescriptionOptions(
3641 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003642 RtpTransceiverDirection audio_direction,
3643 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003644 rtc::Optional<size_t>* audio_index,
3645 rtc::Optional<size_t>* video_index,
3646 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003647 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003648 for (const cricket::ContentInfo& content :
3649 session_desc->description()->contents()) {
3650 if (IsAudioContent(&content)) {
3651 // If we already have an audio m= section, reject this extra one.
3652 if (*audio_index) {
3653 session_options->media_description_options.push_back(
3654 cricket::MediaDescriptionOptions(
3655 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003656 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003657 } else {
3658 session_options->media_description_options.push_back(
3659 cricket::MediaDescriptionOptions(
3660 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003661 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003662 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003663 }
3664 } else if (IsVideoContent(&content)) {
3665 // If we already have an video m= section, reject this extra one.
3666 if (*video_index) {
3667 session_options->media_description_options.push_back(
3668 cricket::MediaDescriptionOptions(
3669 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003670 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003671 } else {
3672 session_options->media_description_options.push_back(
3673 cricket::MediaDescriptionOptions(
3674 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003675 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003676 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003677 }
3678 } else {
3679 RTC_DCHECK(IsDataContent(&content));
3680 // If we already have an data m= section, reject this extra one.
3681 if (*data_index) {
3682 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003683 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003684 } else {
3685 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003686 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003687 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003688 }
3689 }
htaa2a49d92016-03-04 02:51:39 -08003690 }
deadbeefab9b2d12015-10-14 11:33:11 -07003691}
3692
Steve Antonfa2260d2017-12-28 16:38:23 -08003693cricket::MediaDescriptionOptions
3694PeerConnection::GetMediaDescriptionOptionsForActiveData(
3695 const std::string& mid) const {
3696 // Direction for data sections is meaningless, but legacy endpoints might
3697 // expect sendrecv.
3698 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3699 RtpTransceiverDirection::kSendRecv,
3700 /*stopped=*/false);
3701 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3702 return options;
3703}
3704
3705cricket::MediaDescriptionOptions
3706PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3707 const std::string& mid) const {
3708 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3709 RtpTransceiverDirection::kInactive,
3710 /*stopped=*/true);
3711 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3712 return options;
3713}
3714
3715rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3716 switch (data_channel_type_) {
3717 case cricket::DCT_RTP:
3718 if (!rtp_data_channel_) {
3719 return rtc::nullopt;
3720 }
3721 return rtp_data_channel_->content_name();
3722 case cricket::DCT_SCTP:
3723 return sctp_content_name_;
3724 default:
3725 return rtc::nullopt;
3726 }
3727}
3728
Steve Anton4171afb2017-11-20 10:20:22 -08003729void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3730 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3731 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003732 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003733}
3734
Steve Anton4171afb2017-11-20 10:20:22 -08003735void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003736 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003737 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003738 cricket::MediaType media_type,
3739 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003740 std::vector<RtpSenderInfo>* current_senders =
3741 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003742
Steve Anton4171afb2017-11-20 10:20:22 -08003743 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003744 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003745 for (auto sender_it = current_senders->begin();
3746 sender_it != current_senders->end();
3747 /* incremented manually */) {
3748 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003749 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003750 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3751 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003752 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003753 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3754 sender_exists) {
3755 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003756 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003757 OnRemoteSenderRemoved(info, media_type);
3758 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003759 }
3760 }
3761
Steve Anton4171afb2017-11-20 10:20:22 -08003762 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003763 for (const cricket::StreamParams& params : streams) {
3764 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003765 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003766 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003767 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003768 uint32_t ssrc = params.first_ssrc();
3769
3770 rtc::scoped_refptr<MediaStreamInterface> stream =
3771 remote_streams_->find(stream_label);
3772 if (!stream) {
3773 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003774 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3775 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003776 remote_streams_->AddStream(stream);
3777 new_streams->AddStream(stream);
3778 }
3779
Steve Anton4171afb2017-11-20 10:20:22 -08003780 const RtpSenderInfo* sender_info =
3781 FindSenderInfo(*current_senders, stream_label, sender_id);
3782 if (!sender_info) {
3783 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3784 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003785 }
3786 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003787
Steve Anton4171afb2017-11-20 10:20:22 -08003788 // Add default sender if necessary.
3789 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003790 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3791 remote_streams_->find(kDefaultStreamLabel);
3792 if (!default_stream) {
3793 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003794 default_stream = MediaStreamProxy::Create(
3795 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003796 remote_streams_->AddStream(default_stream);
3797 new_streams->AddStream(default_stream);
3798 }
Steve Anton4171afb2017-11-20 10:20:22 -08003799 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3800 ? kDefaultAudioSenderId
3801 : kDefaultVideoSenderId;
3802 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3803 *current_senders, kDefaultStreamLabel, default_sender_id);
3804 if (!default_sender_info) {
3805 current_senders->push_back(
3806 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3807 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003808 }
3809 }
deadbeefab9b2d12015-10-14 11:33:11 -07003810}
3811
Steve Anton4171afb2017-11-20 10:20:22 -08003812void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3813 cricket::MediaType media_type) {
3814 MediaStreamInterface* stream =
3815 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003816
3817 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003818 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003819 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003820 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003821 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003822 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003823 }
3824}
3825
Steve Anton4171afb2017-11-20 10:20:22 -08003826void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3827 cricket::MediaType media_type) {
3828 MediaStreamInterface* stream =
3829 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003830
Henrik Boström933d8b02017-10-10 10:05:16 -07003831 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003832 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003833 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3834 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003835 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003836 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003837 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003838 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003839 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003840 }
3841 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003842 // Stopping or destroying a VideoRtpReceiver will end the
3843 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003844 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003845 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003846 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003847 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003848 // There's no guarantee the track is still available, e.g. the track may
3849 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003850 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003851 }
3852 } else {
nisseede5da42017-01-12 05:15:36 -08003853 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003854 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003855 if (receiver) {
3856 observer_->OnRemoveTrack(receiver);
3857 }
deadbeefab9b2d12015-10-14 11:33:11 -07003858}
3859
3860void PeerConnection::UpdateEndedRemoteMediaStreams() {
3861 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3862 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3863 MediaStreamInterface* stream = remote_streams_->at(i);
3864 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3865 streams_to_remove.push_back(stream);
3866 }
3867 }
3868
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003869 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003870 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003871 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003872 }
3873}
3874
Steve Anton4171afb2017-11-20 10:20:22 -08003875void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003876 const std::vector<cricket::StreamParams>& streams,
3877 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003878 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003879
3880 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3881 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003882 for (auto sender_it = current_senders->begin();
3883 sender_it != current_senders->end();
3884 /* incremented manually */) {
3885 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003886 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003887 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3888 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003889 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003890 OnLocalSenderRemoved(info, media_type);
3891 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003892 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003893 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003894 }
3895 }
3896
Steve Anton4171afb2017-11-20 10:20:22 -08003897 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003898 for (const cricket::StreamParams& params : streams) {
3899 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003900 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003901 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003902 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003903 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003904 const RtpSenderInfo* sender_info =
3905 FindSenderInfo(*current_senders, stream_label, sender_id);
3906 if (!sender_info) {
3907 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3908 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003909 }
3910 }
3911}
3912
Steve Anton4171afb2017-11-20 10:20:22 -08003913void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3914 cricket::MediaType media_type) {
3915 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003916 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003917 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3918 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003919 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003920 return;
3921 }
3922
deadbeeffac06552015-11-25 11:26:01 -08003923 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003924 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003925 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003926 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003927 }
deadbeeffac06552015-11-25 11:26:01 -08003928
Steve Anton4171afb2017-11-20 10:20:22 -08003929 sender->internal()->set_stream_id(sender_info.stream_label);
3930 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003931}
3932
Steve Anton4171afb2017-11-20 10:20:22 -08003933void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3934 cricket::MediaType media_type) {
3935 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003936 if (!sender) {
3937 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003938 // SessionDescriptions has been renegotiated.
3939 return;
3940 }
deadbeeffac06552015-11-25 11:26:01 -08003941
3942 // A sender has been removed from the SessionDescription but it's still
3943 // associated with the PeerConnection. This only occurs if the SDP doesn't
3944 // match with the calls to CreateSender, AddStream and RemoveStream.
3945 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003946 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003947 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003948 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003949 }
deadbeeffac06552015-11-25 11:26:01 -08003950
Steve Anton4171afb2017-11-20 10:20:22 -08003951 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003952}
3953
3954void PeerConnection::UpdateLocalRtpDataChannels(
3955 const cricket::StreamParamsVec& streams) {
3956 std::vector<std::string> existing_channels;
3957
3958 // Find new and active data channels.
3959 for (const cricket::StreamParams& params : streams) {
3960 // |it->sync_label| is actually the data channel label. The reason is that
3961 // we use the same naming of data channels as we do for
3962 // MediaStreams and Tracks.
3963 // For MediaStreams, the sync_label is the MediaStream label and the
3964 // track label is the same as |streamid|.
3965 const std::string& channel_label = params.sync_label;
3966 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003967 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003968 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003969 continue;
3970 }
3971 // Set the SSRC the data channel should use for sending.
3972 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3973 existing_channels.push_back(data_channel_it->first);
3974 }
3975
3976 UpdateClosingRtpDataChannels(existing_channels, true);
3977}
3978
3979void PeerConnection::UpdateRemoteRtpDataChannels(
3980 const cricket::StreamParamsVec& streams) {
3981 std::vector<std::string> existing_channels;
3982
3983 // Find new and active data channels.
3984 for (const cricket::StreamParams& params : streams) {
3985 // The data channel label is either the mslabel or the SSRC if the mslabel
3986 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3987 std::string label = params.sync_label.empty()
3988 ? rtc::ToString(params.first_ssrc())
3989 : params.sync_label;
3990 auto data_channel_it = rtp_data_channels_.find(label);
3991 if (data_channel_it == rtp_data_channels_.end()) {
3992 // This is a new data channel.
3993 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3994 } else {
3995 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3996 }
3997 existing_channels.push_back(label);
3998 }
3999
4000 UpdateClosingRtpDataChannels(existing_channels, false);
4001}
4002
4003void PeerConnection::UpdateClosingRtpDataChannels(
4004 const std::vector<std::string>& active_channels,
4005 bool is_local_update) {
4006 auto it = rtp_data_channels_.begin();
4007 while (it != rtp_data_channels_.end()) {
4008 DataChannel* data_channel = it->second;
4009 if (std::find(active_channels.begin(), active_channels.end(),
4010 data_channel->label()) != active_channels.end()) {
4011 ++it;
4012 continue;
4013 }
4014
4015 if (is_local_update) {
4016 data_channel->SetSendSsrc(0);
4017 } else {
4018 data_channel->RemotePeerRequestClose();
4019 }
4020
4021 if (data_channel->state() == DataChannel::kClosed) {
4022 rtp_data_channels_.erase(it);
4023 it = rtp_data_channels_.begin();
4024 } else {
4025 ++it;
4026 }
4027 }
4028}
4029
4030void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4031 uint32_t remote_ssrc) {
4032 rtc::scoped_refptr<DataChannel> channel(
4033 InternalCreateDataChannel(label, nullptr));
4034 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004035 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004036 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004037 return;
4038 }
4039 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004040 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4041 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004042 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004043}
4044
4045rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4046 const std::string& label,
4047 const InternalDataChannelInit* config) {
4048 if (IsClosed()) {
4049 return nullptr;
4050 }
Steve Anton75737c02017-11-06 10:37:17 -08004051 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004052 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004053 << "InternalCreateDataChannel: Data is not supported in this call.";
4054 return nullptr;
4055 }
4056 InternalDataChannelInit new_config =
4057 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004058 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004059 if (new_config.id < 0) {
4060 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004061 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004062 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004063 RTC_LOG(LS_ERROR)
4064 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004065 return nullptr;
4066 }
4067 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004068 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004069 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004070 return nullptr;
4071 }
4072 }
4073
Steve Anton75737c02017-11-06 10:37:17 -08004074 rtc::scoped_refptr<DataChannel> channel(
4075 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004076 if (!channel) {
4077 sid_allocator_.ReleaseSid(new_config.id);
4078 return nullptr;
4079 }
4080
4081 if (channel->data_channel_type() == cricket::DCT_RTP) {
4082 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004083 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4084 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004085 return nullptr;
4086 }
4087 rtp_data_channels_[channel->label()] = channel;
4088 } else {
4089 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4090 sctp_data_channels_.push_back(channel);
4091 channel->SignalClosed.connect(this,
4092 &PeerConnection::OnSctpDataChannelClosed);
4093 }
4094
Steve Anton2d8609c2018-01-23 16:38:46 -08004095 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004096 return channel;
4097}
4098
4099bool PeerConnection::HasDataChannels() const {
4100 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4101}
4102
4103void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4104 for (const auto& channel : sctp_data_channels_) {
4105 if (channel->id() < 0) {
4106 int sid;
4107 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004108 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004109 continue;
4110 }
4111 channel->SetSctpSid(sid);
4112 }
4113 }
4114}
4115
4116void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004117 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004118 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4119 ++it) {
4120 if (it->get() == channel) {
4121 if (channel->id() >= 0) {
4122 sid_allocator_.ReleaseSid(channel->id());
4123 }
deadbeefbd292462015-12-14 18:15:29 -08004124 // Since this method is triggered by a signal from the DataChannel,
4125 // we can't free it directly here; we need to free it asynchronously.
4126 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004127 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004128 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4129 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004130 return;
4131 }
4132 }
4133}
4134
deadbeefab9b2d12015-10-14 11:33:11 -07004135void PeerConnection::OnDataChannelDestroyed() {
4136 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4137 // DataChannel may callback to us and try to modify the list.
4138 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4139 temp_rtp_dcs.swap(rtp_data_channels_);
4140 for (const auto& kv : temp_rtp_dcs) {
4141 kv.second->OnTransportChannelDestroyed();
4142 }
4143
4144 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4145 temp_sctp_dcs.swap(sctp_data_channels_);
4146 for (const auto& channel : temp_sctp_dcs) {
4147 channel->OnTransportChannelDestroyed();
4148 }
4149}
4150
4151void PeerConnection::OnDataChannelOpenMessage(
4152 const std::string& label,
4153 const InternalDataChannelInit& config) {
4154 rtc::scoped_refptr<DataChannel> channel(
4155 InternalCreateDataChannel(label, &config));
4156 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004157 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004158 return;
4159 }
4160
deadbeefa601f5c2016-06-06 14:27:39 -07004161 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4162 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004163 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004164}
4165
Steve Anton4171afb2017-11-20 10:20:22 -08004166rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4167PeerConnection::GetAudioTransceiver() const {
4168 // This method only works with Plan B SDP, where there is a single
4169 // audio/video transceiver.
4170 RTC_DCHECK(!IsUnifiedPlan());
4171 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004172 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004173 return transceiver;
4174 }
4175 }
4176 RTC_NOTREACHED();
4177 return nullptr;
4178}
4179
4180rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4181PeerConnection::GetVideoTransceiver() const {
4182 // This method only works with Plan B SDP, where there is a single
4183 // audio/video transceiver.
4184 RTC_DCHECK(!IsUnifiedPlan());
4185 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004186 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004187 return transceiver;
4188 }
4189 }
4190 RTC_NOTREACHED();
4191 return nullptr;
4192}
4193
4194// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4195// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004196bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004197 switch (type) {
4198 case cricket::MEDIA_TYPE_AUDIO:
4199 return !GetAudioTransceiver()->internal()->senders().empty();
4200 case cricket::MEDIA_TYPE_VIDEO:
4201 return !GetVideoTransceiver()->internal()->senders().empty();
4202 case cricket::MEDIA_TYPE_DATA:
4203 return false;
4204 }
4205 RTC_NOTREACHED();
4206 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004207}
4208
Steve Anton4171afb2017-11-20 10:20:22 -08004209rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4210PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4211 for (auto transceiver : transceivers_) {
4212 for (auto sender : transceiver->internal()->senders()) {
4213 if (sender->track() == track) {
4214 return sender;
4215 }
4216 }
4217 }
4218 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004219}
4220
Steve Anton4171afb2017-11-20 10:20:22 -08004221rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4222PeerConnection::FindSenderById(const std::string& sender_id) const {
4223 for (auto transceiver : transceivers_) {
4224 for (auto sender : transceiver->internal()->senders()) {
4225 if (sender->id() == sender_id) {
4226 return sender;
4227 }
4228 }
4229 }
4230 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004231}
4232
Steve Anton4171afb2017-11-20 10:20:22 -08004233rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4234PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4235 for (auto transceiver : transceivers_) {
4236 for (auto receiver : transceiver->internal()->receivers()) {
4237 if (receiver->id() == receiver_id) {
4238 return receiver;
4239 }
4240 }
4241 }
4242 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004243}
4244
Steve Anton4171afb2017-11-20 10:20:22 -08004245std::vector<PeerConnection::RtpSenderInfo>*
4246PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4247 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4248 media_type == cricket::MEDIA_TYPE_VIDEO);
4249 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4250 ? &remote_audio_sender_infos_
4251 : &remote_video_sender_infos_;
4252}
4253
4254std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004255 cricket::MediaType media_type) {
4256 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4257 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004258 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4259 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004260}
4261
Steve Anton4171afb2017-11-20 10:20:22 -08004262const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4263 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004264 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004265 const std::string sender_id) const {
4266 for (const RtpSenderInfo& sender_info : infos) {
4267 if (sender_info.stream_label == stream_label &&
4268 sender_info.sender_id == sender_id) {
4269 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004270 }
4271 }
4272 return nullptr;
4273}
4274
4275DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4276 for (const auto& channel : sctp_data_channels_) {
4277 if (channel->id() == sid) {
4278 return channel;
4279 }
4280 }
4281 return nullptr;
4282}
4283
deadbeef91dd5672016-05-18 16:55:30 -07004284bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004285 const RTCConfiguration& configuration) {
4286 cricket::ServerAddresses stun_servers;
4287 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004288 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4289 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004290 return false;
4291 }
4292
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004293 port_allocator_->Initialize();
4294
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004295 // To handle both internal and externally created port allocator, we will
4296 // enable BUNDLE here.
4297 int portallocator_flags = port_allocator_->flags();
4298 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004299 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4300 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004301 // If the disable-IPv6 flag was specified, we'll not override it
4302 // by experiment.
4303 if (configuration.disable_ipv6) {
4304 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004305 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4306 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004307 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4308 }
4309
zhihuangb09b3f92017-03-07 14:40:51 -08004310 if (configuration.disable_ipv6_on_wifi) {
4311 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004312 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004313 }
4314
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004315 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4316 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004317 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004318 }
4319
honghaiz60347052016-05-31 18:29:12 -07004320 if (configuration.candidate_network_policy ==
4321 kCandidateNetworkPolicyLowCost) {
4322 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004323 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004324 }
4325
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004326 if (configuration.disable_link_local_networks) {
4327 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4328 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4329 }
4330
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004331 port_allocator_->set_flags(portallocator_flags);
4332 // No step delay is used while allocating ports.
4333 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4334 port_allocator_->set_candidate_filter(
4335 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004336 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004337
4338 // Call this last since it may create pooled allocator sessions using the
4339 // properties set above.
4340 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004341 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004342 configuration.prune_turn_ports,
4343 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004344 return true;
4345}
4346
deadbeef91dd5672016-05-18 16:55:30 -07004347bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004348 const cricket::ServerAddresses& stun_servers,
4349 const std::vector<cricket::RelayServerConfig>& turn_servers,
4350 IceTransportsType type,
4351 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004352 bool prune_turn_ports,
4353 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004354 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004355 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004356 // Call this last since it may create pooled allocator sessions using the
4357 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004358 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004359 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4360 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004361}
4362
Steve Antonba818672017-11-06 10:21:57 -08004363cricket::ChannelManager* PeerConnection::channel_manager() const {
4364 return factory_->channel_manager();
4365}
4366
4367MetricsObserverInterface* PeerConnection::metrics_observer() const {
4368 return uma_observer_;
4369}
4370
Elad Alon99c3fe52017-10-13 16:29:40 +02004371bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004372 std::unique_ptr<RtcEventLogOutput> output,
4373 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004374 if (!event_log_) {
4375 return false;
4376 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004377 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004378}
4379
4380void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004381 if (event_log_) {
4382 event_log_->StopLogging();
4383 }
ivoc14d5dbe2016-07-04 07:06:55 -07004384}
nisseeaabdf62017-05-05 02:23:02 -07004385
Steve Anton75737c02017-11-06 10:37:17 -08004386cricket::BaseChannel* PeerConnection::GetChannel(
4387 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004388 for (auto transceiver : transceivers_) {
4389 cricket::BaseChannel* channel = transceiver->internal()->channel();
4390 if (channel && channel->content_name() == content_name) {
4391 return channel;
4392 }
Steve Anton75737c02017-11-06 10:37:17 -08004393 }
4394 if (rtp_data_channel() &&
4395 rtp_data_channel()->content_name() == content_name) {
4396 return rtp_data_channel();
4397 }
4398 return nullptr;
4399}
4400
4401bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4402 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004403 RTC_LOG(LS_INFO)
4404 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004405 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004406 return false;
4407 }
4408 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004409 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004410 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004411 return false;
4412 }
4413
4414 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4415}
4416
4417bool PeerConnection::GetSslRole(const std::string& content_name,
4418 rtc::SSLRole* role) {
4419 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004420 RTC_LOG(LS_INFO)
4421 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004422 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004423 return false;
4424 }
4425
4426 return transport_controller_->GetSslRole(GetTransportName(content_name),
4427 role);
4428}
4429
Steve Antonf8470812017-12-04 10:46:21 -08004430void PeerConnection::SetSessionError(SessionError error,
4431 const std::string& error_desc) {
4432 RTC_DCHECK_RUN_ON(signaling_thread());
4433 if (error != session_error_) {
4434 session_error_ = error;
4435 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004436 }
4437}
4438
Steve Anton3828c062017-12-06 10:34:51 -08004439RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004440 cricket::ContentSource source) {
4441 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004442
4443 // If there's already a pending error then no state transition should happen.
4444 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004445 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004446
4447 // If this is an answer then we know whether to BUNDLE or not. If both the
4448 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004449 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004450 const cricket::ContentGroup* local_bundle =
4451 local_description()->description()->GetGroupByName(
4452 cricket::GROUP_TYPE_BUNDLE);
4453 const cricket::ContentGroup* remote_bundle =
4454 remote_description()->description()->GetGroupByName(
4455 cricket::GROUP_TYPE_BUNDLE);
4456 if (local_bundle && remote_bundle) {
4457 // The answerer decides the transport to bundle on.
4458 const cricket::ContentGroup* answer_bundle =
4459 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4460 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004461 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4462 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004463 }
4464 }
Steve Anton75737c02017-11-06 10:37:17 -08004465 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004466
4467 // Only push down the transport description after potentially enabling BUNDLE;
4468 // we don't want to push down a description on a transport about to be
4469 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004470 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004471 if (!error.ok()) {
4472 return error;
4473 }
4474
4475 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004476 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004477 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004478 }
4479
4480 // Update the signaling state according to the specified state machine (see
4481 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004482 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004483 ChangeSignalingState(source == cricket::CS_LOCAL
4484 ? PeerConnectionInterface::kHaveLocalOffer
4485 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004486 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004487 ChangeSignalingState(source == cricket::CS_LOCAL
4488 ? PeerConnectionInterface::kHaveLocalPrAnswer
4489 : PeerConnectionInterface::kHaveRemotePrAnswer);
4490 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004491 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004492 ChangeSignalingState(PeerConnectionInterface::kStable);
4493 }
4494
4495 // Update internal objects according to the session description's media
4496 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004497 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004498 if (!error.ok()) {
4499 SetSessionError(SessionError::kContent, error.message());
4500 }
4501 if (session_error() != SessionError::kNone) {
4502 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4503 }
4504
Steve Anton8a006912017-12-04 15:25:56 -08004505 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004506}
4507
Steve Anton8a006912017-12-04 15:25:56 -08004508RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004509 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004510 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004511 const SessionDescriptionInterface* sdesc =
4512 (source == cricket::CS_LOCAL ? local_description()
4513 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004514 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004515
4516 // Push down the new SDP media section for each audio/video transceiver.
4517 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004518 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004519 FindMediaSectionForTransceiver(transceiver, sdesc);
4520 cricket::BaseChannel* channel = transceiver->internal()->channel();
4521 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004522 continue;
4523 }
4524 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004525 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004526 if (!content_desc) {
4527 continue;
4528 }
4529 std::string error;
4530 bool success =
4531 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004532 ? channel->SetLocalContent(content_desc, type, &error)
4533 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004534 if (!success) {
4535 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4536 }
4537 }
4538
4539 // If using the RtpDataChannel, push down the new SDP section for it too.
4540 if (rtp_data_channel_) {
4541 const ContentInfo* data_content =
4542 cricket::GetFirstDataContent(sdesc->description());
4543 if (data_content && !data_content->rejected) {
4544 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004545 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004546 if (data_desc) {
4547 std::string error;
4548 bool success =
4549 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004550 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4551 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004552 &error);
4553 if (!success) {
4554 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4555 std::move(error));
4556 }
Steve Anton75737c02017-11-06 10:37:17 -08004557 }
4558 }
4559 }
Steve Antoned10bd92017-12-05 10:52:59 -08004560
Steve Anton75737c02017-11-06 10:37:17 -08004561 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4562 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4563 if (sctp_transport_ && local_description() && remote_description() &&
4564 cricket::GetFirstDataContent(local_description()->description()) &&
4565 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004566 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004567 RTC_FROM_HERE,
4568 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004569 if (!success) {
4570 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4571 "Failed to push down SCTP parameters.");
4572 }
Steve Anton75737c02017-11-06 10:37:17 -08004573 }
Steve Antoned10bd92017-12-05 10:52:59 -08004574
Steve Anton8a006912017-12-04 15:25:56 -08004575 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004576}
4577
4578bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4579 RTC_DCHECK(network_thread()->IsCurrent());
4580 RTC_DCHECK(local_description());
4581 RTC_DCHECK(remote_description());
4582 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4583 // When we support "max-message-size", that would also be pushed down here.
4584 return sctp_transport_->Start(
4585 GetSctpPort(local_description()->description()),
4586 GetSctpPort(remote_description()->description()));
4587}
4588
Steve Anton8a006912017-12-04 15:25:56 -08004589RTCError PeerConnection::PushdownTransportDescription(
4590 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004591 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004592 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004593
Steve Anton8a006912017-12-04 15:25:56 -08004594 const SessionDescriptionInterface* sdesc =
4595 (source == cricket::CS_LOCAL ? local_description()
4596 : remote_description());
4597 RTC_DCHECK(sdesc);
4598 for (const cricket::TransportInfo& tinfo :
4599 sdesc->description()->transport_infos()) {
4600 std::string error;
4601 bool success;
4602 if (source == cricket::CS_LOCAL) {
4603 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004604 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004605 } else {
4606 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004607 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004608 }
4609 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004610 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4611 "Failed to push down transport description for " +
4612 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004613 }
4614 }
4615
Steve Anton8a006912017-12-04 15:25:56 -08004616 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004617}
4618
4619bool PeerConnection::GetTransportDescription(
4620 const SessionDescription* description,
4621 const std::string& content_name,
4622 cricket::TransportDescription* tdesc) {
4623 if (!description || !tdesc) {
4624 return false;
4625 }
4626 const TransportInfo* transport_info =
4627 description->GetTransportInfoByName(content_name);
4628 if (!transport_info) {
4629 return false;
4630 }
4631 *tdesc = transport_info->description;
4632 return true;
4633}
4634
4635bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4636 const std::string* first_content_name = bundle.FirstContentName();
4637 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004638 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004639 return false;
4640 }
4641 const std::string& transport_name = *first_content_name;
4642
4643 auto maybe_set_transport = [this, bundle,
4644 transport_name](cricket::BaseChannel* ch) {
4645 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004646 return;
Steve Anton75737c02017-11-06 10:37:17 -08004647 }
4648
4649 std::string old_transport_name = ch->transport_name();
4650 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004651 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4652 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004653 return;
Steve Anton75737c02017-11-06 10:37:17 -08004654 }
4655
4656 cricket::DtlsTransportInternal* rtp_dtls_transport =
4657 transport_controller_->CreateDtlsTransport(
4658 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4659 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4660 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4661 if (need_rtcp) {
4662 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4663 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4664 }
4665
4666 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004667 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4668 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004669 transport_controller_->DestroyDtlsTransport(
4670 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4671 // If the channel needs rtcp, it means that the channel used to have a
4672 // rtcp transport which needs to be deleted now.
4673 if (need_rtcp) {
4674 transport_controller_->DestroyDtlsTransport(
4675 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4676 }
Steve Anton75737c02017-11-06 10:37:17 -08004677 };
4678
Steve Antoned10bd92017-12-05 10:52:59 -08004679 for (auto transceiver : transceivers_) {
4680 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004681 }
Steve Antoned10bd92017-12-05 10:52:59 -08004682 maybe_set_transport(rtp_data_channel_);
4683
Steve Anton75737c02017-11-06 10:37:17 -08004684 // For SCTP, transport creation/deletion happens here instead of in the
4685 // object itself.
4686 if (sctp_transport_) {
4687 RTC_DCHECK(sctp_transport_name_);
4688 RTC_DCHECK(sctp_content_name_);
4689 if (transport_name != *sctp_transport_name_ &&
4690 bundle.HasContentName(*sctp_content_name_)) {
4691 network_thread()->Invoke<void>(
4692 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4693 transport_name));
4694 }
4695 }
4696
4697 return true;
4698}
4699
Steve Anton75737c02017-11-06 10:37:17 -08004700cricket::IceConfig PeerConnection::ParseIceConfig(
4701 const PeerConnectionInterface::RTCConfiguration& config) const {
4702 cricket::ContinualGatheringPolicy gathering_policy;
4703 // TODO(honghaiz): Add the third continual gathering policy in
4704 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4705 switch (config.continual_gathering_policy) {
4706 case PeerConnectionInterface::GATHER_ONCE:
4707 gathering_policy = cricket::GATHER_ONCE;
4708 break;
4709 case PeerConnectionInterface::GATHER_CONTINUALLY:
4710 gathering_policy = cricket::GATHER_CONTINUALLY;
4711 break;
4712 default:
4713 RTC_NOTREACHED();
4714 gathering_policy = cricket::GATHER_ONCE;
4715 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004716
Steve Anton75737c02017-11-06 10:37:17 -08004717 cricket::IceConfig ice_config;
4718 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4719 ice_config.prioritize_most_likely_candidate_pairs =
4720 config.prioritize_most_likely_ice_candidate_pairs;
4721 ice_config.backup_connection_ping_interval =
4722 config.ice_backup_candidate_pair_ping_interval;
4723 ice_config.continual_gathering_policy = gathering_policy;
4724 ice_config.presume_writable_when_fully_relayed =
4725 config.presume_writable_when_fully_relayed;
4726 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4727 ice_config.regather_all_networks_interval_range =
4728 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004729 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004730 return ice_config;
4731}
4732
Steve Anton75737c02017-11-06 10:37:17 -08004733bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4734 std::string* track_id) {
4735 if (!local_description()) {
4736 return false;
4737 }
4738 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4739 track_id);
4740}
4741
4742bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4743 std::string* track_id) {
4744 if (!remote_description()) {
4745 return false;
4746 }
4747 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4748 track_id);
4749}
4750
4751bool PeerConnection::SendData(const cricket::SendDataParams& params,
4752 const rtc::CopyOnWriteBuffer& payload,
4753 cricket::SendDataResult* result) {
4754 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004755 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004756 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004757 return false;
4758 }
4759 return rtp_data_channel_
4760 ? rtp_data_channel_->SendData(params, payload, result)
4761 : network_thread()->Invoke<bool>(
4762 RTC_FROM_HERE,
4763 Bind(&cricket::SctpTransportInternal::SendData,
4764 sctp_transport_.get(), params, payload, result));
4765}
4766
4767bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4768 if (!rtp_data_channel_ && !sctp_transport_) {
4769 // Don't log an error here, because DataChannels are expected to call
4770 // ConnectDataChannel in this state. It's the only way to initially tell
4771 // whether or not the underlying transport is ready.
4772 return false;
4773 }
4774 if (rtp_data_channel_) {
4775 rtp_data_channel_->SignalReadyToSendData.connect(
4776 webrtc_data_channel, &DataChannel::OnChannelReady);
4777 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4778 &DataChannel::OnDataReceived);
4779 } else {
4780 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4781 &DataChannel::OnChannelReady);
4782 SignalSctpDataReceived.connect(webrtc_data_channel,
4783 &DataChannel::OnDataReceived);
4784 SignalSctpStreamClosedRemotely.connect(
4785 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4786 }
4787 return true;
4788}
4789
4790void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4791 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004792 RTC_LOG(LS_ERROR)
4793 << "DisconnectDataChannel called when rtp_data_channel_ and "
4794 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004795 return;
4796 }
4797 if (rtp_data_channel_) {
4798 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4799 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4800 } else {
4801 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4802 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4803 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4804 }
4805}
4806
4807void PeerConnection::AddSctpDataStream(int sid) {
4808 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004809 RTC_LOG(LS_ERROR)
4810 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004811 return;
4812 }
4813 network_thread()->Invoke<void>(
4814 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4815 sctp_transport_.get(), sid));
4816}
4817
4818void PeerConnection::RemoveSctpDataStream(int sid) {
4819 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004820 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004821 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004822 return;
4823 }
4824 network_thread()->Invoke<void>(
4825 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4826 sctp_transport_.get(), sid));
4827}
4828
4829bool PeerConnection::ReadyToSendData() const {
4830 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4831 sctp_ready_to_send_data_;
4832}
4833
Steve Anton5dfde182018-02-06 10:34:40 -08004834std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4835 const {
4836 std::map<std::string, std::string> transport_names_by_mid;
4837 for (auto transceiver : transceivers_) {
4838 cricket::BaseChannel* channel = transceiver->internal()->channel();
4839 if (channel) {
4840 transport_names_by_mid[channel->content_name()] =
4841 channel->transport_name();
4842 }
Steve Anton75737c02017-11-06 10:37:17 -08004843 }
Steve Anton5dfde182018-02-06 10:34:40 -08004844 if (rtp_data_channel_) {
4845 transport_names_by_mid[rtp_data_channel_->content_name()] =
4846 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004847 }
4848 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004849 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004850 }
Steve Anton5dfde182018-02-06 10:34:40 -08004851 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004852}
4853
Steve Anton5dfde182018-02-06 10:34:40 -08004854std::map<std::string, cricket::TransportStats>
4855PeerConnection::GetTransportStatsByNames(
4856 const std::set<std::string>& transport_names) {
4857 if (!network_thread()->IsCurrent()) {
4858 return network_thread()
4859 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4860 RTC_FROM_HERE,
4861 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004862 }
Steve Anton5dfde182018-02-06 10:34:40 -08004863 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4864 for (const std::string& transport_name : transport_names) {
4865 cricket::TransportStats transport_stats;
4866 bool success =
4867 transport_controller_->GetStats(transport_name, &transport_stats);
4868 if (success) {
4869 transport_stats_by_name[transport_name] = std::move(transport_stats);
4870 } else {
4871 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4872 << transport_name;
4873 }
4874 }
4875 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004876}
4877
4878bool PeerConnection::GetLocalCertificate(
4879 const std::string& transport_name,
4880 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4881 return transport_controller_->GetLocalCertificate(transport_name,
4882 certificate);
4883}
4884
4885std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4886 const std::string& transport_name) {
4887 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4888}
4889
4890cricket::DataChannelType PeerConnection::data_channel_type() const {
4891 return data_channel_type_;
4892}
4893
4894bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4895 return pending_ice_restarts_.find(content_name) !=
4896 pending_ice_restarts_.end();
4897}
4898
Steve Anton75737c02017-11-06 10:37:17 -08004899bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4900 return transport_controller_->NeedsIceRestart(content_name);
4901}
4902
4903void PeerConnection::OnCertificateReady(
4904 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4905 transport_controller_->SetLocalCertificate(certificate);
4906}
4907
4908void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004909 SetSessionError(SessionError::kTransport,
4910 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004911}
4912
4913void PeerConnection::OnTransportControllerConnectionState(
4914 cricket::IceConnectionState state) {
4915 switch (state) {
4916 case cricket::kIceConnectionConnecting:
4917 // If the current state is Connected or Completed, then there were
4918 // writable channels but now there are not, so the next state must
4919 // be Disconnected.
4920 // kIceConnectionConnecting is currently used as the default,
4921 // un-connected state by the TransportController, so its only use is
4922 // detecting disconnections.
4923 if (ice_connection_state_ ==
4924 PeerConnectionInterface::kIceConnectionConnected ||
4925 ice_connection_state_ ==
4926 PeerConnectionInterface::kIceConnectionCompleted) {
4927 SetIceConnectionState(
4928 PeerConnectionInterface::kIceConnectionDisconnected);
4929 }
4930 break;
4931 case cricket::kIceConnectionFailed:
4932 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4933 break;
4934 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004935 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004936 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004937 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4938 break;
4939 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004940 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004941 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004942 if (ice_connection_state_ !=
4943 PeerConnectionInterface::kIceConnectionConnected) {
4944 // If jumping directly from "checking" to "connected",
4945 // signal "connected" first.
4946 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4947 }
4948 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4949 if (metrics_observer()) {
4950 ReportTransportStats();
4951 }
4952 break;
4953 default:
4954 RTC_NOTREACHED();
4955 }
4956}
4957
4958void PeerConnection::OnTransportControllerCandidatesGathered(
4959 const std::string& transport_name,
4960 const cricket::Candidates& candidates) {
4961 RTC_DCHECK(signaling_thread()->IsCurrent());
4962 int sdp_mline_index;
4963 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004964 RTC_LOG(LS_ERROR)
4965 << "OnTransportControllerCandidatesGathered: content name "
4966 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004967 return;
4968 }
4969
4970 for (cricket::Candidates::const_iterator citer = candidates.begin();
4971 citer != candidates.end(); ++citer) {
4972 // Use transport_name as the candidate media id.
4973 std::unique_ptr<JsepIceCandidate> candidate(
4974 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4975 if (local_description()) {
4976 mutable_local_description()->AddCandidate(candidate.get());
4977 }
4978 OnIceCandidate(std::move(candidate));
4979 }
4980}
4981
4982void PeerConnection::OnTransportControllerCandidatesRemoved(
4983 const std::vector<cricket::Candidate>& candidates) {
4984 RTC_DCHECK(signaling_thread()->IsCurrent());
4985 // Sanity check.
4986 for (const cricket::Candidate& candidate : candidates) {
4987 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004988 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004989 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01004990 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004991 return;
4992 }
4993 }
4994
4995 if (local_description()) {
4996 mutable_local_description()->RemoveCandidates(candidates);
4997 }
4998 OnIceCandidatesRemoved(candidates);
4999}
5000
5001void PeerConnection::OnTransportControllerDtlsHandshakeError(
5002 rtc::SSLHandshakeError error) {
5003 if (metrics_observer()) {
5004 metrics_observer()->IncrementEnumCounter(
5005 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5006 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5007 }
5008}
5009
Steve Antoned10bd92017-12-05 10:52:59 -08005010void PeerConnection::EnableSending() {
5011 for (auto transceiver : transceivers_) {
5012 cricket::BaseChannel* channel = transceiver->internal()->channel();
5013 if (channel && !channel->enabled()) {
5014 channel->Enable(true);
5015 }
Steve Anton75737c02017-11-06 10:37:17 -08005016 }
5017
Steve Anton4171afb2017-11-20 10:20:22 -08005018 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005019 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005020 }
Steve Anton75737c02017-11-06 10:37:17 -08005021}
5022
5023// Returns the media index for a local ice candidate given the content name.
5024bool PeerConnection::GetLocalCandidateMediaIndex(
5025 const std::string& content_name,
5026 int* sdp_mline_index) {
5027 if (!local_description() || !sdp_mline_index) {
5028 return false;
5029 }
5030
5031 bool content_found = false;
5032 const ContentInfos& contents = local_description()->description()->contents();
5033 for (size_t index = 0; index < contents.size(); ++index) {
5034 if (contents[index].name == content_name) {
5035 *sdp_mline_index = static_cast<int>(index);
5036 content_found = true;
5037 break;
5038 }
5039 }
5040 return content_found;
5041}
5042
5043bool PeerConnection::UseCandidatesInSessionDescription(
5044 const SessionDescriptionInterface* remote_desc) {
5045 if (!remote_desc) {
5046 return true;
5047 }
5048 bool ret = true;
5049
5050 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5051 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5052 for (size_t n = 0; n < candidates->count(); ++n) {
5053 const IceCandidateInterface* candidate = candidates->at(n);
5054 bool valid = false;
5055 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5056 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005057 RTC_LOG(LS_INFO)
5058 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005059 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005060 }
5061 continue;
5062 }
5063 ret = UseCandidate(candidate);
5064 if (!ret) {
5065 break;
5066 }
5067 }
5068 }
5069 return ret;
5070}
5071
5072bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5073 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5074 size_t remote_content_size =
5075 remote_description()->description()->contents().size();
5076 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005077 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005078 return false;
5079 }
5080
5081 cricket::ContentInfo content =
5082 remote_description()->description()->contents()[mediacontent_index];
5083 std::vector<cricket::Candidate> candidates;
5084 candidates.push_back(candidate->candidate());
5085 // Invoking BaseSession method to handle remote candidates.
5086 std::string error;
5087 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5088 &error)) {
5089 // Candidates successfully submitted for checking.
5090 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5091 ice_connection_state_ ==
5092 PeerConnectionInterface::kIceConnectionDisconnected) {
5093 // If state is New, then the session has just gotten its first remote ICE
5094 // candidates, so go to Checking.
5095 // If state is Disconnected, the session is re-using old candidates or
5096 // receiving additional ones, so go to Checking.
5097 // If state is Connected, stay Connected.
5098 // TODO(bemasc): If state is Connected, and the new candidates are for a
5099 // newly added transport, then the state actually _should_ move to
5100 // checking. Add a way to distinguish that case.
5101 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5102 }
5103 // TODO(bemasc): If state is Completed, go back to Connected.
5104 } else {
5105 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005106 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005107 }
5108 }
5109 return true;
5110}
5111
5112void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005113 // Destroy video channel first since it may have a pointer to the
5114 // voice channel.
5115 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005116 if (!video_info || video_info->rejected) {
5117 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005118 }
5119
Steve Anton6fec8802017-12-04 10:37:29 -08005120 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5121 if (!audio_info || audio_info->rejected) {
5122 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005123 }
5124
5125 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5126 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005127 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005128 }
5129}
5130
Steve Antoneda6ccd2017-12-04 10:21:55 -08005131std::string PeerConnection::GetTransportNameForMediaSection(
5132 const std::string& mid,
5133 const cricket::ContentGroup* bundle_group) const {
5134 if (!bundle_group) {
5135 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005136 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005137 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005138 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005140 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005141 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005142 if (!bundle_group->HasContentName(mid)) {
5143 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5144 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005146 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5147 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005148}
5149
Steve Antondcc3c022017-12-22 16:02:54 -08005150RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5151 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005152 const cricket::ContentGroup* bundle_group = nullptr;
5153 if (configuration_.bundle_policy ==
5154 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005155 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005156 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5158 "max-bundle configured but session description "
5159 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005160 }
5161 }
Steve Antondcc3c022017-12-22 16:02:54 -08005162 return std::move(bundle_group);
5163}
5164
5165RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5166 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5167 if (!bundle_group_or_error.ok()) {
5168 return bundle_group_or_error.MoveError();
5169 }
5170 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005171
Steve Antoneda6ccd2017-12-04 10:21:55 -08005172 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005173 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005174 if (voice && !voice->rejected &&
5175 !GetAudioTransceiver()->internal()->channel()) {
5176 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5177 voice->name,
5178 GetTransportNameForMediaSection(voice->name, bundle_group));
5179 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005180 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5181 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005182 }
5183 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5184 }
5185
Steve Antondcc3c022017-12-22 16:02:54 -08005186 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005187 if (video && !video->rejected &&
5188 !GetVideoTransceiver()->internal()->channel()) {
5189 cricket::VideoChannel* video_channel = CreateVideoChannel(
5190 video->name,
5191 GetTransportNameForMediaSection(video->name, bundle_group));
5192 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005193 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5194 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005195 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005196 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005197 }
5198
Steve Antondcc3c022017-12-22 16:02:54 -08005199 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005200 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5201 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005202 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5203 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005204 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5205 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005206 }
5207 }
5208
Steve Anton8a006912017-12-04 15:25:56 -08005209 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005210}
5211
Steve Anton4171afb2017-11-20 10:20:22 -08005212// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005213cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5214 const std::string& mid,
5215 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005216 cricket::DtlsTransportInternal* rtp_dtls_transport =
5217 transport_controller_->CreateDtlsTransport(
5218 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5219 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5220 if (configuration_.rtcp_mux_policy !=
5221 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5222 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5223 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5224 }
5225
5226 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5227 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005228 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5229 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005230 if (!voice_channel) {
5231 transport_controller_->DestroyDtlsTransport(
5232 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5233 if (rtcp_dtls_transport) {
5234 transport_controller_->DestroyDtlsTransport(
5235 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5236 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005237 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005238 }
Steve Anton75737c02017-11-06 10:37:17 -08005239 voice_channel->SignalRtcpMuxFullyActive.connect(
5240 this, &PeerConnection::DestroyRtcpTransport_n);
5241 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5242 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005243 voice_channel->SignalSentPacket.connect(this,
5244 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005245
Steve Antoneda6ccd2017-12-04 10:21:55 -08005246 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005247}
5248
Steve Anton4171afb2017-11-20 10:20:22 -08005249// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005250cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5251 const std::string& mid,
5252 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005253 cricket::DtlsTransportInternal* rtp_dtls_transport =
5254 transport_controller_->CreateDtlsTransport(
5255 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5256 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5257 if (configuration_.rtcp_mux_policy !=
5258 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5259 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5260 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5261 }
5262
5263 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5264 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005265 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5266 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005267
5268 if (!video_channel) {
5269 transport_controller_->DestroyDtlsTransport(
5270 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5271 if (rtcp_dtls_transport) {
5272 transport_controller_->DestroyDtlsTransport(
5273 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5274 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005275 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
Steve Anton75737c02017-11-06 10:37:17 -08005277 video_channel->SignalRtcpMuxFullyActive.connect(
5278 this, &PeerConnection::DestroyRtcpTransport_n);
5279 video_channel->SignalDtlsSrtpSetupFailure.connect(
5280 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005281 video_channel->SignalSentPacket.connect(this,
5282 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005283
Steve Antoneda6ccd2017-12-04 10:21:55 -08005284 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005285}
5286
Steve Antoneda6ccd2017-12-04 10:21:55 -08005287bool PeerConnection::CreateDataChannel(const std::string& mid,
5288 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005289 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5290 if (sctp) {
5291 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005292 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005293 << "Trying to create SCTP transport, but didn't compile with "
5294 "SCTP support (HAVE_SCTP)";
5295 return false;
5296 }
5297 if (!network_thread()->Invoke<bool>(
5298 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005299 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005300 return false;
5301 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005302 for (const auto& channel : sctp_data_channels_) {
5303 channel->OnTransportChannelCreated();
5304 }
Steve Anton75737c02017-11-06 10:37:17 -08005305 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005306 cricket::DtlsTransportInternal* rtp_dtls_transport =
5307 transport_controller_->CreateDtlsTransport(
5308 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5309 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5310 if (configuration_.rtcp_mux_policy !=
5311 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5312 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5313 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5314 }
5315
5316 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5317 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005318 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005319
5320 if (!rtp_data_channel_) {
5321 transport_controller_->DestroyDtlsTransport(
5322 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5323 if (rtcp_dtls_transport) {
5324 transport_controller_->DestroyDtlsTransport(
5325 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5326 }
5327 return false;
5328 }
5329
5330 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5331 this, &PeerConnection::DestroyRtcpTransport_n);
5332 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5333 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5334 rtp_data_channel_->SignalSentPacket.connect(
5335 this, &PeerConnection::OnSentPacket_w);
5336 }
5337
Steve Anton75737c02017-11-06 10:37:17 -08005338 return true;
5339}
5340
5341Call::Stats PeerConnection::GetCallStats() {
5342 if (!worker_thread()->IsCurrent()) {
5343 return worker_thread()->Invoke<Call::Stats>(
5344 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5345 }
5346 if (call_) {
5347 return call_->GetStats();
5348 } else {
5349 return Call::Stats();
5350 }
5351}
5352
Steve Anton75737c02017-11-06 10:37:17 -08005353bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5354 const std::string& transport_name) {
5355 RTC_DCHECK(network_thread()->IsCurrent());
5356 RTC_DCHECK(sctp_factory_);
5357 cricket::DtlsTransportInternal* tc =
5358 transport_controller_->CreateDtlsTransport_n(
5359 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5360 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5361 RTC_DCHECK(sctp_transport_);
5362 sctp_invoker_.reset(new rtc::AsyncInvoker());
5363 sctp_transport_->SignalReadyToSendData.connect(
5364 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5365 sctp_transport_->SignalDataReceived.connect(
5366 this, &PeerConnection::OnSctpTransportDataReceived_n);
5367 sctp_transport_->SignalStreamClosedRemotely.connect(
5368 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005369 sctp_transport_name_ = transport_name;
5370 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005371 return true;
5372}
5373
5374void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5375 RTC_DCHECK(network_thread()->IsCurrent());
5376 RTC_DCHECK(sctp_transport_);
5377 RTC_DCHECK(sctp_transport_name_);
5378 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005379 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005380 cricket::DtlsTransportInternal* tc =
5381 transport_controller_->CreateDtlsTransport_n(
5382 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5383 sctp_transport_->SetTransportChannel(tc);
5384 transport_controller_->DestroyDtlsTransport_n(
5385 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5386}
5387
5388void PeerConnection::DestroySctpTransport_n() {
5389 RTC_DCHECK(network_thread()->IsCurrent());
5390 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005391 transport_controller_->DestroyDtlsTransport_n(
5392 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005393 sctp_content_name_.reset();
5394 sctp_transport_name_.reset();
5395 sctp_invoker_.reset(nullptr);
5396 sctp_ready_to_send_data_ = false;
5397}
5398
5399void PeerConnection::OnSctpTransportReadyToSendData_n() {
5400 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5401 RTC_DCHECK(network_thread()->IsCurrent());
5402 // Note: Cannot use rtc::Bind here because it will grab a reference to
5403 // PeerConnection and potentially cause PeerConnection to live longer than
5404 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5405 // be destroyed before PeerConnection is destroyed, and at that point all
5406 // pending tasks will be cleared.
5407 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5408 OnSctpTransportReadyToSendData_s(true);
5409 });
5410}
5411
5412void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5413 RTC_DCHECK(signaling_thread()->IsCurrent());
5414 sctp_ready_to_send_data_ = ready;
5415 SignalSctpReadyToSendData(ready);
5416}
5417
5418void PeerConnection::OnSctpTransportDataReceived_n(
5419 const cricket::ReceiveDataParams& params,
5420 const rtc::CopyOnWriteBuffer& payload) {
5421 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5422 RTC_DCHECK(network_thread()->IsCurrent());
5423 // Note: Cannot use rtc::Bind here because it will grab a reference to
5424 // PeerConnection and potentially cause PeerConnection to live longer than
5425 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5426 // be destroyed before PeerConnection is destroyed, and at that point all
5427 // pending tasks will be cleared.
5428 sctp_invoker_->AsyncInvoke<void>(
5429 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5430 OnSctpTransportDataReceived_s(params, payload);
5431 });
5432}
5433
5434void PeerConnection::OnSctpTransportDataReceived_s(
5435 const cricket::ReceiveDataParams& params,
5436 const rtc::CopyOnWriteBuffer& payload) {
5437 RTC_DCHECK(signaling_thread()->IsCurrent());
5438 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5439 // Received OPEN message; parse and signal that a new data channel should
5440 // be created.
5441 std::string label;
5442 InternalDataChannelInit config;
5443 config.id = params.ssrc;
5444 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005445 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5446 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005447 return;
5448 }
5449 config.open_handshake_role = InternalDataChannelInit::kAcker;
5450 OnDataChannelOpenMessage(label, config);
5451 } else {
5452 // Otherwise just forward the signal.
5453 SignalSctpDataReceived(params, payload);
5454 }
5455}
5456
5457void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5458 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5459 RTC_DCHECK(network_thread()->IsCurrent());
5460 sctp_invoker_->AsyncInvoke<void>(
5461 RTC_FROM_HERE, signaling_thread(),
5462 rtc::Bind(&sigslot::signal1<int>::operator(),
5463 &SignalSctpStreamClosedRemotely, sid));
5464}
5465
5466// Returns false if bundle is enabled and rtcp_mux is disabled.
5467bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5468 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5469 if (!bundle_enabled)
5470 return true;
5471
5472 const cricket::ContentGroup* bundle_group =
5473 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5474 RTC_DCHECK(bundle_group != NULL);
5475
5476 const cricket::ContentInfos& contents = desc->contents();
5477 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5478 citer != contents.end(); ++citer) {
5479 const cricket::ContentInfo* content = (&*citer);
5480 RTC_DCHECK(content != NULL);
5481 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005482 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005483 if (!HasRtcpMuxEnabled(content))
5484 return false;
5485 }
5486 }
5487 // RTCP-MUX is enabled in all the contents.
5488 return true;
5489}
5490
5491bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005492 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005493}
5494
Steve Anton8a006912017-12-04 15:25:56 -08005495RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005496 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005497 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005498 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005499 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005500 }
5501
5502 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005503 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005504 }
5505
Steve Anton3828c062017-12-06 10:34:51 -08005506 SdpType type = sdesc->GetType();
5507 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5508 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005509 LOG_AND_RETURN_ERROR(
5510 RTCErrorType::INVALID_PARAMETER,
5511 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005512 }
5513
5514 // Verify crypto settings.
5515 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005516 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5517 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005518 RTCError crypto_error =
5519 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005520 if (!crypto_error.ok()) {
5521 return crypto_error;
5522 }
Steve Anton75737c02017-11-06 10:37:17 -08005523 }
5524
5525 // Verify ice-ufrag and ice-pwd.
5526 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005527 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5528 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005529 }
5530
5531 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5533 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005534 }
5535
5536 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5537 // m-lines that do not rtcp-mux enabled.
5538
5539 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005540 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005541 // With an answer we want to compare the new answer session description with
5542 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005543 const cricket::SessionDescription* offer_desc =
5544 (source == cricket::CS_LOCAL) ? remote_description()->description()
5545 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005546 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5547 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5548 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005549 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5550 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005551 }
5552 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005553 // The re-offers should respect the order of m= sections in current
5554 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005555 // With a re-offer, either the current local or current remote descriptions
5556 // could be the most up to date, so we would like to check against both of
5557 // them if they exist. It could be the case that one of them has a 0 port
5558 // for a media section, but the other does not. This is important to check
5559 // against in the case that we are recycling an m= section.
5560 const cricket::SessionDescription* current_desc = nullptr;
5561 const cricket::SessionDescription* secondary_current_desc = nullptr;
5562 if (local_description()) {
5563 current_desc = local_description()->description();
5564 if (remote_description()) {
5565 secondary_current_desc = remote_description()->description();
5566 }
5567 } else if (remote_description()) {
5568 current_desc = remote_description()->description();
5569 }
Steve Anton75737c02017-11-06 10:37:17 -08005570 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005571 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5572 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005573 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5574 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
5576 }
5577
Steve Anton8a006912017-12-04 15:25:56 -08005578 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005579}
5580
Steve Anton3828c062017-12-06 10:34:51 -08005581bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005582 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005583 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005584 return (state == PeerConnectionInterface::kStable) ||
5585 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005586 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005587 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005588 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5589 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5590 }
5591}
5592
Steve Anton3828c062017-12-06 10:34:51 -08005593bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005594 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005595 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005596 return (state == PeerConnectionInterface::kStable) ||
5597 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005598 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005599 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005600 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5601 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5602 }
5603}
5604
Steve Antonf8470812017-12-04 10:46:21 -08005605const char* PeerConnection::SessionErrorToString(SessionError error) const {
5606 switch (error) {
5607 case SessionError::kNone:
5608 return "ERROR_NONE";
5609 case SessionError::kContent:
5610 return "ERROR_CONTENT";
5611 case SessionError::kTransport:
5612 return "ERROR_TRANSPORT";
5613 }
5614 RTC_NOTREACHED();
5615 return "";
5616}
5617
Steve Anton75737c02017-11-06 10:37:17 -08005618std::string PeerConnection::GetSessionErrorMsg() {
5619 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005620 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5621 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005622 return desc.str();
5623}
5624
5625// We need to check the local/remote description for the Transport instead of
5626// the session, because a new Transport added during renegotiation may have
5627// them unset while the session has them set from the previous negotiation.
5628// Not doing so may trigger the auto generation of transport description and
5629// mess up DTLS identity information, ICE credential, etc.
5630bool PeerConnection::ReadyToUseRemoteCandidate(
5631 const IceCandidateInterface* candidate,
5632 const SessionDescriptionInterface* remote_desc,
5633 bool* valid) {
5634 *valid = true;
5635
5636 const SessionDescriptionInterface* current_remote_desc =
5637 remote_desc ? remote_desc : remote_description();
5638
5639 if (!current_remote_desc) {
5640 return false;
5641 }
5642
5643 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5644 size_t remote_content_size =
5645 current_remote_desc->description()->contents().size();
5646 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005647 RTC_LOG(LS_ERROR)
5648 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5649 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005650
5651 *valid = false;
5652 return false;
5653 }
5654
5655 cricket::ContentInfo content =
5656 current_remote_desc->description()->contents()[mediacontent_index];
5657
5658 const std::string transport_name = GetTransportName(content.name);
5659 if (transport_name.empty()) {
5660 return false;
5661 }
5662 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5663}
5664
5665bool PeerConnection::SrtpRequired() const {
5666 return dtls_enabled_ ||
5667 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5668}
5669
5670void PeerConnection::OnTransportControllerGatheringState(
5671 cricket::IceGatheringState state) {
5672 RTC_DCHECK(signaling_thread()->IsCurrent());
5673 if (state == cricket::kIceGatheringGathering) {
5674 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5675 } else if (state == cricket::kIceGatheringComplete) {
5676 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5677 }
5678}
5679
5680void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005681 std::map<std::string, std::set<cricket::MediaType>>
5682 media_types_by_transport_name;
5683 for (auto transceiver : transceivers_) {
5684 if (transceiver->internal()->channel()) {
5685 const std::string& transport_name =
5686 transceiver->internal()->channel()->transport_name();
5687 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005688 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005689 }
Steve Anton75737c02017-11-06 10:37:17 -08005690 }
5691 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005692 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5693 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005694 }
5695 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005696 media_types_by_transport_name[*sctp_transport_name_].insert(
5697 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005698 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005699 for (const auto& entry : media_types_by_transport_name) {
5700 const std::string& transport_name = entry.first;
5701 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005702 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005703 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005704 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005705 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005706 }
5707 }
5708}
5709// Walk through the ConnectionInfos to gather best connection usage
5710// for IPv4 and IPv6.
5711void PeerConnection::ReportBestConnectionState(
5712 const cricket::TransportStats& stats) {
5713 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005714 for (const cricket::TransportChannelStats& channel_stats :
5715 stats.channel_stats) {
5716 for (const cricket::ConnectionInfo& connection_info :
5717 channel_stats.connection_infos) {
5718 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005719 continue;
5720 }
5721
5722 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005723 const cricket::Candidate& local = connection_info.local_candidate;
5724 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005725
5726 // Increment the counter for IceCandidatePairType.
5727 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5728 (local.type() == RELAY_PORT_TYPE &&
5729 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5730 type = kEnumCounterIceCandidatePairTypeTcp;
5731 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5732 type = kEnumCounterIceCandidatePairTypeUdp;
5733 } else {
5734 RTC_CHECK(0);
5735 }
5736 metrics_observer()->IncrementEnumCounter(
5737 type, GetIceCandidatePairCounter(local, remote),
5738 kIceCandidatePairMax);
5739
5740 // Increment the counter for IP type.
5741 if (local.address().family() == AF_INET) {
5742 metrics_observer()->IncrementEnumCounter(
5743 kEnumCounterAddressFamily, kBestConnections_IPv4,
5744 kPeerConnectionAddressFamilyCounter_Max);
5745
5746 } else if (local.address().family() == AF_INET6) {
5747 metrics_observer()->IncrementEnumCounter(
5748 kEnumCounterAddressFamily, kBestConnections_IPv6,
5749 kPeerConnectionAddressFamilyCounter_Max);
5750 } else {
5751 RTC_CHECK(0);
5752 }
5753
5754 return;
5755 }
5756 }
5757}
5758
5759void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005760 const cricket::TransportStats& stats,
5761 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005762 RTC_DCHECK(metrics_observer());
5763 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5764 return;
5765 }
5766
5767 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5768 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5769 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5770 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5771 return;
5772 }
5773
Steve Antonc7b964c2018-02-01 14:39:45 -08005774 for (cricket::MediaType media_type : media_types) {
5775 PeerConnectionEnumCounterType srtp_counter_type;
5776 PeerConnectionEnumCounterType ssl_counter_type;
5777 switch (media_type) {
5778 case cricket::MEDIA_TYPE_AUDIO:
5779 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5780 ssl_counter_type = kEnumCounterAudioSslCipher;
5781 break;
5782 case cricket::MEDIA_TYPE_VIDEO:
5783 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5784 ssl_counter_type = kEnumCounterVideoSslCipher;
5785 break;
5786 case cricket::MEDIA_TYPE_DATA:
5787 srtp_counter_type = kEnumCounterDataSrtpCipher;
5788 ssl_counter_type = kEnumCounterDataSslCipher;
5789 break;
5790 default:
5791 RTC_NOTREACHED();
5792 continue;
5793 }
5794 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5795 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5796 srtp_crypto_suite);
5797 }
5798 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5799 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5800 ssl_cipher_suite);
5801 }
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803}
5804
5805void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5806 RTC_DCHECK(worker_thread()->IsCurrent());
5807 RTC_DCHECK(call_);
5808 call_->OnSentPacket(sent_packet);
5809}
5810
5811const std::string PeerConnection::GetTransportName(
5812 const std::string& content_name) {
5813 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005814 if (channel) {
5815 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005816 }
Steve Anton6fec8802017-12-04 10:37:29 -08005817 if (sctp_transport_) {
5818 RTC_DCHECK(sctp_content_name_);
5819 RTC_DCHECK(sctp_transport_name_);
5820 if (content_name == *sctp_content_name_) {
5821 return *sctp_transport_name_;
5822 }
5823 }
5824 // Return an empty string if failed to retrieve the transport name.
5825 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005826}
5827
5828void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5829 RTC_DCHECK(network_thread()->IsCurrent());
5830 transport_controller_->DestroyDtlsTransport_n(
5831 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5832}
5833
Steve Anton6fec8802017-12-04 10:37:29 -08005834void PeerConnection::DestroyTransceiverChannel(
5835 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5836 transceiver) {
5837 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005838
Steve Anton6fec8802017-12-04 10:37:29 -08005839 cricket::BaseChannel* channel = transceiver->internal()->channel();
5840 if (channel) {
5841 transceiver->internal()->SetChannel(nullptr);
5842 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005843 }
5844}
5845
5846void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005847 if (rtp_data_channel_) {
5848 OnDataChannelDestroyed();
5849 DestroyBaseChannel(rtp_data_channel_);
5850 rtp_data_channel_ = nullptr;
5851 }
5852
5853 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5854 // grab a reference to this PeerConnection. If this is called from the
5855 // PeerConnection destructor, the RefCountedObject vtable will have already
5856 // been destroyed (since it is a subclass of PeerConnection) and using
5857 // rtc::Bind will cause "Pure virtual function called" error to appear.
5858
5859 if (sctp_transport_) {
5860 OnDataChannelDestroyed();
5861 network_thread()->Invoke<void>(RTC_FROM_HERE,
5862 [this] { DestroySctpTransport_n(); });
5863 }
5864}
5865
5866void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5867 RTC_DCHECK(channel);
5868 RTC_DCHECK(channel->rtp_dtls_transport());
5869
5870 // Need to cache these before destroying the base channel so that we do not
5871 // access uninitialized memory.
5872 const std::string transport_name =
5873 channel->rtp_dtls_transport()->transport_name();
5874 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5875
5876 switch (channel->media_type()) {
5877 case cricket::MEDIA_TYPE_AUDIO:
5878 channel_manager()->DestroyVoiceChannel(
5879 static_cast<cricket::VoiceChannel*>(channel));
5880 break;
5881 case cricket::MEDIA_TYPE_VIDEO:
5882 channel_manager()->DestroyVideoChannel(
5883 static_cast<cricket::VideoChannel*>(channel));
5884 break;
5885 case cricket::MEDIA_TYPE_DATA:
5886 channel_manager()->DestroyRtpDataChannel(
5887 static_cast<cricket::RtpDataChannel*>(channel));
5888 break;
5889 default:
5890 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5891 break;
5892 }
5893
5894 // |channel| can no longer be used.
5895
Steve Anton75737c02017-11-06 10:37:17 -08005896 transport_controller_->DestroyDtlsTransport(
5897 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5898 if (need_to_delete_rtcp) {
5899 transport_controller_->DestroyDtlsTransport(
5900 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5901 }
5902}
5903
Harald Alvestrand89061872018-01-02 14:08:34 +01005904void PeerConnection::ClearStatsCache() {
5905 if (stats_collector_) {
5906 stats_collector_->ClearCachedStatsReport();
5907 }
5908}
5909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005910} // namespace webrtc