blob: b99df990144adbfe0426ce8274b31033b7431956 [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"
Elad Alon83ccca12017-10-04 13:18:26 +020025#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "logging/rtc_event_log/rtc_event_log.h"
27#include "media/sctp/sctptransport.h"
28#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080029#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "pc/channelmanager.h"
31#include "pc/dtmfsender.h"
32#include "pc/mediastream.h"
33#include "pc/mediastreamobserver.h"
34#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080035#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "pc/rtpreceiver.h"
37#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080039#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/streamcollection.h"
41#include "pc/videocapturertracksource.h"
42#include "pc/videotrack.h"
43#include "rtc_base/bind.h"
44#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010046#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020047#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/stringencode.h"
49#include "rtc_base/stringutils.h"
50#include "rtc_base/trace_event.h"
51#include "system_wrappers/include/clock.h"
52#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
Steve Anton75737c02017-11-06 10:37:17 -080054using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080058using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::TransportInfo;
60
61using cricket::LOCAL_PORT_TYPE;
62using cricket::STUN_PORT_TYPE;
63using cricket::RELAY_PORT_TYPE;
64using cricket::PRFLX_PORT_TYPE;
65
Steve Antonba818672017-11-06 10:21:57 -080066namespace webrtc {
67
Steve Anton75737c02017-11-06 10:37:17 -080068// Error messages
69const char kBundleWithoutRtcpMux[] =
70 "rtcp-mux must be enabled when BUNDLE "
71 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080072const char kInvalidCandidates[] = "Description contains invalid candidates.";
73const char kInvalidSdp[] = "Invalid session description.";
74const char kMlineMismatchInAnswer[] =
75 "The order of m-lines in answer doesn't match order in offer. Rejecting "
76 "answer.";
77const char kMlineMismatchInSubsequentOffer[] =
78 "The order of m-lines in subsequent offer doesn't match order from "
79 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080080const char kSdpWithoutDtlsFingerprint[] =
81 "Called with SDP without DTLS fingerprint.";
82const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
83const char kSdpWithoutIceUfragPwd[] =
84 "Called with SDP without ice-ufrag and ice-pwd.";
85const char kSessionError[] = "Session error code: ";
86const char kSessionErrorDesc[] = "Session error description: ";
87const char kDtlsSrtpSetupFailureRtp[] =
88 "Couldn't set up DTLS-SRTP on RTP channel.";
89const char kDtlsSrtpSetupFailureRtcp[] =
90 "Couldn't set up DTLS-SRTP on RTCP channel.";
91const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
Steve Anton75737c02017-11-06 10:37:17 -080093namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
deadbeefab9b2d12015-10-14 11:33:11 -070095static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080096static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070098
zhihuang8f65cdf2016-05-06 18:40:30 -070099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
deadbeefab9b2d12015-10-14 11:33:11 -0700138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
144 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
146 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 12:49:08 -0700152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 11:33:11 -0700162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 14:10:50 -0700168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700187 }
zhihuang1c378ed2017-08-17 14:10:50 -0700188}
olka3c747662017-08-17 06:50:32 -0700189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 11:33:11 -0700198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 05:56:46 -0800223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 12:28:30 -0800228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 15:59:59 -0700236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 10:21:57 -0800243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262
Steve Anton75737c02017-11-06 10:37:17 -0800263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
320// Verify that the order of media sections in |new_desc| matches
321// |existing_desc|. The number of m= sections in |new_desc| should be no less
322// than |existing_desc|.
323bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
324 const SessionDescription* new_desc) {
325 if (!existing_desc || !new_desc) {
326 return false;
327 }
328
329 if (existing_desc->contents().size() > new_desc->contents().size()) {
330 return false;
331 }
332
333 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-22 16:02:54 -0800334 if (existing_desc->contents()[i].rejected) {
335 // If the media section can be recycled, it's valid for the MID and media
336 // type to change.
337 continue;
338 }
Steve Anton75737c02017-11-06 10:37:17 -0800339 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
340 return false;
341 }
342 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800343 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800344 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800345 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800367RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 const cricket::ContentGroup* bundle =
369 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800370 for (const cricket::ContentInfo& content_info : desc->contents()) {
371 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 continue;
373 }
Steve Anton8a006912017-12-04 15:25:56 -0800374 const std::string& mid = content_info.name;
375 if (bundle && bundle->HasContentName(mid) &&
376 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800377 // This isn't the first media section in the BUNDLE group, so it's not
378 // required to have crypto attributes, since only the crypto attributes
379 // from the first section actually get used.
380 continue;
381 }
382
383 // If the content isn't rejected or bundled into another m= section, crypto
384 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800385 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800386 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800387 if (!media || !tinfo) {
388 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800390 }
391 if (dtls_enabled) {
392 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG(LS_WARNING)
394 << "Session description must have DTLS fingerprint if "
395 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800396 return RTCError(RTCErrorType::INVALID_PARAMETER,
397 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800398 }
399 } else {
400 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100401 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800402 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800404 }
405 }
406 }
Steve Anton8a006912017-12-04 15:25:56 -0800407 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800408}
409
410// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
411// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
412// media section/description in the BUNDLE group) needs a ufrag and pwd.
413bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
414 const cricket::ContentGroup* bundle =
415 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800416 for (const cricket::ContentInfo& content_info : desc->contents()) {
417 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 continue;
419 }
Steve Anton8a006912017-12-04 15:25:56 -0800420 const std::string& mid = content_info.name;
421 if (bundle && bundle->HasContentName(mid) &&
422 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800423 // This isn't the first media section in the BUNDLE group, so it's not
424 // required to have ufrag/password, since only the ufrag/password from
425 // the first section actually get used.
426 continue;
427 }
428
429 // If the content isn't rejected or bundled into another m= section,
430 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800431 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800432 if (!tinfo) {
433 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800435 return false;
436 }
437 if (tinfo->description.ice_ufrag.empty() ||
438 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800440 return false;
441 }
442 }
443 return true;
444}
445
446bool GetTrackIdBySsrc(const SessionDescription* session_description,
447 uint32_t ssrc,
448 std::string* track_id) {
449 RTC_DCHECK(track_id != NULL);
450
Steve Antonb1c1de12017-12-21 15:14:30 -0800451 const cricket::AudioContentDescription* audio_desc =
452 cricket::GetFirstAudioContentDescription(session_description);
453 if (audio_desc) {
454 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
Steve Antonb1c1de12017-12-21 15:14:30 -0800461 const cricket::VideoContentDescription* video_desc =
462 cricket::GetFirstVideoContentDescription(session_description);
463 if (video_desc) {
464 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470 return false;
471}
472
473// Get the SCTP port out of a SessionDescription.
474// Return -1 if not found.
475int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const cricket::DataContentDescription* data_desc =
477 GetFirstDataContentDescription(session_description);
478 RTC_DCHECK(data_desc);
479 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 return -1;
481 }
Steve Anton75737c02017-11-06 10:37:17 -0800482 std::string value;
483 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
484 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800485 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!codec.Matches(match_pattern)) {
487 continue;
488 }
489 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
490 return rtc::FromString<int>(value);
491 }
492 }
493 return -1;
494}
495
Steve Anton75737c02017-11-06 10:37:17 -0800496// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
497bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
498 const SessionDescriptionInterface* new_desc,
499 const std::string& content_name) {
500 if (!old_desc) {
501 return false;
502 }
503 const SessionDescription* new_sd = new_desc->description();
504 const SessionDescription* old_sd = old_desc->description();
505 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
506 if (!cinfo || cinfo->rejected) {
507 return false;
508 }
509 // If the content isn't rejected, check if ufrag and password has changed.
510 const cricket::TransportDescription* new_transport_desc =
511 new_sd->GetTransportDescriptionByName(content_name);
512 const cricket::TransportDescription* old_transport_desc =
513 old_sd->GetTransportDescriptionByName(content_name);
514 if (!new_transport_desc || !old_transport_desc) {
515 // No transport description exists. This is not an ICE restart.
516 return false;
517 }
518 if (cricket::IceCredentialsChanged(
519 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
520 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100521 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
522 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800523 return true;
524 }
525 return false;
526}
527
528} // namespace
529
Henrik Boström31638672017-11-23 17:48:32 +0100530// Upon completion, posts a task to execute the callback of the
531// SetSessionDescriptionObserver asynchronously on the same thread. At this
532// point, the state of the peer connection might no longer reflect the effects
533// of the SetRemoteDescription operation, as the peer connection could have been
534// modified during the post.
535// TODO(hbos): Remove this class once we remove the version of
536// PeerConnectionInterface::SetRemoteDescription() that takes a
537// SetSessionDescriptionObserver as an argument.
538class PeerConnection::SetRemoteDescriptionObserverAdapter
539 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
540 public:
541 SetRemoteDescriptionObserverAdapter(
542 rtc::scoped_refptr<PeerConnection> pc,
543 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
544 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
545
546 // SetRemoteDescriptionObserverInterface implementation.
547 void OnSetRemoteDescriptionComplete(RTCError error) override {
548 if (error.ok())
549 pc_->PostSetSessionDescriptionSuccess(wrapper_);
550 else
551 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
552 }
553
554 private:
555 rtc::scoped_refptr<PeerConnection> pc_;
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
557};
558
deadbeef293e9262017-01-11 12:28:30 -0800559bool PeerConnectionInterface::RTCConfiguration::operator==(
560 const PeerConnectionInterface::RTCConfiguration& o) const {
561 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700562 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800563 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000564 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700565 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800566 BundlePolicy bundle_policy;
567 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700568 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
569 int ice_candidate_pool_size;
570 bool disable_ipv6;
571 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700572 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 bool enable_rtp_data_channel;
574 rtc::Optional<int> screencast_min_bitrate;
575 rtc::Optional<bool> combined_audio_video_bwe;
576 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800577 TcpCandidatePolicy tcp_candidate_policy;
578 CandidateNetworkPolicy candidate_network_policy;
579 int audio_jitter_buffer_max_packets;
580 bool audio_jitter_buffer_fast_accelerate;
581 int ice_connection_receiving_timeout;
582 int ice_backup_candidate_pair_ping_interval;
583 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800584 bool prioritize_most_likely_ice_candidate_pairs;
585 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800586 bool prune_turn_ports;
587 bool presume_writable_when_fully_relayed;
588 bool enable_ice_renomination;
589 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800590 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700591 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200592 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800593 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800594 };
595 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
596 "Did you add something to RTCConfiguration and forget to "
597 "update operator==?");
598 return type == o.type && servers == o.servers &&
599 bundle_policy == o.bundle_policy &&
600 rtcp_mux_policy == o.rtcp_mux_policy &&
601 tcp_candidate_policy == o.tcp_candidate_policy &&
602 candidate_network_policy == o.candidate_network_policy &&
603 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
604 audio_jitter_buffer_fast_accelerate ==
605 o.audio_jitter_buffer_fast_accelerate &&
606 ice_connection_receiving_timeout ==
607 o.ice_connection_receiving_timeout &&
608 ice_backup_candidate_pair_ping_interval ==
609 o.ice_backup_candidate_pair_ping_interval &&
610 continual_gathering_policy == o.continual_gathering_policy &&
611 certificates == o.certificates &&
612 prioritize_most_likely_ice_candidate_pairs ==
613 o.prioritize_most_likely_ice_candidate_pairs &&
614 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800615 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700616 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800617 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800618 screencast_min_bitrate == o.screencast_min_bitrate &&
619 combined_audio_video_bwe == o.combined_audio_video_bwe &&
620 enable_dtls_srtp == o.enable_dtls_srtp &&
621 ice_candidate_pool_size == o.ice_candidate_pool_size &&
622 prune_turn_ports == o.prune_turn_ports &&
623 presume_writable_when_fully_relayed ==
624 o.presume_writable_when_fully_relayed &&
625 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800626 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700627 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200628 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800629 turn_customizer == o.turn_customizer &&
630 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800631}
632
633bool PeerConnectionInterface::RTCConfiguration::operator!=(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800636}
637
zhihuang8f65cdf2016-05-06 18:40:30 -0700638// Generate a RTCP CNAME when a PeerConnection is created.
639std::string GenerateRtcpCname() {
640 std::string cname;
641 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100642 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800643 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700644 }
645 return cname;
646}
647
zhihuang1c378ed2017-08-17 14:10:50 -0700648bool ValidateOfferAnswerOptions(
649 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
650 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
651 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700652}
653
zhihuang1c378ed2017-08-17 14:10:50 -0700654// From |rtc_options|, fill parts of |session_options| shared by all generated
655// m= sections (in other words, nothing that involves a map/array).
656void ExtractSharedMediaSessionOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
658 cricket::MediaSessionOptions* session_options) {
659 session_options->vad_enabled = rtc_options.voice_activity_detection;
660 session_options->bundle_enabled = rtc_options.use_rtp_mux;
661}
zhihuanga77e6bb2017-08-14 18:17:48 -0700662
zhihuang1c378ed2017-08-17 14:10:50 -0700663bool ConvertConstraintsToOfferAnswerOptions(
664 const MediaConstraintsInterface* constraints,
665 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700666 if (!constraints) {
667 return true;
668 }
zhihuang1c378ed2017-08-17 14:10:50 -0700669
670 bool value = false;
671 size_t mandatory_constraints_satisfied = 0;
672
673 if (FindConstraint(constraints,
674 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
675 &mandatory_constraints_satisfied)) {
676 offer_answer_options->offer_to_receive_audio =
677 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
678 kOfferToReceiveMediaTrue
679 : 0;
680 }
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_video =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kVoiceActivityDetection, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->voice_activity_detection = value;
694 }
695 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->use_rtp_mux = value;
698 }
699 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
700 &value, &mandatory_constraints_satisfied)) {
701 offer_answer_options->ice_restart = value;
702 }
703
deadbeefab9b2d12015-10-14 11:33:11 -0700704 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
705}
706
zhihuang38ede132017-06-15 12:52:32 -0700707PeerConnection::PeerConnection(PeerConnectionFactory* factory,
708 std::unique_ptr<RtcEventLog> event_log,
709 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700711 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700712 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700713 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700714 remote_streams_(StreamCollection::Create()),
715 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716
717PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100718 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800719 RTC_DCHECK_RUN_ON(signaling_thread());
720
Steve Anton8af21862017-12-15 11:20:13 -0800721 // Need to stop transceivers before destroying the stats collector because
722 // AudioRtpSender has a reference to the StatsCollector it will update when
723 // stopping.
724 for (auto transceiver : transceivers_) {
725 transceiver->Stop();
726 }
Steve Anton4171afb2017-11-20 10:20:22 -0800727
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700728 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800729 if (stats_collector_) {
730 stats_collector_->WaitForPendingRequest();
731 stats_collector_ = nullptr;
732 }
Steve Anton75737c02017-11-06 10:37:17 -0800733
Steve Anton8af21862017-12-15 11:20:13 -0800734 // Don't destroy BaseChannels until after stats has been cleaned up so that
735 // the last stats request can still read from the channels.
736 DestroyAllChannels();
737
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800739
740 webrtc_session_desc_factory_.reset();
741 sctp_invoker_.reset();
742 sctp_factory_.reset();
743 transport_controller_.reset();
744
deadbeef91dd5672016-05-18 16:55:30 -0700745 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700746 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700747 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700748 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700749 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700750 call_.reset();
751 event_log_.reset();
752 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753}
754
Steve Anton8af21862017-12-15 11:20:13 -0800755void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800756 // Destroy video channels first since they may have a pointer to a voice
757 // channel.
758 for (auto transceiver : transceivers_) {
759 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
760 DestroyTransceiverChannel(transceiver);
761 }
762 }
763 for (auto transceiver : transceivers_) {
764 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
765 DestroyTransceiverChannel(transceiver);
766 }
767 }
768 DestroyDataChannel();
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000772 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700773 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200774 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800775 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100776 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700777
778 RTCError config_error = ValidateConfiguration(configuration);
779 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700781 return false;
782 }
783
deadbeef293e9262017-01-11 12:28:30 -0800784 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100785 RTC_LOG(LS_ERROR)
786 << "PeerConnection initialized without a PortAllocator? "
787 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800788 return false;
789 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200790
deadbeef653b8e02015-11-11 12:55:10 -0800791 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800792 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
794 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800795 return false;
796 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000797 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800798 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800799
deadbeef91dd5672016-05-18 16:55:30 -0700800 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700801 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700802 if (!network_thread()->Invoke<bool>(
803 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
804 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 return false;
806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807
Steve Anton75737c02017-11-06 10:37:17 -0800808 // RFC 3264: The numeric value of the session id and version in the
809 // o line MUST be representable with a "64 bit signed integer".
810 // Due to this constraint session id |session_id_| is max limited to
811 // LLONG_MAX.
812 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
813 transport_controller_.reset(factory_->CreateTransportController(
814 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
815 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
816 transport_controller_->SignalConnectionState.connect(
817 this, &PeerConnection::OnTransportControllerConnectionState);
818 transport_controller_->SignalGatheringState.connect(
819 this, &PeerConnection::OnTransportControllerGatheringState);
820 transport_controller_->SignalCandidatesGathered.connect(
821 this, &PeerConnection::OnTransportControllerCandidatesGathered);
822 transport_controller_->SignalCandidatesRemoved.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
824 transport_controller_->SignalDtlsHandshakeError.connect(
825 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
826
827 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700828
deadbeefab9b2d12015-10-14 11:33:11 -0700829 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700830 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
Steve Antonba818672017-11-06 10:21:57 -0800832 configuration_ = configuration;
833
Steve Anton75737c02017-11-06 10:37:17 -0800834 const PeerConnectionFactoryInterface::Options& options = factory_->options();
835
836 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
837
838 // Obtain a certificate from RTCConfiguration if any were provided (optional).
839 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
840 if (!configuration.certificates.empty()) {
841 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
842 // just picking the first one. The decision should be made based on the DTLS
843 // handshake. The DTLS negotiations need to know about all certificates.
844 certificate = configuration.certificates[0];
845 }
846
Steve Antond25da372017-11-06 14:50:29 -0800847 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800848
849 if (options.disable_encryption) {
850 dtls_enabled_ = false;
851 } else {
852 // Enable DTLS by default if we have an identity store or a certificate.
853 dtls_enabled_ = (cert_generator || certificate);
854 // |configuration| can override the default |dtls_enabled_| value.
855 if (configuration.enable_dtls_srtp) {
856 dtls_enabled_ = *(configuration.enable_dtls_srtp);
857 }
858 }
859
860 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
861 // It takes precendence over the disable_sctp_data_channels
862 // PeerConnectionFactoryInterface::Options.
863 if (configuration.enable_rtp_data_channel) {
864 data_channel_type_ = cricket::DCT_RTP;
865 } else {
866 // DTLS has to be enabled to use SCTP.
867 if (!options.disable_sctp_data_channels && dtls_enabled_) {
868 data_channel_type_ = cricket::DCT_SCTP;
869 }
870 }
871
872 video_options_.screencast_min_bitrate_kbps =
873 configuration.screencast_min_bitrate;
874 audio_options_.combined_audio_video_bwe =
875 configuration.combined_audio_video_bwe;
876
877 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100878 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800879
880 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100881 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800882
883 // Whether the certificate generator/certificate is null or not determines
884 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
885 // the right instructions by clearing the variables if needed.
886 if (!dtls_enabled_) {
887 cert_generator.reset();
888 certificate = nullptr;
889 } else if (certificate) {
890 // Favor generated certificate over the certificate generator.
891 cert_generator.reset();
892 }
893
894 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
895 signaling_thread(), channel_manager(), this, session_id(),
896 std::move(cert_generator), certificate));
897 webrtc_session_desc_factory_->SignalCertificateReady.connect(
898 this, &PeerConnection::OnCertificateReady);
899
900 if (options.disable_encryption) {
901 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
902 }
903
904 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
905 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
Steve Anton4171afb2017-11-20 10:20:22 -0800907 // Add default audio/video transceivers for Plan B SDP.
908 if (!IsUnifiedPlan()) {
909 transceivers_.push_back(
910 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
911 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
912 transceivers_.push_back(
913 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
914 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
915 }
916
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return true;
918}
919
Steve Anton038834f2017-07-14 15:59:59 -0700920RTCError PeerConnection::ValidateConfiguration(
921 const RTCConfiguration& config) const {
922 if (config.ice_regather_interval_range &&
923 config.continual_gathering_policy == GATHER_ONCE) {
924 return RTCError(RTCErrorType::INVALID_PARAMETER,
925 "ice_regather_interval_range specified but continual "
926 "gathering policy is GATHER_ONCE");
927 }
928 return RTCError::OK();
929}
930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000931rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700933 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000936rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700938 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939}
940
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000941bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100942 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 if (IsClosed()) {
944 return false;
945 }
deadbeefab9b2d12015-10-14 11:33:11 -0700946 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 return false;
948 }
deadbeefab9b2d12015-10-14 11:33:11 -0700949
950 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800951 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
952 observer->SignalAudioTrackAdded.connect(this,
953 &PeerConnection::OnAudioTrackAdded);
954 observer->SignalAudioTrackRemoved.connect(
955 this, &PeerConnection::OnAudioTrackRemoved);
956 observer->SignalVideoTrackAdded.connect(this,
957 &PeerConnection::OnVideoTrackAdded);
958 observer->SignalVideoTrackRemoved.connect(
959 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700960 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700961
deadbeefab9b2d12015-10-14 11:33:11 -0700962 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700963 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700964 }
965 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700966 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700967 }
968
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000969 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 observer_->OnRenegotiationNeeded();
971 return true;
972}
973
974void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100975 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700976 if (!IsClosed()) {
977 for (const auto& track : local_stream->GetAudioTracks()) {
978 RemoveAudioTrack(track.get(), local_stream);
979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
981 RemoveVideoTrack(track.get(), local_stream);
982 }
deadbeefab9b2d12015-10-14 11:33:11 -0700983 }
deadbeefab9b2d12015-10-14 11:33:11 -0700984 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800985 stream_observers_.erase(
986 std::remove_if(
987 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700988 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800989 return observer->stream()->label().compare(local_stream->label()) ==
990 0;
991 }),
992 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 if (IsClosed()) {
995 return;
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 observer_->OnRenegotiationNeeded();
998}
999
deadbeefe1f9d832016-01-14 15:35:42 -08001000rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1001 MediaStreamTrackInterface* track,
1002 std::vector<MediaStreamInterface*> streams) {
1003 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001004 std::vector<std::string> stream_labels;
1005 for (auto* stream : streams) {
1006 if (!stream) {
1007 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1008 return nullptr;
1009 }
1010 stream_labels.push_back(stream->label());
1011 }
1012 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1013 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001014 return nullptr;
1015 }
Steve Antonf9381f02017-12-14 10:23:57 -08001016 return sender_or_error.MoveValue();
1017}
1018
1019RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1020PeerConnection::AddTrackWithStreamLabels(
1021 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1022 const std::vector<std::string>& stream_labels) {
1023 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1024 if (!track) {
1025 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1026 }
1027 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1028 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1030 "Track has invalid kind: " + track->kind());
1031 }
1032 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1033 if (stream_labels.size() > 1u) {
1034 LOG_AND_RETURN_ERROR(
1035 RTCErrorType::UNSUPPORTED_OPERATION,
1036 "AddTrack with more than one stream is not currently supported.");
1037 }
1038 if (IsClosed()) {
1039 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1040 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001041 }
Steve Anton4171afb2017-11-20 10:20:22 -08001042 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001043 LOG_AND_RETURN_ERROR(
1044 RTCErrorType::INVALID_PARAMETER,
1045 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001046 }
Steve Antonf9381f02017-12-14 10:23:57 -08001047 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1048 // one stream. AddTrackInternal will return an error if there is more than one
1049 // stream, but if the caller specifies none then we need to generate a random
1050 // stream label.
1051 std::vector<std::string> adjusted_stream_labels = stream_labels;
1052 if (stream_labels.empty()) {
1053 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1054 }
1055 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1056 auto sender_or_error =
1057 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1058 : AddTrackPlanB(track, adjusted_stream_labels));
1059 if (sender_or_error.ok()) {
1060 observer_->OnRenegotiationNeeded();
1061 }
1062 return sender_or_error;
1063}
deadbeefe1f9d832016-01-14 15:35:42 -08001064
Steve Antonf9381f02017-12-14 10:23:57 -08001065RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1066PeerConnection::AddTrackPlanB(
1067 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1068 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001069 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001070 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001071 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001072 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001073 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001074 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001075 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001076 const RtpSenderInfo* sender_info =
1077 FindSenderInfo(local_audio_sender_infos_,
1078 new_sender->internal()->stream_id(), track->id());
1079 if (sender_info) {
1080 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001081 }
Steve Antonf9381f02017-12-14 10:23:57 -08001082 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
1083 } else {
1084 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1085 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001086 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001087 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001088 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001089 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001090 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001091 const RtpSenderInfo* sender_info =
1092 FindSenderInfo(local_video_sender_infos_,
1093 new_sender->internal()->stream_id(), track->id());
1094 if (sender_info) {
1095 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001096 }
Steve Antonf9381f02017-12-14 10:23:57 -08001097 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001098 }
Steve Antonf9381f02017-12-14 10:23:57 -08001099}
deadbeefe1f9d832016-01-14 15:35:42 -08001100
Steve Antonf9381f02017-12-14 10:23:57 -08001101RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1102PeerConnection::AddTrackUnifiedPlan(
1103 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1104 const std::vector<std::string>& stream_labels) {
1105 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1106 if (transceiver) {
1107 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1108 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1109 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1110 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1111 }
1112 } else {
1113 cricket::MediaType media_type =
1114 (track->kind() == MediaStreamTrackInterface::kAudioKind
1115 ? cricket::MEDIA_TYPE_AUDIO
1116 : cricket::MEDIA_TYPE_VIDEO);
1117 transceiver = CreateTransceiver(media_type);
1118 transceiver->internal()->set_created_by_addtrack(true);
1119 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1120 }
1121 transceiver->sender()->SetTrack(track);
1122 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1123 return transceiver->sender();
1124}
1125
1126rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1127PeerConnection::FindFirstTransceiverForAddedTrack(
1128 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1129 RTC_DCHECK(track);
1130 for (auto transceiver : transceivers_) {
1131 if (!transceiver->sender()->track() &&
1132 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1133 track->kind() &&
1134 !transceiver->internal()->has_ever_been_used_to_send()) {
1135 return transceiver;
1136 }
1137 }
1138 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001139}
1140
1141bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1142 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001143 return RemoveTrackInternal(sender).ok();
1144}
1145
1146RTCError PeerConnection::RemoveTrackInternal(
1147 rtc::scoped_refptr<RtpSenderInterface> sender) {
1148 if (!sender) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1150 }
deadbeefe1f9d832016-01-14 15:35:42 -08001151 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1153 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
Steve Antonf9381f02017-12-14 10:23:57 -08001155 if (IsUnifiedPlan()) {
1156 auto transceiver = FindTransceiverBySender(sender);
1157 if (!transceiver || !sender->track()) {
1158 return RTCError::OK();
1159 }
1160 sender->SetTrack(nullptr);
1161 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1162 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1163 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1164 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001167 bool removed;
1168 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1169 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1170 } else {
1171 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1172 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1173 }
1174 if (!removed) {
1175 LOG_AND_RETURN_ERROR(
1176 RTCErrorType::INVALID_PARAMETER,
1177 "Couldn't find sender " + sender->id() + " to remove.");
1178 }
Steve Anton4171afb2017-11-20 10:20:22 -08001179 }
deadbeefe1f9d832016-01-14 15:35:42 -08001180 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001181 return RTCError::OK();
1182}
1183
1184rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1185PeerConnection::FindTransceiverBySender(
1186 rtc::scoped_refptr<RtpSenderInterface> sender) {
1187 for (auto transceiver : transceivers_) {
1188 if (transceiver->sender() == sender) {
1189 return transceiver;
1190 }
1191 }
1192 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001193}
1194
Steve Anton9158ef62017-11-27 13:01:52 -08001195RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1196PeerConnection::AddTransceiver(
1197 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1198 return AddTransceiver(track, RtpTransceiverInit());
1199}
1200
1201RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1202PeerConnection::AddTransceiver(
1203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1204 const RtpTransceiverInit& init) {
1205 if (!IsUnifiedPlan()) {
1206 LOG_AND_RETURN_ERROR(
1207 RTCErrorType::INTERNAL_ERROR,
1208 "AddTransceiver only supported when Unified Plan is enabled.");
1209 }
1210 if (!track) {
1211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1212 }
1213 cricket::MediaType media_type;
1214 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1215 media_type = cricket::MEDIA_TYPE_AUDIO;
1216 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1217 media_type = cricket::MEDIA_TYPE_VIDEO;
1218 } else {
1219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1220 "Track kind is not audio or video");
1221 }
1222 return AddTransceiver(media_type, track, init);
1223}
1224
1225RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1226PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1227 return AddTransceiver(media_type, RtpTransceiverInit());
1228}
1229
1230RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1231PeerConnection::AddTransceiver(cricket::MediaType media_type,
1232 const RtpTransceiverInit& init) {
1233 if (!IsUnifiedPlan()) {
1234 LOG_AND_RETURN_ERROR(
1235 RTCErrorType::INTERNAL_ERROR,
1236 "AddTransceiver only supported when Unified Plan is enabled.");
1237 }
1238 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1239 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1241 "media type is not audio or video");
1242 }
1243 return AddTransceiver(media_type, nullptr, init);
1244}
1245
1246RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1247PeerConnection::AddTransceiver(
1248 cricket::MediaType media_type,
1249 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1250 const RtpTransceiverInit& init) {
1251 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1252 media_type == cricket::MEDIA_TYPE_VIDEO));
1253 if (track) {
1254 RTC_DCHECK_EQ(media_type,
1255 (track->kind() == MediaStreamTrackInterface::kAudioKind
1256 ? cricket::MEDIA_TYPE_AUDIO
1257 : cricket::MEDIA_TYPE_VIDEO));
1258 }
1259
1260 // TODO(bugs.webrtc.org/7600): Verify init.
1261
Steve Antonf9381f02017-12-14 10:23:57 -08001262 auto transceiver = CreateTransceiver(media_type);
1263 transceiver->SetDirection(init.direction);
1264 if (track) {
1265 transceiver->sender()->SetTrack(track);
1266 }
1267
1268 observer_->OnRenegotiationNeeded();
1269
1270 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1271}
1272
1273rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1274PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001275 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1276 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1277 receiver;
1278 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001279 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1280 // channel prevents users from calling SetParameters on them, which is needed
1281 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001282 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1283 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1284 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1285 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1286 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1287 } else {
1288 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1289 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1290 signaling_thread(), new VideoRtpSender(nullptr));
1291 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1292 signaling_thread(),
1293 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1294 }
Steve Anton9158ef62017-11-27 13:01:52 -08001295 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1296 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1297 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001298 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001299 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001300}
1301
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001302rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001304 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001305 if (IsClosed()) {
1306 return nullptr;
1307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001309 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001310 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 }
Steve Anton4171afb2017-11-20 10:20:22 -08001312 auto track_sender = FindSenderForTrack(track);
1313 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001314 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001315 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 }
1317
Steve Anton4171afb2017-11-20 10:20:22 -08001318 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319}
1320
deadbeeffac06552015-11-25 11:26:01 -08001321rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001322 const std::string& kind,
1323 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001324 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001325 if (IsClosed()) {
1326 return nullptr;
1327 }
Steve Anton4171afb2017-11-20 10:20:22 -08001328
1329 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001330 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001331 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001332 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001333 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001334 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001335 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001336 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001337 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001338 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001339 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001340 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001341 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001342 }
Steve Anton4171afb2017-11-20 10:20:22 -08001343
deadbeefbd7d8f72015-12-18 16:58:44 -08001344 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001345 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001346 }
Steve Anton4171afb2017-11-20 10:20:22 -08001347
deadbeefe1f9d832016-01-14 15:35:42 -08001348 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001349}
1350
deadbeef70ab1a12015-09-28 16:53:55 -07001351std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1352 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001353 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001354 for (auto sender : GetSendersInternal()) {
1355 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001356 }
1357 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001358}
1359
Steve Anton4171afb2017-11-20 10:20:22 -08001360std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1361PeerConnection::GetSendersInternal() const {
1362 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1363 all_senders;
1364 for (auto transceiver : transceivers_) {
1365 auto senders = transceiver->internal()->senders();
1366 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1367 }
1368 return all_senders;
1369}
1370
deadbeef70ab1a12015-09-28 16:53:55 -07001371std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1372PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001373 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001374 for (const auto& receiver : GetReceiversInternal()) {
1375 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001376 }
1377 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001378}
1379
Steve Anton4171afb2017-11-20 10:20:22 -08001380std::vector<
1381 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1382PeerConnection::GetReceiversInternal() const {
1383 std::vector<
1384 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1385 all_receivers;
1386 for (auto transceiver : transceivers_) {
1387 auto receivers = transceiver->internal()->receivers();
1388 all_receivers.insert(all_receivers.end(), receivers.begin(),
1389 receivers.end());
1390 }
1391 return all_receivers;
1392}
1393
Steve Anton9158ef62017-11-27 13:01:52 -08001394std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1395PeerConnection::GetTransceivers() const {
1396 RTC_DCHECK(IsUnifiedPlan());
1397 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1398 for (auto transceiver : transceivers_) {
1399 all_transceivers.push_back(transceiver);
1400 }
1401 return all_transceivers;
1402}
1403
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001405 MediaStreamTrackInterface* track,
1406 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001407 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001408 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001409 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001410 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 return false;
1412 }
1413
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001414 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001415 // The StatsCollector is used to tell if a track is valid because it may
1416 // remember tracks that the PeerConnection previously removed.
1417 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001418 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1419 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001420 return false;
1421 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001422 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001423 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424 return true;
1425}
1426
hbos74e1a4f2016-09-15 23:33:01 -07001427void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1428 RTC_DCHECK(stats_collector_);
1429 stats_collector_->GetStatsReport(callback);
1430}
1431
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1433 return signaling_state_;
1434}
1435
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436PeerConnectionInterface::IceConnectionState
1437PeerConnection::ice_connection_state() {
1438 return ice_connection_state_;
1439}
1440
1441PeerConnectionInterface::IceGatheringState
1442PeerConnection::ice_gathering_state() {
1443 return ice_gathering_state_;
1444}
1445
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447PeerConnection::CreateDataChannel(
1448 const std::string& label,
1449 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001450 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001451
deadbeefab9b2d12015-10-14 11:33:11 -07001452 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001453
kwibergd1fe2812016-04-27 06:47:29 -07001454 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001455 if (config) {
1456 internal_config.reset(new InternalDataChannelInit(*config));
1457 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001458 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001459 InternalCreateDataChannel(label, internal_config.get()));
1460 if (!channel.get()) {
1461 return nullptr;
1462 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001464 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1465 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001466 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001467 observer_->OnRenegotiationNeeded();
1468 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001469
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 return DataChannelProxy::Create(signaling_thread(), channel.get());
1471}
1472
1473void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1474 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001475 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001476
zhihuang1c378ed2017-08-17 14:10:50 -07001477 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1478 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1479 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1480 // compares the mandatory fields parsed with the mandatory fields added in the
1481 // |constraints| and some downstream applications might create offers with
1482 // mandatory fields which would not be parsed in the helper method. For
1483 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1484 // |constraints| as a mandatory field but it is not parsed.
1485 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001486
zhihuang1c378ed2017-08-17 14:10:50 -07001487 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001488}
1489
1490void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1491 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001492 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001493
nisse7ce109a2017-01-31 00:57:56 -08001494 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001495 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001496 return;
1497 }
deadbeefab9b2d12015-10-14 11:33:11 -07001498
Steve Anton8d3444d2017-10-20 15:30:51 -07001499 if (IsClosed()) {
1500 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001501 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001502 PostCreateSessionDescriptionFailure(observer, error);
1503 return;
1504 }
1505
zhihuang1c378ed2017-08-17 14:10:50 -07001506 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001507 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001508 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001509 PostCreateSessionDescriptionFailure(observer, error);
1510 return;
1511 }
1512
zhihuang1c378ed2017-08-17 14:10:50 -07001513 cricket::MediaSessionOptions session_options;
1514 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001515 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001516}
1517
1518void PeerConnection::CreateAnswer(
1519 CreateSessionDescriptionObserver* observer,
1520 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001521 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001522
nisse7ce109a2017-01-31 00:57:56 -08001523 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001524 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525 return;
1526 }
deadbeefab9b2d12015-10-14 11:33:11 -07001527
zhihuang1c378ed2017-08-17 14:10:50 -07001528 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1529 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1530 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001531 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001533 PostCreateSessionDescriptionFailure(observer, error);
1534 return;
1535 }
1536
Steve Anton8d3444d2017-10-20 15:30:51 -07001537 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001538}
1539
1540void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1541 const RTCOfferAnswerOptions& options) {
1542 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001543 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001544 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001545 return;
1546 }
1547
Steve Anton8d3444d2017-10-20 15:30:51 -07001548 if (IsClosed()) {
1549 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001550 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001551 PostCreateSessionDescriptionFailure(observer, error);
1552 return;
1553 }
1554
Steve Anton75737c02017-11-06 10:37:17 -08001555 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001556 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001557 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001558 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 PostCreateSessionDescriptionFailure(observer, error);
1560 return;
1561 }
1562
htaa2a49d92016-03-04 02:51:39 -08001563 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001564 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001565
Steve Antond25da372017-11-06 14:50:29 -08001566 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567}
1568
1569void PeerConnection::SetLocalDescription(
1570 SetSessionDescriptionObserver* observer,
1571 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001573
nisse7ce109a2017-01-31 00:57:56 -08001574 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001575 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 return;
1577 }
Steve Anton8a006912017-12-04 15:25:56 -08001578
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 if (!desc) {
1580 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1581 return;
1582 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001583
Steve Antona3a92c22017-12-07 10:27:41 -08001584 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001585
Steve Anton8a006912017-12-04 15:25:56 -08001586 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1587 // |desc| may be destroyed at this point.
1588
1589 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001590 std::ostringstream oss;
1591 oss << "Failed to set local " << SdpTypeToString(type)
1592 << " sdp: " << error.message();
1593 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001594 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1595 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001596 return;
1597 }
Steve Anton8a006912017-12-04 15:25:56 -08001598 RTC_DCHECK(local_description());
1599
1600 PostSetSessionDescriptionSuccess(observer);
1601
1602 // According to JSEP, after setLocalDescription, changing the candidate pool
1603 // size is not allowed, and changing the set of ICE servers will not result
1604 // in new candidates being gathered.
1605 port_allocator_->FreezeCandidatePool();
1606
1607 // MaybeStartGathering needs to be called after posting
1608 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1609 // before signaling that SetLocalDescription completed.
1610 transport_controller_->MaybeStartGathering();
1611
Steve Antona3a92c22017-12-07 10:27:41 -08001612 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001613 // TODO(deadbeef): We already had to hop to the network thread for
1614 // MaybeStartGathering...
1615 network_thread()->Invoke<void>(
1616 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1617 port_allocator_.get()));
1618 }
1619}
1620
1621RTCError PeerConnection::ApplyLocalDescription(
1622 std::unique_ptr<SessionDescriptionInterface> desc) {
1623 RTC_DCHECK_RUN_ON(signaling_thread());
1624 RTC_DCHECK(desc);
1625
1626 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1627 if (!error.ok()) {
1628 return error;
1629 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001630
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001631 // Update stats here so that we have the most recent stats for tracks and
1632 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001633 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001634
1635 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001636 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001637 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001638 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001639 if (*initial_offerer_) {
1640 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1641 } else {
1642 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001644 }
Steve Anton8a006912017-12-04 15:25:56 -08001645
Steve Antondcc3c022017-12-22 16:02:54 -08001646 // Take a reference to the old local description since it's used below to
1647 // compare against the new local description. When setting the new local
1648 // description, grab ownership of the replaced session description in case it
1649 // is the same as |old_local_description|, to keep it alive for the duration
1650 // of the method.
1651 const SessionDescriptionInterface* old_local_description =
1652 local_description();
1653 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001654 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001655 replaced_local_description = pending_local_description_
1656 ? std::move(pending_local_description_)
1657 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001658 current_local_description_ = std::move(desc);
1659 pending_local_description_ = nullptr;
1660 current_remote_description_ = std::move(pending_remote_description_);
1661 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001662 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001663 pending_local_description_ = std::move(desc);
1664 }
1665 // The session description to apply now must be accessed by
1666 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001667 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001668
Steve Antondcc3c022017-12-22 16:02:54 -08001669 if (IsUnifiedPlan()) {
1670 RTCError error = UpdateTransceiversAndDataChannels(
1671 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001672 if (!error.ok()) {
1673 return error;
1674 }
Steve Antondcc3c022017-12-22 16:02:54 -08001675 for (auto transceiver : transceivers_) {
1676 const ContentInfo* content =
1677 FindMediaSectionForTransceiver(transceiver, local_description());
1678 if (!content) {
1679 continue;
1680 }
1681 const MediaContentDescription* media_desc = content->media_description();
1682 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1683 transceiver->internal()->set_current_direction(media_desc->direction());
1684 }
1685 if (content->rejected && !transceiver->stopped()) {
1686 transceiver->Stop();
1687 }
1688 }
1689 } else {
1690 // Transport and Media channels will be created only when offer is set.
1691 if (type == SdpType::kOffer) {
1692 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1693 // description is applied. Restore back to old description.
1694 RTCError error = CreateChannels(*local_description()->description());
1695 if (!error.ok()) {
1696 return error;
1697 }
1698 }
Steve Anton8a006912017-12-04 15:25:56 -08001699
Steve Antondcc3c022017-12-22 16:02:54 -08001700 // Remove unused channels if MediaContentDescription is rejected.
1701 RemoveUnusedChannels(local_description()->description());
1702 }
Steve Anton8a006912017-12-04 15:25:56 -08001703
Steve Anton3828c062017-12-06 10:34:51 -08001704 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001705 if (!error.ok()) {
1706 return error;
1707 }
Steve Antondcc3c022017-12-22 16:02:54 -08001708
Steve Anton8a006912017-12-04 15:25:56 -08001709 if (remote_description()) {
1710 // Now that we have a local description, we can push down remote candidates.
1711 UseCandidatesInSessionDescription(remote_description());
1712 }
1713
1714 pending_ice_restarts_.clear();
1715 if (session_error() != SessionError::kNone) {
1716 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1717 }
1718
deadbeefab9b2d12015-10-14 11:33:11 -07001719 // If setting the description decided our SSL role, allocate any necessary
1720 // SCTP sids.
1721 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001722 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001723 AllocateSctpSids(role);
1724 }
1725
Steve Antondcc3c022017-12-22 16:02:54 -08001726 if (!IsUnifiedPlan()) {
1727 // Update state and SSRC of local MediaStreams and DataChannels based on the
1728 // local session description.
1729 const cricket::ContentInfo* audio_content =
1730 GetFirstAudioContent(local_description()->description());
1731 if (audio_content) {
1732 if (audio_content->rejected) {
1733 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1734 } else {
1735 const cricket::AudioContentDescription* audio_desc =
1736 audio_content->media_description()->as_audio();
1737 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1738 }
deadbeeffaac4972015-11-12 15:33:07 -08001739 }
deadbeefab9b2d12015-10-14 11:33:11 -07001740
Steve Antondcc3c022017-12-22 16:02:54 -08001741 const cricket::ContentInfo* video_content =
1742 GetFirstVideoContent(local_description()->description());
1743 if (video_content) {
1744 if (video_content->rejected) {
1745 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1746 } else {
1747 const cricket::VideoContentDescription* video_desc =
1748 video_content->media_description()->as_video();
1749 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1750 }
deadbeeffaac4972015-11-12 15:33:07 -08001751 }
deadbeefab9b2d12015-10-14 11:33:11 -07001752 }
1753
1754 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001755 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001756 if (data_content) {
1757 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001758 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001759 if (rtc::starts_with(data_desc->protocol().data(),
1760 cricket::kMediaProtocolRtpPrefix)) {
1761 UpdateLocalRtpDataChannels(data_desc->streams());
1762 }
1763 }
1764
Steve Anton8a006912017-12-04 15:25:56 -08001765 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766}
1767
1768void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001769 SetSessionDescriptionObserver* observer,
1770 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001771 SetRemoteDescription(
1772 std::unique_ptr<SessionDescriptionInterface>(desc),
1773 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1774 new SetRemoteDescriptionObserverAdapter(this, observer)));
1775}
1776
1777void PeerConnection::SetRemoteDescription(
1778 std::unique_ptr<SessionDescriptionInterface> desc,
1779 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001780 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001781
nisse7ce109a2017-01-31 00:57:56 -08001782 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001783 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 return;
1785 }
Steve Anton8a006912017-12-04 15:25:56 -08001786
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001788 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001789 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790 return;
1791 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001792
Steve Antona3a92c22017-12-07 10:27:41 -08001793 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001794
1795 RTCError error = ApplyRemoteDescription(std::move(desc));
1796 // |desc| may be destroyed at this point.
1797
1798 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001799 std::ostringstream oss;
1800 oss << "Failed to set remote " << SdpTypeToString(type)
1801 << " sdp: " << error.message();
1802 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001803 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001804 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001805 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001806 return;
1807 }
1808
Steve Antona3a92c22017-12-07 10:27:41 -08001809 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001810 // TODO(deadbeef): We already had to hop to the network thread for
1811 // MaybeStartGathering...
1812 network_thread()->Invoke<void>(
1813 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1814 port_allocator_.get()));
1815 }
1816
1817 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1818}
1819
1820RTCError PeerConnection::ApplyRemoteDescription(
1821 std::unique_ptr<SessionDescriptionInterface> desc) {
1822 RTC_DCHECK_RUN_ON(signaling_thread());
1823 RTC_DCHECK(desc);
1824
1825 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1826 if (!error.ok()) {
1827 return error;
1828 }
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 // Update stats here so that we have the most recent stats for tracks and
1831 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001832 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001833
Steve Antondcc3c022017-12-22 16:02:54 -08001834 // Take a reference to the old remote description since it's used below to
1835 // compare against the new remote description. When setting the new remote
1836 // description, grab ownership of the replaced session description in case it
1837 // is the same as |old_remote_description|, to keep it alive for the duration
1838 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001839 const SessionDescriptionInterface* old_remote_description =
1840 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08001841 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001842 SdpType type = desc->GetType();
1843 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001844 replaced_remote_description = pending_remote_description_
1845 ? std::move(pending_remote_description_)
1846 : std::move(current_remote_description_);
1847 current_remote_description_ = std::move(desc);
1848 pending_remote_description_ = nullptr;
1849 current_local_description_ = std::move(pending_local_description_);
1850 } else {
1851 replaced_remote_description = std::move(pending_remote_description_);
1852 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853 }
Steve Anton8a006912017-12-04 15:25:56 -08001854 // The session description to apply now must be accessed by
1855 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001856 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857
Steve Anton8a006912017-12-04 15:25:56 -08001858 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08001859 if (IsUnifiedPlan()) {
1860 RTCError error = UpdateTransceiversAndDataChannels(
1861 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001862 if (!error.ok()) {
1863 return error;
1864 }
Steve Antondcc3c022017-12-22 16:02:54 -08001865 } else {
1866 if (type == SdpType::kOffer) {
1867 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1868 // description is applied. Restore back to old description.
1869 RTCError error = CreateChannels(*remote_description()->description());
1870 if (!error.ok()) {
1871 return error;
1872 }
1873 }
Steve Anton8a006912017-12-04 15:25:56 -08001874
Steve Antondcc3c022017-12-22 16:02:54 -08001875 // Remove unused channels if MediaContentDescription is rejected.
1876 RemoveUnusedChannels(remote_description()->description());
1877 }
Steve Anton8a006912017-12-04 15:25:56 -08001878
1879 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1880 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001881 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001882 if (!error.ok()) {
1883 return error;
1884 }
1885
1886 if (local_description() &&
1887 !UseCandidatesInSessionDescription(remote_description())) {
1888 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1889 }
1890
1891 if (old_remote_description) {
1892 for (const cricket::ContentInfo& content :
1893 old_remote_description->description()->contents()) {
1894 // Check if this new SessionDescription contains new ICE ufrag and
1895 // password that indicates the remote peer requests an ICE restart.
1896 // TODO(deadbeef): When we start storing both the current and pending
1897 // remote description, this should reset pending_ice_restarts and compare
1898 // against the current description.
1899 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1900 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001901 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001902 pending_ice_restarts_.insert(content.name);
1903 }
1904 } else {
1905 // We retain all received candidates only if ICE is not restarted.
1906 // When ICE is restarted, all previous candidates belong to an old
1907 // generation and should not be kept.
1908 // TODO(deadbeef): This goes against the W3C spec which says the remote
1909 // description should only contain candidates from the last set remote
1910 // description plus any candidates added since then. We should remove
1911 // this once we're sure it won't break anything.
1912 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1913 old_remote_description, content.name, mutable_remote_description());
1914 }
1915 }
1916 }
1917
1918 if (session_error() != SessionError::kNone) {
1919 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1920 }
1921
1922 // Set the the ICE connection state to connecting since the connection may
1923 // become writable with peer reflexive candidates before any remote candidate
1924 // is signaled.
1925 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1926 // is to have a new signal the indicates a change in checking state from the
1927 // transport and expose a new checking() member from transport that can be
1928 // read to determine the current checking state. The existing SignalConnecting
1929 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001930 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001931 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1932 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1933 }
1934
deadbeefab9b2d12015-10-14 11:33:11 -07001935 // If setting the description decided our SSL role, allocate any necessary
1936 // SCTP sids.
1937 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001938 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001939 AllocateSctpSids(role);
1940 }
1941
Steve Antondcc3c022017-12-22 16:02:54 -08001942 if (IsUnifiedPlan()) {
1943 for (auto transceiver : transceivers_) {
1944 const ContentInfo* content =
1945 FindMediaSectionForTransceiver(transceiver, remote_description());
1946 if (!content) {
1947 continue;
1948 }
1949 const MediaContentDescription* media_desc = content->media_description();
1950 RtpTransceiverDirection local_direction =
1951 RtpTransceiverDirectionReversed(media_desc->direction());
1952 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
1953 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
1954 // transceiver's current direction is neither sendrecv nor recvonly,
1955 // process the addition of a remote track for the media description.
1956 if (RtpTransceiverDirectionHasRecv(local_direction) &&
1957 (!transceiver->current_direction() ||
1958 !RtpTransceiverDirectionHasRecv(
1959 *transceiver->current_direction()))) {
1960 // TODO(bugs.webrtc.org/7600): Process the addition of a remote track.
1961 }
1962 // If direction is sendonly or inactive, and transceiver's current
1963 // direction is neither sendonly nor inactive, process the removal of a
1964 // remote track for the media description.
1965 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
1966 (!transceiver->current_direction() ||
1967 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
1968 // TODO(bugs.webrtc.org/7600): Process the removal of a remote track.
1969 }
1970 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1971 transceiver->internal()->set_current_direction(local_direction);
1972 }
1973 if (content->rejected && !transceiver->stopped()) {
1974 transceiver->Stop();
1975 }
1976 }
1977 }
1978
Henrik Boströmfdb92012017-11-09 19:55:44 +01001979 const cricket::ContentInfo* audio_content =
1980 GetFirstAudioContent(remote_description()->description());
1981 const cricket::ContentInfo* video_content =
1982 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001983 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001984 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001985 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001986 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001987 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001988 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001989
1990 // Check if the descriptions include streams, just in case the peer supports
1991 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001992 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001993 (audio_desc && !audio_desc->streams().empty()) ||
1994 (video_desc && !video_desc->streams().empty())) {
1995 remote_peer_supports_msid_ = true;
1996 }
deadbeefab9b2d12015-10-14 11:33:11 -07001997
1998 // We wait to signal new streams until we finish processing the description,
1999 // since only at that point will new streams have all their tracks.
2000 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2001
Steve Antondcc3c022017-12-22 16:02:54 -08002002 if (!IsUnifiedPlan()) {
2003 // TODO(steveanton): When removing RTP senders/receivers in response to a
2004 // rejected media section, there is some cleanup logic that expects the
2005 // voice/ video channel to still be set. But in this method the voice/video
2006 // channel would have been destroyed by the SetRemoteDescription caller
2007 // above so the cleanup that relies on them fails to run. The RemoveSenders
2008 // calls should be moved to right before the DestroyChannel calls to fix
2009 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002010
Steve Antondcc3c022017-12-22 16:02:54 -08002011 // Find all audio rtp streams and create corresponding remote AudioTracks
2012 // and MediaStreams.
2013 if (audio_content) {
2014 if (audio_content->rejected) {
2015 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2016 } else {
2017 bool default_audio_track_needed =
2018 !remote_peer_supports_msid_ &&
2019 RtpTransceiverDirectionHasSend(audio_desc->direction());
2020 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2021 default_audio_track_needed, audio_desc->type(),
2022 new_streams);
2023 }
deadbeeffaac4972015-11-12 15:33:07 -08002024 }
deadbeefab9b2d12015-10-14 11:33:11 -07002025
Steve Antondcc3c022017-12-22 16:02:54 -08002026 // Find all video rtp streams and create corresponding remote VideoTracks
2027 // and MediaStreams.
2028 if (video_content) {
2029 if (video_content->rejected) {
2030 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2031 } else {
2032 bool default_video_track_needed =
2033 !remote_peer_supports_msid_ &&
2034 RtpTransceiverDirectionHasSend(video_desc->direction());
2035 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2036 default_video_track_needed, video_desc->type(),
2037 new_streams);
2038 }
deadbeeffaac4972015-11-12 15:33:07 -08002039 }
deadbeefab9b2d12015-10-14 11:33:11 -07002040
Steve Antondcc3c022017-12-22 16:02:54 -08002041 // Update the DataChannels with the information from the remote peer.
2042 if (data_desc) {
2043 if (rtc::starts_with(data_desc->protocol().data(),
2044 cricket::kMediaProtocolRtpPrefix)) {
2045 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2046 }
deadbeefab9b2d12015-10-14 11:33:11 -07002047 }
deadbeefab9b2d12015-10-14 11:33:11 -07002048
Steve Antondcc3c022017-12-22 16:02:54 -08002049 // Iterate new_streams and notify the observer about new MediaStreams.
2050 for (size_t i = 0; i < new_streams->count(); ++i) {
2051 MediaStreamInterface* new_stream = new_streams->at(i);
2052 stats_->AddStream(new_stream);
2053 observer_->OnAddStream(
2054 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2055 }
deadbeefab9b2d12015-10-14 11:33:11 -07002056
Steve Antondcc3c022017-12-22 16:02:54 -08002057 UpdateEndedRemoteMediaStreams();
2058 }
deadbeefab9b2d12015-10-14 11:33:11 -07002059
Steve Anton8a006912017-12-04 15:25:56 -08002060 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002061}
2062
Steve Antondcc3c022017-12-22 16:02:54 -08002063RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2064 cricket::ContentSource source,
2065 const SessionDescriptionInterface* old_session,
2066 const SessionDescriptionInterface& new_session) {
2067 RTC_DCHECK(IsUnifiedPlan());
2068
2069 auto bundle_group_or_error = GetEarlyBundleGroup(*new_session.description());
2070 if (!bundle_group_or_error.ok()) {
2071 return bundle_group_or_error.MoveError();
2072 }
2073 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
2074
2075 const ContentInfos& old_contents =
2076 (old_session ? old_session->description()->contents() : ContentInfos());
2077 const ContentInfos& new_contents = new_session.description()->contents();
2078
2079 for (size_t i = 0; i < new_contents.size(); ++i) {
2080 const cricket::ContentInfo& new_content = new_contents[i];
2081 const cricket::ContentInfo* old_content =
2082 (i < old_contents.size() ? &old_contents[i] : nullptr);
2083 cricket::MediaType media_type = new_content.media_description()->type();
2084 seen_mids_.insert(new_content.name);
2085 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2086 media_type == cricket::MEDIA_TYPE_VIDEO) {
2087 auto transceiver_or_error =
2088 AssociateTransceiver(source, i, new_content, old_content);
2089 if (!transceiver_or_error.ok()) {
2090 return transceiver_or_error.MoveError();
2091 }
2092 auto transceiver = transceiver_or_error.MoveValue();
2093 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2094 continue;
2095 }
2096 RTCError error =
2097 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2098 if (!error.ok()) {
2099 return error;
2100 }
2101 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
2102 // TODO(bugs.webrtc.org/7600): Add support for data channels with Unified
2103 // Plan.
2104 } else {
2105 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2106 "Unknown section type.");
2107 }
2108 }
2109
2110 return RTCError::OK();
2111}
2112
2113RTCError PeerConnection::UpdateTransceiverChannel(
2114 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2115 transceiver,
2116 const cricket::ContentInfo& content,
2117 const cricket::ContentGroup* bundle_group) {
2118 RTC_DCHECK(IsUnifiedPlan());
2119 RTC_DCHECK(transceiver);
2120 cricket::BaseChannel* channel = transceiver->internal()->channel();
2121 if (content.rejected) {
2122 if (channel) {
2123 transceiver->internal()->SetChannel(nullptr);
2124 DestroyBaseChannel(channel);
2125 }
2126 } else {
2127 if (!channel) {
2128 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2129 channel = CreateVoiceChannel(
2130 content.name,
2131 GetTransportNameForMediaSection(content.name, bundle_group));
2132 } else {
2133 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2134 transceiver->internal()->media_type());
2135 channel = CreateVideoChannel(
2136 content.name,
2137 GetTransportNameForMediaSection(content.name, bundle_group));
2138 }
2139 if (!channel) {
2140 LOG_AND_RETURN_ERROR(
2141 RTCErrorType::INTERNAL_ERROR,
2142 "Failed to create channel for mid=" + content.name);
2143 }
2144 transceiver->internal()->SetChannel(channel);
2145 }
2146 }
2147 return RTCError::OK();
2148}
2149
2150RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2151PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2152 size_t mline_index,
2153 const ContentInfo& content,
2154 const ContentInfo* old_content) {
2155 RTC_DCHECK(IsUnifiedPlan());
2156 // If the m= section is being recycled (rejected in previous remote
2157 // description, not rejected in current description), dissociate the currently
2158 // associated RtpTransceiver by setting its mid property to null, and discard
2159 // the mapping between the transceiver and its m= section index.
2160 if (old_content && old_content->rejected && !content.rejected) {
2161 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2162 if (old_transceiver) {
2163 old_transceiver->internal()->set_mid(rtc::nullopt);
2164 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2165 }
2166 }
2167 const MediaContentDescription* media_desc = content.media_description();
2168 auto transceiver = GetAssociatedTransceiver(content.name);
2169 if (source == cricket::CS_LOCAL) {
2170 // Find the RtpTransceiver that corresponds to this m= section, using the
2171 // mapping between transceivers and m= section indices established when
2172 // creating the offer.
2173 if (!transceiver) {
2174 transceiver = GetTransceiverByMLineIndex(mline_index);
2175 }
2176 if (!transceiver) {
2177 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2178 "Unknown transceiver");
2179 }
2180 } else {
2181 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2182 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2183 // of the same type...
2184 if (!transceiver &&
2185 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2186 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2187 }
2188 // If no RtpTransceiver was found in the previous step, create one with a
2189 // recvonly direction.
2190 if (!transceiver) {
2191 transceiver = CreateTransceiver(media_desc->type());
2192 transceiver->internal()->set_direction(
2193 RtpTransceiverDirection::kRecvOnly);
2194 }
2195 }
2196 RTC_DCHECK(transceiver);
2197 if (transceiver->internal()->media_type() != media_desc->type()) {
2198 LOG_AND_RETURN_ERROR(
2199 RTCErrorType::INVALID_PARAMETER,
2200 "Transceiver type does not match media description type.");
2201 }
2202 // Associate the found or created RtpTransceiver with the m= section by
2203 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2204 // section, and establish a mapping between the transceiver and the index of
2205 // the m= section.
2206 transceiver->internal()->set_mid(content.name);
2207 transceiver->internal()->set_mline_index(mline_index);
2208 return std::move(transceiver);
2209}
2210
2211rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2212PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2213 RTC_DCHECK(IsUnifiedPlan());
2214 for (auto transceiver : transceivers_) {
2215 if (transceiver->mid() == mid) {
2216 return transceiver;
2217 }
2218 }
2219 return nullptr;
2220}
2221
2222rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2223PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2224 RTC_DCHECK(IsUnifiedPlan());
2225 for (auto transceiver : transceivers_) {
2226 if (transceiver->internal()->mline_index() == mline_index) {
2227 return transceiver;
2228 }
2229 }
2230 return nullptr;
2231}
2232
2233rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2234PeerConnection::FindAvailableTransceiverToReceive(
2235 cricket::MediaType media_type) const {
2236 RTC_DCHECK(IsUnifiedPlan());
2237 // From JSEP section 5.10 (Applying a Remote Description):
2238 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2239 // the same type that were added to the PeerConnection by addTrack and are not
2240 // associated with any m= section and are not stopped, find the first such
2241 // RtpTransceiver.
2242 for (auto transceiver : transceivers_) {
2243 if (transceiver->internal()->media_type() == media_type &&
2244 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2245 !transceiver->stopped()) {
2246 return transceiver;
2247 }
2248 }
2249 return nullptr;
2250}
2251
Steve Antoned10bd92017-12-05 10:52:59 -08002252const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2253 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2254 transceiver,
2255 const SessionDescriptionInterface* sdesc) const {
2256 RTC_DCHECK(transceiver);
2257 RTC_DCHECK(sdesc);
2258 if (IsUnifiedPlan()) {
2259 if (!transceiver->internal()->mid()) {
2260 // This transceiver is not associated with a media section yet.
2261 return nullptr;
2262 }
2263 return sdesc->description()->GetContentByName(
2264 *transceiver->internal()->mid());
2265 } else {
2266 // Plan B only allows at most one audio and one video section, so use the
2267 // first media section of that type.
2268 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2269 transceiver->internal()->media_type());
2270 }
2271}
2272
deadbeef46c73892016-11-16 19:42:04 -08002273PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2274 return configuration_;
2275}
2276
deadbeef293e9262017-01-11 12:28:30 -08002277bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2278 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002279 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002280
Steve Anton75737c02017-11-06 10:37:17 -08002281 if (local_description() && configuration.ice_candidate_pool_size !=
2282 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002283 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2284 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002285 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002286 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002287
deadbeef293e9262017-01-11 12:28:30 -08002288 // The simplest (and most future-compatible) way to tell if the config was
2289 // modified in an invalid way is to copy each property we do support
2290 // modifying, then use operator==. There are far more properties we don't
2291 // support modifying than those we do, and more could be added.
2292 RTCConfiguration modified_config = configuration_;
2293 modified_config.servers = configuration.servers;
2294 modified_config.type = configuration.type;
2295 modified_config.ice_candidate_pool_size =
2296 configuration.ice_candidate_pool_size;
2297 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002298 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002299 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002300 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002301 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002302 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2303 }
2304
Steve Anton038834f2017-07-14 15:59:59 -07002305 // Validate the modified configuration.
2306 RTCError validate_error = ValidateConfiguration(modified_config);
2307 if (!validate_error.ok()) {
2308 return SafeSetError(std::move(validate_error), error);
2309 }
2310
deadbeef293e9262017-01-11 12:28:30 -08002311 // Note that this isn't possible through chromium, since it's an unsigned
2312 // short in WebIDL.
2313 if (configuration.ice_candidate_pool_size < 0 ||
2314 configuration.ice_candidate_pool_size > UINT16_MAX) {
2315 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2316 }
2317
2318 // Parse ICE servers before hopping to network thread.
2319 cricket::ServerAddresses stun_servers;
2320 std::vector<cricket::RelayServerConfig> turn_servers;
2321 RTCErrorType parse_error =
2322 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2323 if (parse_error != RTCErrorType::NONE) {
2324 return SafeSetError(parse_error, error);
2325 }
2326
2327 // In theory this shouldn't fail.
2328 if (!network_thread()->Invoke<bool>(
2329 RTC_FROM_HERE,
2330 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2331 stun_servers, turn_servers, modified_config.type,
2332 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002333 modified_config.prune_turn_ports,
2334 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002335 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002336 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2337 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002338
deadbeefd1a38b52016-12-10 13:15:33 -08002339 // As described in JSEP, calling setConfiguration with new ICE servers or
2340 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2341 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002342 if (modified_config.servers != configuration_.servers ||
2343 modified_config.type != configuration_.type ||
2344 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002345 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002346 }
skvladd1f5fda2017-02-03 16:54:05 -08002347
2348 if (modified_config.ice_check_min_interval !=
2349 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002350 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002351 }
2352
deadbeef293e9262017-01-11 12:28:30 -08002353 configuration_ = modified_config;
2354 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002355}
2356
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002357bool PeerConnection::AddIceCandidate(
2358 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002359 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002360 if (IsClosed()) {
2361 return false;
2362 }
Steve Antond25da372017-11-06 14:50:29 -08002363
2364 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002365 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2366 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002367 return false;
2368 }
2369
2370 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002371 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002372 return false;
2373 }
2374
2375 bool valid = false;
2376 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2377 if (!valid) {
2378 return false;
2379 }
2380
2381 // Add this candidate to the remote session description.
2382 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002383 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002384 return false;
2385 }
2386
2387 if (ready) {
2388 return UseCandidate(ice_candidate);
2389 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002390 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002391 return true;
2392 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393}
2394
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002395bool PeerConnection::RemoveIceCandidates(
2396 const std::vector<cricket::Candidate>& candidates) {
2397 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002398 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002399 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2400 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002401 return false;
2402 }
2403
2404 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002405 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002406 return false;
2407 }
2408
2409 size_t number_removed =
2410 mutable_remote_description()->RemoveCandidates(candidates);
2411 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002412 RTC_LOG(LS_ERROR)
2413 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2414 << "Requested " << candidates.size() << " but only " << number_removed
2415 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002416 }
2417
2418 // Remove the candidates from the transport controller.
2419 std::string error;
2420 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2421 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002422 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002423 }
2424 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002425}
2426
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002427void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002428 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002429 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002430
Steve Anton75737c02017-11-06 10:37:17 -08002431 if (transport_controller()) {
2432 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002433 }
2434
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002435 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002436 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002437 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002438 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002439 uma_observer_->IncrementEnumCounter(
2440 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2441 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002442 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002443 uma_observer_->IncrementEnumCounter(
2444 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2445 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002446 }
2447 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002448}
2449
zstein4b979802017-06-02 14:37:37 -07002450RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002451 if (!worker_thread()->IsCurrent()) {
2452 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002453 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2454 }
2455
2456 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2457 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2458 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2459 if (has_min && *bitrate.min_bitrate_bps < 0) {
2460 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2461 "min_bitrate_bps <= 0");
2462 }
2463 if (has_current) {
2464 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2465 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2466 "current_bitrate_bps < min_bitrate_bps");
2467 } else if (*bitrate.current_bitrate_bps < 0) {
2468 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2469 "curent_bitrate_bps < 0");
2470 }
2471 }
2472 if (has_max) {
2473 if (has_current &&
2474 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2475 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2476 "max_bitrate_bps < current_bitrate_bps");
2477 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2478 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2479 "max_bitrate_bps < min_bitrate_bps");
2480 } else if (*bitrate.max_bitrate_bps < 0) {
2481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2482 "max_bitrate_bps < 0");
2483 }
2484 }
2485
2486 Call::Config::BitrateConfigMask mask;
2487 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2488 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2489 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2490
2491 RTC_DCHECK(call_.get());
2492 call_->SetBitrateConfigMask(mask);
2493
2494 return RTCError::OK();
2495}
2496
Alex Narest78609d52017-10-20 10:37:47 +02002497void PeerConnection::SetBitrateAllocationStrategy(
2498 std::unique_ptr<rtc::BitrateAllocationStrategy>
2499 bitrate_allocation_strategy) {
2500 rtc::Thread* worker_thread = factory_->worker_thread();
2501 if (!worker_thread->IsCurrent()) {
2502 rtc::BitrateAllocationStrategy* strategy_raw =
2503 bitrate_allocation_strategy.release();
2504 auto functor = [this, strategy_raw]() {
2505 call_->SetBitrateAllocationStrategy(
2506 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2507 };
2508 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2509 return;
2510 }
2511 RTC_DCHECK(call_.get());
2512 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2513}
2514
henrika5f6bf242017-11-01 11:06:56 +01002515void PeerConnection::SetAudioPlayout(bool playout) {
2516 if (!worker_thread()->IsCurrent()) {
2517 worker_thread()->Invoke<void>(
2518 RTC_FROM_HERE,
2519 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2520 return;
2521 }
2522 auto audio_state =
2523 factory_->channel_manager()->media_engine()->GetAudioState();
2524 audio_state->SetPlayout(playout);
2525}
2526
2527void PeerConnection::SetAudioRecording(bool recording) {
2528 if (!worker_thread()->IsCurrent()) {
2529 worker_thread()->Invoke<void>(
2530 RTC_FROM_HERE,
2531 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2532 return;
2533 }
2534 auto audio_state =
2535 factory_->channel_manager()->media_engine()->GetAudioState();
2536 audio_state->SetRecording(recording);
2537}
2538
Steve Anton8c0f7a72017-10-03 10:03:10 -07002539std::unique_ptr<rtc::SSLCertificate>
2540PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002541 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002542 return nullptr;
2543 }
Steve Anton75737c02017-11-06 10:37:17 -08002544 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002545}
2546
ivoc14d5dbe2016-07-04 07:06:55 -07002547bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2548 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002549 // TODO(eladalon): It would be better to not allow negative values into PC.
2550 const size_t max_size = (max_size_bytes < 0)
2551 ? RtcEventLog::kUnlimitedOutput
2552 : rtc::saturated_cast<size_t>(max_size_bytes);
2553 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002554 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2555 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002556}
2557
Bjorn Tereliusde939432017-11-20 17:38:14 +01002558bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2559 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002560 // TODO(eladalon): In C++14, this can be done with a lambda.
2561 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002562 bool operator()() {
2563 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2564 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002565 PeerConnection* const pc;
2566 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002567 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002568 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002569 return worker_thread()->Invoke<bool>(
2570 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002571}
2572
2573void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002574 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002575 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2576}
2577
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002578const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002579 return pending_local_description_ ? pending_local_description_.get()
2580 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581}
2582
2583const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002584 return pending_remote_description_ ? pending_remote_description_.get()
2585 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002586}
2587
deadbeeffe4a8a42016-12-20 17:56:17 -08002588const SessionDescriptionInterface* PeerConnection::current_local_description()
2589 const {
Steve Anton75737c02017-11-06 10:37:17 -08002590 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002591}
2592
2593const SessionDescriptionInterface* PeerConnection::current_remote_description()
2594 const {
Steve Anton75737c02017-11-06 10:37:17 -08002595 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002596}
2597
2598const SessionDescriptionInterface* PeerConnection::pending_local_description()
2599 const {
Steve Anton75737c02017-11-06 10:37:17 -08002600 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002601}
2602
2603const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2604 const {
Steve Anton75737c02017-11-06 10:37:17 -08002605 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002606}
2607
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002609 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 // Update stats here so that we have the most recent stats for tracks and
2611 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002612 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613
Steve Anton75737c02017-11-06 10:37:17 -08002614 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002615
Steve Anton8af21862017-12-15 11:20:13 -08002616 for (auto transceiver : transceivers_) {
2617 transceiver->Stop();
2618 }
2619 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002620
deadbeef42a42632017-03-10 15:18:00 -08002621 network_thread()->Invoke<void>(
2622 RTC_FROM_HERE,
2623 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2624 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002625
Steve Anton978b8762017-09-29 12:15:02 -07002626 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002627 call_.reset();
2628 // The event log must outlive call (and any other object that uses it).
2629 event_log_.reset();
2630 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002631}
2632
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002633void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002635 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2636 SetSessionDescriptionMsg* param =
2637 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2638 param->observer->OnSuccess();
2639 delete param;
2640 break;
2641 }
2642 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2643 SetSessionDescriptionMsg* param =
2644 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2645 param->observer->OnFailure(param->error);
2646 delete param;
2647 break;
2648 }
deadbeefab9b2d12015-10-14 11:33:11 -07002649 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2650 CreateSessionDescriptionMsg* param =
2651 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2652 param->observer->OnFailure(param->error);
2653 delete param;
2654 break;
2655 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656 case MSG_GETSTATS: {
2657 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002658 StatsReports reports;
2659 stats_->GetStats(param->track, &reports);
2660 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661 delete param;
2662 break;
2663 }
deadbeefbd292462015-12-14 18:15:29 -08002664 case MSG_FREE_DATACHANNELS: {
2665 sctp_data_channels_to_free_.clear();
2666 break;
2667 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002668 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002669 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670 break;
2671 }
2672}
2673
Steve Anton4171afb2017-11-20 10:20:22 -08002674void PeerConnection::CreateAudioReceiver(
2675 MediaStreamInterface* stream,
2676 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002677 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2678 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002679 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2680 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002681 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002682 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002683 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002684 stream->AddTrack(
2685 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002686 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002687 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688}
2689
Steve Anton4171afb2017-11-20 10:20:22 -08002690void PeerConnection::CreateVideoReceiver(
2691 MediaStreamInterface* stream,
2692 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002693 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2694 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002695 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2696 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002697 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002698 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2699 worker_thread(), remote_sender_info.first_ssrc,
2700 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002701 stream->AddTrack(
2702 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002703 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002704 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705}
2706
deadbeef70ab1a12015-09-28 16:53:55 -07002707// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2708// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002709rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002710 const RtpSenderInfo& remote_sender_info) {
2711 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2712 if (!receiver) {
2713 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2714 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002715 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002716 }
Steve Anton4171afb2017-11-20 10:20:22 -08002717 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2718 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2719 } else {
2720 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2721 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002722 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002723}
2724
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002725void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2726 MediaStreamInterface* stream) {
2727 RTC_DCHECK(!IsClosed());
2728 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002729 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002730 // We already have a sender for this track, so just change the stream_id
2731 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002732 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002733 return;
2734 }
2735
2736 // Normal case; we've never seen this track before.
2737 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2738 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2739 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002740 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2741 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002742 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002743 // If the sender has already been configured in SDP, we call SetSsrc,
2744 // which will connect the sender to the underlying transport. This can
2745 // occur if a local session description that contains the ID of the sender
2746 // is set before AddStream is called. It can also occur if the local
2747 // session description is not changed and RemoveStream is called, and
2748 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002749 const RtpSenderInfo* sender_info =
2750 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2751 if (sender_info) {
2752 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002753 }
2754}
2755
2756// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2757// indefinitely, when we have unified plan SDP.
2758void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2759 MediaStreamInterface* stream) {
2760 RTC_DCHECK(!IsClosed());
2761 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002762 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002763 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2764 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002765 return;
2766 }
Steve Anton4171afb2017-11-20 10:20:22 -08002767 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002768}
2769
2770void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2771 MediaStreamInterface* stream) {
2772 RTC_DCHECK(!IsClosed());
2773 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002774 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002775 // We already have a sender for this track, so just change the stream_id
2776 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002777 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002778 return;
2779 }
2780
2781 // Normal case; we've never seen this track before.
2782 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2783 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002784 signaling_thread(),
2785 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002786 GetVideoTransceiver()->internal()->AddSender(new_sender);
2787 const RtpSenderInfo* sender_info =
2788 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2789 if (sender_info) {
2790 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002791 }
2792}
2793
2794void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2795 MediaStreamInterface* stream) {
2796 RTC_DCHECK(!IsClosed());
2797 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002798 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002799 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2800 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002801 return;
2802 }
Steve Anton4171afb2017-11-20 10:20:22 -08002803 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002804}
2805
Steve Antonba818672017-11-06 10:21:57 -08002806void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002807 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002808 if (ice_connection_state_ == new_state) {
2809 return;
2810 }
2811
deadbeefcbecd352015-09-23 11:50:27 -07002812 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002813 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002814 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002815 return;
2816 }
Steve Antonba818672017-11-06 10:21:57 -08002817
Mirko Bonadei675513b2017-11-09 11:09:25 +01002818 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2819 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002820 RTC_DCHECK(ice_connection_state_ !=
2821 PeerConnectionInterface::kIceConnectionClosed);
2822
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002823 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002824 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002825}
2826
2827void PeerConnection::OnIceGatheringChange(
2828 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002829 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 if (IsClosed()) {
2831 return;
2832 }
2833 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002834 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835}
2836
jbauch81bf7b02017-03-25 08:31:12 -07002837void PeerConnection::OnIceCandidate(
2838 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002839 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002840 if (IsClosed()) {
2841 return;
2842 }
jbauch81bf7b02017-03-25 08:31:12 -07002843 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844}
2845
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002846void PeerConnection::OnIceCandidatesRemoved(
2847 const std::vector<cricket::Candidate>& candidates) {
2848 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002849 if (IsClosed()) {
2850 return;
2851 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002852 observer_->OnIceCandidatesRemoved(candidates);
2853}
2854
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855void PeerConnection::ChangeSignalingState(
2856 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002857 RTC_DCHECK(signaling_thread()->IsCurrent());
2858 if (signaling_state_ == signaling_state) {
2859 return;
2860 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002861 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2862 << GetSignalingStateString(signaling_state_)
2863 << " New state: "
2864 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 signaling_state_ = signaling_state;
2866 if (signaling_state == kClosed) {
2867 ice_connection_state_ = kIceConnectionClosed;
2868 observer_->OnIceConnectionChange(ice_connection_state_);
2869 if (ice_gathering_state_ != kIceGatheringComplete) {
2870 ice_gathering_state_ = kIceGatheringComplete;
2871 observer_->OnIceGatheringChange(ice_gathering_state_);
2872 }
2873 }
2874 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002875}
2876
deadbeefeb459812015-12-15 19:24:43 -08002877void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2878 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002879 if (IsClosed()) {
2880 return;
2881 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002882 AddAudioTrack(track, stream);
2883 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002884}
2885
deadbeefeb459812015-12-15 19:24:43 -08002886void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2887 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002888 if (IsClosed()) {
2889 return;
2890 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002891 RemoveAudioTrack(track, stream);
2892 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002893}
2894
2895void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2896 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002897 if (IsClosed()) {
2898 return;
2899 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002900 AddVideoTrack(track, stream);
2901 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002902}
2903
2904void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2905 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002906 if (IsClosed()) {
2907 return;
2908 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002909 RemoveVideoTrack(track, stream);
2910 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002911}
2912
Henrik Boström31638672017-11-23 17:48:32 +01002913void PeerConnection::PostSetSessionDescriptionSuccess(
2914 SetSessionDescriptionObserver* observer) {
2915 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2916 signaling_thread()->Post(RTC_FROM_HERE, this,
2917 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2918}
2919
deadbeefab9b2d12015-10-14 11:33:11 -07002920void PeerConnection::PostSetSessionDescriptionFailure(
2921 SetSessionDescriptionObserver* observer,
2922 const std::string& error) {
2923 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2924 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002925 signaling_thread()->Post(RTC_FROM_HERE, this,
2926 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002927}
2928
2929void PeerConnection::PostCreateSessionDescriptionFailure(
2930 CreateSessionDescriptionObserver* observer,
2931 const std::string& error) {
2932 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2933 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002934 signaling_thread()->Post(RTC_FROM_HERE, this,
2935 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002936}
2937
zhihuang1c378ed2017-08-17 14:10:50 -07002938void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08002939 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07002940 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08002941 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07002942
Steve Antondcc3c022017-12-22 16:02:54 -08002943 if (IsUnifiedPlan()) {
2944 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
2945 } else {
2946 GetOptionsForPlanBOffer(offer_answer_options, session_options);
2947 }
2948
2949 // Apply ICE restart flag and renomination flag.
2950 for (auto& options : session_options->media_description_options) {
2951 options.transport_options.ice_restart = offer_answer_options.ice_restart;
2952 options.transport_options.enable_ice_renomination =
2953 configuration_.enable_ice_renomination;
2954 }
2955
2956 session_options->rtcp_cname = rtcp_cname_;
2957 session_options->crypto_options = factory_->options().crypto_options;
2958}
2959
2960void PeerConnection::GetOptionsForPlanBOffer(
2961 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
2962 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002963 // Figure out transceiver directional preferences.
2964 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2965 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2966
2967 // By default, generate sendrecv/recvonly m= sections.
2968 bool recv_audio = true;
2969 bool recv_video = true;
2970
2971 // By default, only offer a new m= section if we have media to send with it.
2972 bool offer_new_audio_description = send_audio;
2973 bool offer_new_video_description = send_video;
2974 bool offer_new_data_description = HasDataChannels();
2975
2976 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08002977 if (offer_answer_options.offer_to_receive_audio !=
2978 RTCOfferAnswerOptions::kUndefined) {
2979 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07002980 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08002981 offer_new_audio_description ||
2982 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07002983 }
Steve Antondcc3c022017-12-22 16:02:54 -08002984 if (offer_answer_options.offer_to_receive_video !=
2985 RTCOfferAnswerOptions::kUndefined) {
2986 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07002987 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08002988 offer_new_video_description ||
2989 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07002990 }
2991
2992 rtc::Optional<size_t> audio_index;
2993 rtc::Optional<size_t> video_index;
2994 rtc::Optional<size_t> data_index;
2995 // If a current description exists, generate m= sections in the same order,
2996 // using the first audio/video/data section that appears and rejecting
2997 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002998 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002999 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003000 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003001 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3002 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3003 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003004 }
3005
zhihuang1c378ed2017-08-17 14:10:50 -07003006 // Add audio/video/data m= sections to the end if needed.
3007 if (!audio_index && offer_new_audio_description) {
3008 session_options->media_description_options.push_back(
3009 cricket::MediaDescriptionOptions(
3010 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003011 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3012 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003013 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003014 }
zhihuang1c378ed2017-08-17 14:10:50 -07003015 if (!video_index && offer_new_video_description) {
3016 session_options->media_description_options.push_back(
3017 cricket::MediaDescriptionOptions(
3018 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003019 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3020 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003021 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003022 }
zhihuang1c378ed2017-08-17 14:10:50 -07003023 if (!data_index && offer_new_data_description) {
3024 session_options->media_description_options.push_back(
3025 cricket::MediaDescriptionOptions(
3026 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08003027 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003028 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003029 }
3030
3031 cricket::MediaDescriptionOptions* audio_media_description_options =
3032 !audio_index ? nullptr
3033 : &session_options->media_description_options[*audio_index];
3034 cricket::MediaDescriptionOptions* video_media_description_options =
3035 !video_index ? nullptr
3036 : &session_options->media_description_options[*video_index];
3037 cricket::MediaDescriptionOptions* data_media_description_options =
3038 !data_index ? nullptr
3039 : &session_options->media_description_options[*data_index];
3040
Steve Anton4171afb2017-11-20 10:20:22 -08003041 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003042 video_media_description_options);
3043 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07003044
zhihuang9763d562016-08-05 11:14:50 -07003045 // Intentionally unset the data channel type for RTP data channel with the
3046 // second condition. Otherwise the RTP data channels would be successfully
3047 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3048 // when building with chromium. We want to leave RTP data channels broken, so
3049 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08003050 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3051 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07003052 }
Steve Antondcc3c022017-12-22 16:02:54 -08003053}
3054
3055// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3056// and return a reference to it.
3057// Generated MIDs should be no more than 3 bytes long to take up less space in
3058// the RTP packet.
3059static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3060 RTC_DCHECK(used_mids);
3061 // We're boring: just generate MIDs 0, 1, 2, ...
3062 size_t i = 0;
3063 std::set<std::string>::iterator it;
3064 bool inserted;
3065 do {
3066 std::string mid = rtc::ToString(i++);
3067 auto insert_result = used_mids->insert(mid);
3068 it = insert_result.first;
3069 inserted = insert_result.second;
3070 } while (!inserted);
3071 return *it;
3072}
3073
3074static cricket::MediaDescriptionOptions
3075GetMediaDescriptionOptionsForTransceiver(
3076 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3077 transceiver,
3078 const std::string& mid) {
3079 cricket::MediaDescriptionOptions media_description_options(
3080 transceiver->internal()->media_type(), mid, transceiver->direction(),
3081 transceiver->stopped());
3082 cricket::SenderOptions sender_options;
3083 sender_options.track_id = transceiver->sender()->id();
3084 sender_options.stream_ids = transceiver->sender()->stream_ids();
3085 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3086 // set in the RTP parameters when the transceiver was added.
3087 sender_options.num_sim_layers = 1;
3088 media_description_options.sender_options.push_back(sender_options);
3089 return media_description_options;
3090}
3091
3092void PeerConnection::GetOptionsForUnifiedPlanOffer(
3093 const RTCOfferAnswerOptions& offer_answer_options,
3094 cricket::MediaSessionOptions* session_options) {
3095 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3096 // Offers) and 5.2.2 (Subsequent Offers).
3097 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3098 const ContentInfos& local_contents =
3099 (local_description() ? local_description()->description()->contents()
3100 : ContentInfos());
3101 const ContentInfos& remote_contents =
3102 (remote_description() ? remote_description()->description()->contents()
3103 : ContentInfos());
3104 // The mline indices that can be recycled. New transceivers should reuse these
3105 // slots first.
3106 std::queue<size_t> recycleable_mline_indices;
3107 // Track the MIDs used in previous offer/answer exchanges and the current
3108 // offer so that new, unique MIDs are generated.
3109 std::set<std::string> used_mids = seen_mids_;
3110 // First, go through each media section that exists in either the local or
3111 // remote description and generate a media section in this offer for the
3112 // associated transceiver. If a media section can be recycled, generate a
3113 // default, rejected media section here that can be later overwritten.
3114 for (size_t i = 0;
3115 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3116 // Either |local_content| or |remote_content| is non-null.
3117 const ContentInfo* local_content =
3118 (i < local_contents.size() ? &local_contents[i] : nullptr);
3119 const ContentInfo* remote_content =
3120 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3121 bool had_been_rejected = (local_content && local_content->rejected) ||
3122 (remote_content && remote_content->rejected);
3123 const std::string& mid =
3124 (local_content ? local_content->name : remote_content->name);
3125 cricket::MediaType media_type =
3126 (local_content ? local_content->media_description()->type()
3127 : remote_content->media_description()->type());
3128 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3129 media_type == cricket::MEDIA_TYPE_VIDEO) {
3130 auto transceiver = GetAssociatedTransceiver(mid);
3131 RTC_CHECK(transceiver);
3132 // A media section is considered eligible for recycling if it is marked as
3133 // rejected in either the local or remote description.
3134 if (had_been_rejected) {
3135 session_options->media_description_options.push_back(
3136 cricket::MediaDescriptionOptions(
3137 transceiver->internal()->media_type(), mid,
3138 RtpTransceiverDirection::kInactive,
3139 /*stopped=*/true));
3140 recycleable_mline_indices.push(i);
3141 } else {
3142 session_options->media_description_options.push_back(
3143 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3144 // CreateOffer shouldn't really cause any state changes in
3145 // PeerConnection, but we need a way to match new transceivers to new
3146 // media sections in SetLocalDescription and JSEP specifies this is done
3147 // by recording the index of the media section generated for the
3148 // transceiver in the offer.
3149 transceiver->internal()->set_mline_index(i);
3150 }
3151 } else {
3152 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
3153 // TODO(bugs.webrtc.org/7600): Add support for data channels with Unified
3154 // Plan.
3155 }
3156 }
3157 // Next, look for transceivers that are newly added (that is, are not stopped
3158 // and not associated). Reuse media sections marked as recyclable first,
3159 // otherwise append to the end of the offer. New media sections should be
3160 // added in the order they were added to the PeerConnection.
3161 for (auto transceiver : transceivers_) {
3162 if (transceiver->mid() || transceiver->stopped()) {
3163 continue;
3164 }
3165 size_t mline_index;
3166 if (!recycleable_mline_indices.empty()) {
3167 mline_index = recycleable_mline_indices.front();
3168 recycleable_mline_indices.pop();
3169 session_options->media_description_options[mline_index] =
3170 GetMediaDescriptionOptionsForTransceiver(transceiver,
3171 AllocateMid(&used_mids));
3172 } else {
3173 mline_index = session_options->media_description_options.size();
3174 session_options->media_description_options.push_back(
3175 GetMediaDescriptionOptionsForTransceiver(transceiver,
3176 AllocateMid(&used_mids)));
3177 }
3178 // See comment above for why CreateOffer changes the transceiver's state.
3179 transceiver->internal()->set_mline_index(mline_index);
3180 }
3181 // TODO(bugs.webrtc.org/7600): Add support for data channels with Unified
3182 // Plan.
3183}
3184
3185void PeerConnection::GetOptionsForAnswer(
3186 const RTCOfferAnswerOptions& offer_answer_options,
3187 cricket::MediaSessionOptions* session_options) {
3188 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3189
3190 if (IsUnifiedPlan()) {
3191 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3192 } else {
3193 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3194 }
3195
3196 // Apply ICE renomination flag.
3197 for (auto& options : session_options->media_description_options) {
3198 options.transport_options.enable_ice_renomination =
3199 configuration_.enable_ice_renomination;
3200 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003201
3202 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003203 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003204}
3205
Steve Antondcc3c022017-12-22 16:02:54 -08003206void PeerConnection::GetOptionsForPlanBAnswer(
3207 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003208 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003209 // Figure out transceiver directional preferences.
3210 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3211 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3212
3213 // By default, generate sendrecv/recvonly m= sections. The direction is also
3214 // restricted by the direction in the offer.
3215 bool recv_audio = true;
3216 bool recv_video = true;
3217
3218 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003219 if (offer_answer_options.offer_to_receive_audio !=
3220 RTCOfferAnswerOptions::kUndefined) {
3221 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003222 }
Steve Antondcc3c022017-12-22 16:02:54 -08003223 if (offer_answer_options.offer_to_receive_video !=
3224 RTCOfferAnswerOptions::kUndefined) {
3225 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003226 }
3227
3228 rtc::Optional<size_t> audio_index;
3229 rtc::Optional<size_t> video_index;
3230 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08003231 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07003232 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08003233 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07003234 // Generate m= sections that match those in the offer.
3235 // Note that mediasession.cc will handle intersection our preferred
3236 // direction with the offered direction.
3237 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003238 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003239 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3240 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3241 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07003242 }
zhihuang1c378ed2017-08-17 14:10:50 -07003243
3244 cricket::MediaDescriptionOptions* audio_media_description_options =
3245 !audio_index ? nullptr
3246 : &session_options->media_description_options[*audio_index];
3247 cricket::MediaDescriptionOptions* video_media_description_options =
3248 !video_index ? nullptr
3249 : &session_options->media_description_options[*video_index];
3250 cricket::MediaDescriptionOptions* data_media_description_options =
3251 !data_index ? nullptr
3252 : &session_options->media_description_options[*data_index];
3253
Steve Anton4171afb2017-11-20 10:20:22 -08003254 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003255 video_media_description_options);
3256 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
3257
zhihuang9763d562016-08-05 11:14:50 -07003258 // Intentionally unset the data channel type for RTP data channel. Otherwise
3259 // the RTP data channels would be successfully negotiated by default and the
3260 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3261 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08003262 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3263 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07003264 }
Steve Antondcc3c022017-12-22 16:02:54 -08003265}
zhihuangaf388472016-11-02 16:49:48 -07003266
Steve Antondcc3c022017-12-22 16:02:54 -08003267void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3268 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3269 cricket::MediaSessionOptions* session_options) {
3270 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3271 // Answers) and 5.3.2 (Subsequent Answers).
3272 RTC_DCHECK(remote_description());
3273 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3274 for (const ContentInfo& content :
3275 remote_description()->description()->contents()) {
3276 cricket::MediaType media_type = content.media_description()->type();
3277 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3278 media_type == cricket::MEDIA_TYPE_VIDEO) {
3279 auto transceiver = GetAssociatedTransceiver(content.name);
3280 RTC_CHECK(transceiver);
3281 session_options->media_description_options.push_back(
3282 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3283 } else {
3284 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
3285 // TODO(bugs.webrtc.org/7600): Add support for data channels with Unified
3286 // Plan.
3287 }
3288 }
htaa2a49d92016-03-04 02:51:39 -08003289}
3290
zhihuang1c378ed2017-08-17 14:10:50 -07003291void PeerConnection::GenerateMediaDescriptionOptions(
3292 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003293 RtpTransceiverDirection audio_direction,
3294 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003295 rtc::Optional<size_t>* audio_index,
3296 rtc::Optional<size_t>* video_index,
3297 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003298 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003299 for (const cricket::ContentInfo& content :
3300 session_desc->description()->contents()) {
3301 if (IsAudioContent(&content)) {
3302 // If we already have an audio m= section, reject this extra one.
3303 if (*audio_index) {
3304 session_options->media_description_options.push_back(
3305 cricket::MediaDescriptionOptions(
3306 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003307 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003308 } else {
3309 session_options->media_description_options.push_back(
3310 cricket::MediaDescriptionOptions(
3311 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003312 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003313 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003314 }
3315 } else if (IsVideoContent(&content)) {
3316 // If we already have an video m= section, reject this extra one.
3317 if (*video_index) {
3318 session_options->media_description_options.push_back(
3319 cricket::MediaDescriptionOptions(
3320 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003321 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003322 } else {
3323 session_options->media_description_options.push_back(
3324 cricket::MediaDescriptionOptions(
3325 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003326 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003327 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003328 }
3329 } else {
3330 RTC_DCHECK(IsDataContent(&content));
3331 // If we already have an data m= section, reject this extra one.
3332 if (*data_index) {
3333 session_options->media_description_options.push_back(
3334 cricket::MediaDescriptionOptions(
3335 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003336 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003337 } else {
3338 session_options->media_description_options.push_back(
3339 cricket::MediaDescriptionOptions(
3340 cricket::MEDIA_TYPE_DATA, content.name,
3341 // Direction for data sections is meaningless, but legacy
3342 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08003343 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003344 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003345 }
3346 }
htaa2a49d92016-03-04 02:51:39 -08003347 }
deadbeefab9b2d12015-10-14 11:33:11 -07003348}
3349
Steve Anton4171afb2017-11-20 10:20:22 -08003350void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3351 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3352 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003353 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003354}
3355
Steve Anton4171afb2017-11-20 10:20:22 -08003356void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003357 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003358 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003359 cricket::MediaType media_type,
3360 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003361 std::vector<RtpSenderInfo>* current_senders =
3362 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003363
Steve Anton4171afb2017-11-20 10:20:22 -08003364 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003365 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003366 for (auto sender_it = current_senders->begin();
3367 sender_it != current_senders->end();
3368 /* incremented manually */) {
3369 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003370 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003371 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3372 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003373 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003374 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3375 sender_exists) {
3376 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003377 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003378 OnRemoteSenderRemoved(info, media_type);
3379 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003380 }
3381 }
3382
Steve Anton4171afb2017-11-20 10:20:22 -08003383 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003384 for (const cricket::StreamParams& params : streams) {
3385 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003386 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003387 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003388 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003389 uint32_t ssrc = params.first_ssrc();
3390
3391 rtc::scoped_refptr<MediaStreamInterface> stream =
3392 remote_streams_->find(stream_label);
3393 if (!stream) {
3394 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003395 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3396 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003397 remote_streams_->AddStream(stream);
3398 new_streams->AddStream(stream);
3399 }
3400
Steve Anton4171afb2017-11-20 10:20:22 -08003401 const RtpSenderInfo* sender_info =
3402 FindSenderInfo(*current_senders, stream_label, sender_id);
3403 if (!sender_info) {
3404 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3405 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003406 }
3407 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003408
Steve Anton4171afb2017-11-20 10:20:22 -08003409 // Add default sender if necessary.
3410 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003411 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3412 remote_streams_->find(kDefaultStreamLabel);
3413 if (!default_stream) {
3414 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003415 default_stream = MediaStreamProxy::Create(
3416 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003417 remote_streams_->AddStream(default_stream);
3418 new_streams->AddStream(default_stream);
3419 }
Steve Anton4171afb2017-11-20 10:20:22 -08003420 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3421 ? kDefaultAudioSenderId
3422 : kDefaultVideoSenderId;
3423 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3424 *current_senders, kDefaultStreamLabel, default_sender_id);
3425 if (!default_sender_info) {
3426 current_senders->push_back(
3427 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3428 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003429 }
3430 }
deadbeefab9b2d12015-10-14 11:33:11 -07003431}
3432
Steve Anton4171afb2017-11-20 10:20:22 -08003433void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3434 cricket::MediaType media_type) {
3435 MediaStreamInterface* stream =
3436 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003437
3438 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003439 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003440 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003441 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003442 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003443 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003444 }
3445}
3446
Steve Anton4171afb2017-11-20 10:20:22 -08003447void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3448 cricket::MediaType media_type) {
3449 MediaStreamInterface* stream =
3450 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003451
Henrik Boström933d8b02017-10-10 10:05:16 -07003452 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003453 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003454 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3455 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003456 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003457 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003458 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003459 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003460 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003461 }
3462 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003463 // Stopping or destroying a VideoRtpReceiver will end the
3464 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003465 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003466 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003467 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003468 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003469 // There's no guarantee the track is still available, e.g. the track may
3470 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003471 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003472 }
3473 } else {
nisseede5da42017-01-12 05:15:36 -08003474 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003475 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003476 if (receiver) {
3477 observer_->OnRemoveTrack(receiver);
3478 }
deadbeefab9b2d12015-10-14 11:33:11 -07003479}
3480
3481void PeerConnection::UpdateEndedRemoteMediaStreams() {
3482 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3483 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3484 MediaStreamInterface* stream = remote_streams_->at(i);
3485 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3486 streams_to_remove.push_back(stream);
3487 }
3488 }
3489
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003490 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003491 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003492 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003493 }
3494}
3495
Steve Anton4171afb2017-11-20 10:20:22 -08003496void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003497 const std::vector<cricket::StreamParams>& streams,
3498 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003499 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003500
3501 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3502 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003503 for (auto sender_it = current_senders->begin();
3504 sender_it != current_senders->end();
3505 /* incremented manually */) {
3506 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003507 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003508 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3509 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003510 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003511 OnLocalSenderRemoved(info, media_type);
3512 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003513 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003514 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003515 }
3516 }
3517
Steve Anton4171afb2017-11-20 10:20:22 -08003518 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003519 for (const cricket::StreamParams& params : streams) {
3520 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003521 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003522 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003523 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003524 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003525 const RtpSenderInfo* sender_info =
3526 FindSenderInfo(*current_senders, stream_label, sender_id);
3527 if (!sender_info) {
3528 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3529 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003530 }
3531 }
3532}
3533
Steve Anton4171afb2017-11-20 10:20:22 -08003534void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3535 cricket::MediaType media_type) {
3536 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003537 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003538 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3539 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003540 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003541 return;
3542 }
3543
deadbeeffac06552015-11-25 11:26:01 -08003544 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003545 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3546 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003547 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003548 }
deadbeeffac06552015-11-25 11:26:01 -08003549
Steve Anton4171afb2017-11-20 10:20:22 -08003550 sender->internal()->set_stream_id(sender_info.stream_label);
3551 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003552}
3553
Steve Anton4171afb2017-11-20 10:20:22 -08003554void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3555 cricket::MediaType media_type) {
3556 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003557 if (!sender) {
3558 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003559 // SessionDescriptions has been renegotiated.
3560 return;
3561 }
deadbeeffac06552015-11-25 11:26:01 -08003562
3563 // A sender has been removed from the SessionDescription but it's still
3564 // associated with the PeerConnection. This only occurs if the SDP doesn't
3565 // match with the calls to CreateSender, AddStream and RemoveStream.
3566 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003567 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3568 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003569 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003570 }
deadbeeffac06552015-11-25 11:26:01 -08003571
Steve Anton4171afb2017-11-20 10:20:22 -08003572 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003573}
3574
3575void PeerConnection::UpdateLocalRtpDataChannels(
3576 const cricket::StreamParamsVec& streams) {
3577 std::vector<std::string> existing_channels;
3578
3579 // Find new and active data channels.
3580 for (const cricket::StreamParams& params : streams) {
3581 // |it->sync_label| is actually the data channel label. The reason is that
3582 // we use the same naming of data channels as we do for
3583 // MediaStreams and Tracks.
3584 // For MediaStreams, the sync_label is the MediaStream label and the
3585 // track label is the same as |streamid|.
3586 const std::string& channel_label = params.sync_label;
3587 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003588 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003589 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003590 continue;
3591 }
3592 // Set the SSRC the data channel should use for sending.
3593 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3594 existing_channels.push_back(data_channel_it->first);
3595 }
3596
3597 UpdateClosingRtpDataChannels(existing_channels, true);
3598}
3599
3600void PeerConnection::UpdateRemoteRtpDataChannels(
3601 const cricket::StreamParamsVec& streams) {
3602 std::vector<std::string> existing_channels;
3603
3604 // Find new and active data channels.
3605 for (const cricket::StreamParams& params : streams) {
3606 // The data channel label is either the mslabel or the SSRC if the mslabel
3607 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3608 std::string label = params.sync_label.empty()
3609 ? rtc::ToString(params.first_ssrc())
3610 : params.sync_label;
3611 auto data_channel_it = rtp_data_channels_.find(label);
3612 if (data_channel_it == rtp_data_channels_.end()) {
3613 // This is a new data channel.
3614 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3615 } else {
3616 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3617 }
3618 existing_channels.push_back(label);
3619 }
3620
3621 UpdateClosingRtpDataChannels(existing_channels, false);
3622}
3623
3624void PeerConnection::UpdateClosingRtpDataChannels(
3625 const std::vector<std::string>& active_channels,
3626 bool is_local_update) {
3627 auto it = rtp_data_channels_.begin();
3628 while (it != rtp_data_channels_.end()) {
3629 DataChannel* data_channel = it->second;
3630 if (std::find(active_channels.begin(), active_channels.end(),
3631 data_channel->label()) != active_channels.end()) {
3632 ++it;
3633 continue;
3634 }
3635
3636 if (is_local_update) {
3637 data_channel->SetSendSsrc(0);
3638 } else {
3639 data_channel->RemotePeerRequestClose();
3640 }
3641
3642 if (data_channel->state() == DataChannel::kClosed) {
3643 rtp_data_channels_.erase(it);
3644 it = rtp_data_channels_.begin();
3645 } else {
3646 ++it;
3647 }
3648 }
3649}
3650
3651void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3652 uint32_t remote_ssrc) {
3653 rtc::scoped_refptr<DataChannel> channel(
3654 InternalCreateDataChannel(label, nullptr));
3655 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003656 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3657 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003658 return;
3659 }
3660 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003661 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3662 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003663 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003664}
3665
3666rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3667 const std::string& label,
3668 const InternalDataChannelInit* config) {
3669 if (IsClosed()) {
3670 return nullptr;
3671 }
Steve Anton75737c02017-11-06 10:37:17 -08003672 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003673 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003674 << "InternalCreateDataChannel: Data is not supported in this call.";
3675 return nullptr;
3676 }
3677 InternalDataChannelInit new_config =
3678 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003679 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003680 if (new_config.id < 0) {
3681 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003682 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003683 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003684 RTC_LOG(LS_ERROR)
3685 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003686 return nullptr;
3687 }
3688 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003689 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3690 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003691 return nullptr;
3692 }
3693 }
3694
Steve Anton75737c02017-11-06 10:37:17 -08003695 rtc::scoped_refptr<DataChannel> channel(
3696 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003697 if (!channel) {
3698 sid_allocator_.ReleaseSid(new_config.id);
3699 return nullptr;
3700 }
3701
3702 if (channel->data_channel_type() == cricket::DCT_RTP) {
3703 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003704 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3705 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003706 return nullptr;
3707 }
3708 rtp_data_channels_[channel->label()] = channel;
3709 } else {
3710 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3711 sctp_data_channels_.push_back(channel);
3712 channel->SignalClosed.connect(this,
3713 &PeerConnection::OnSctpDataChannelClosed);
3714 }
3715
hbos82ebe022016-11-14 01:41:09 -08003716 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003717 return channel;
3718}
3719
3720bool PeerConnection::HasDataChannels() const {
3721 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3722}
3723
3724void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3725 for (const auto& channel : sctp_data_channels_) {
3726 if (channel->id() < 0) {
3727 int sid;
3728 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003729 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003730 continue;
3731 }
3732 channel->SetSctpSid(sid);
3733 }
3734 }
3735}
3736
3737void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003738 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003739 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3740 ++it) {
3741 if (it->get() == channel) {
3742 if (channel->id() >= 0) {
3743 sid_allocator_.ReleaseSid(channel->id());
3744 }
deadbeefbd292462015-12-14 18:15:29 -08003745 // Since this method is triggered by a signal from the DataChannel,
3746 // we can't free it directly here; we need to free it asynchronously.
3747 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003748 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003749 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3750 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003751 return;
3752 }
3753 }
3754}
3755
deadbeefab9b2d12015-10-14 11:33:11 -07003756void PeerConnection::OnDataChannelDestroyed() {
3757 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3758 // DataChannel may callback to us and try to modify the list.
3759 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3760 temp_rtp_dcs.swap(rtp_data_channels_);
3761 for (const auto& kv : temp_rtp_dcs) {
3762 kv.second->OnTransportChannelDestroyed();
3763 }
3764
3765 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3766 temp_sctp_dcs.swap(sctp_data_channels_);
3767 for (const auto& channel : temp_sctp_dcs) {
3768 channel->OnTransportChannelDestroyed();
3769 }
3770}
3771
3772void PeerConnection::OnDataChannelOpenMessage(
3773 const std::string& label,
3774 const InternalDataChannelInit& config) {
3775 rtc::scoped_refptr<DataChannel> channel(
3776 InternalCreateDataChannel(label, &config));
3777 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003778 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003779 return;
3780 }
3781
deadbeefa601f5c2016-06-06 14:27:39 -07003782 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3783 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003784 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003785}
3786
Steve Anton4171afb2017-11-20 10:20:22 -08003787rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3788PeerConnection::GetAudioTransceiver() const {
3789 // This method only works with Plan B SDP, where there is a single
3790 // audio/video transceiver.
3791 RTC_DCHECK(!IsUnifiedPlan());
3792 for (auto transceiver : transceivers_) {
3793 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3794 return transceiver;
3795 }
3796 }
3797 RTC_NOTREACHED();
3798 return nullptr;
3799}
3800
3801rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3802PeerConnection::GetVideoTransceiver() const {
3803 // This method only works with Plan B SDP, where there is a single
3804 // audio/video transceiver.
3805 RTC_DCHECK(!IsUnifiedPlan());
3806 for (auto transceiver : transceivers_) {
3807 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3808 return transceiver;
3809 }
3810 }
3811 RTC_NOTREACHED();
3812 return nullptr;
3813}
3814
3815// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3816// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003817bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003818 switch (type) {
3819 case cricket::MEDIA_TYPE_AUDIO:
3820 return !GetAudioTransceiver()->internal()->senders().empty();
3821 case cricket::MEDIA_TYPE_VIDEO:
3822 return !GetVideoTransceiver()->internal()->senders().empty();
3823 case cricket::MEDIA_TYPE_DATA:
3824 return false;
3825 }
3826 RTC_NOTREACHED();
3827 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003828}
3829
Steve Anton4171afb2017-11-20 10:20:22 -08003830rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3831PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3832 for (auto transceiver : transceivers_) {
3833 for (auto sender : transceiver->internal()->senders()) {
3834 if (sender->track() == track) {
3835 return sender;
3836 }
3837 }
3838 }
3839 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003840}
3841
Steve Anton4171afb2017-11-20 10:20:22 -08003842rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3843PeerConnection::FindSenderById(const std::string& sender_id) const {
3844 for (auto transceiver : transceivers_) {
3845 for (auto sender : transceiver->internal()->senders()) {
3846 if (sender->id() == sender_id) {
3847 return sender;
3848 }
3849 }
3850 }
3851 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003852}
3853
Steve Anton4171afb2017-11-20 10:20:22 -08003854rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3855PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3856 for (auto transceiver : transceivers_) {
3857 for (auto receiver : transceiver->internal()->receivers()) {
3858 if (receiver->id() == receiver_id) {
3859 return receiver;
3860 }
3861 }
3862 }
3863 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003864}
3865
Steve Anton4171afb2017-11-20 10:20:22 -08003866std::vector<PeerConnection::RtpSenderInfo>*
3867PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3868 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3869 media_type == cricket::MEDIA_TYPE_VIDEO);
3870 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3871 ? &remote_audio_sender_infos_
3872 : &remote_video_sender_infos_;
3873}
3874
3875std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003876 cricket::MediaType media_type) {
3877 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3878 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003879 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3880 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003881}
3882
Steve Anton4171afb2017-11-20 10:20:22 -08003883const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3884 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003885 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003886 const std::string sender_id) const {
3887 for (const RtpSenderInfo& sender_info : infos) {
3888 if (sender_info.stream_label == stream_label &&
3889 sender_info.sender_id == sender_id) {
3890 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003891 }
3892 }
3893 return nullptr;
3894}
3895
3896DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3897 for (const auto& channel : sctp_data_channels_) {
3898 if (channel->id() == sid) {
3899 return channel;
3900 }
3901 }
3902 return nullptr;
3903}
3904
deadbeef91dd5672016-05-18 16:55:30 -07003905bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003906 const RTCConfiguration& configuration) {
3907 cricket::ServerAddresses stun_servers;
3908 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003909 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3910 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003911 return false;
3912 }
3913
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003914 port_allocator_->Initialize();
3915
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003916 // To handle both internal and externally created port allocator, we will
3917 // enable BUNDLE here.
3918 int portallocator_flags = port_allocator_->flags();
3919 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003920 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3921 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003922 // If the disable-IPv6 flag was specified, we'll not override it
3923 // by experiment.
3924 if (configuration.disable_ipv6) {
3925 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003926 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3927 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003928 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3929 }
3930
zhihuangb09b3f92017-03-07 14:40:51 -08003931 if (configuration.disable_ipv6_on_wifi) {
3932 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003933 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003934 }
3935
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003936 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3937 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003938 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003939 }
3940
honghaiz60347052016-05-31 18:29:12 -07003941 if (configuration.candidate_network_policy ==
3942 kCandidateNetworkPolicyLowCost) {
3943 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003944 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003945 }
3946
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003947 port_allocator_->set_flags(portallocator_flags);
3948 // No step delay is used while allocating ports.
3949 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3950 port_allocator_->set_candidate_filter(
3951 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003952 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003953
3954 // Call this last since it may create pooled allocator sessions using the
3955 // properties set above.
3956 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003957 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003958 configuration.prune_turn_ports,
3959 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003960 return true;
3961}
3962
deadbeef91dd5672016-05-18 16:55:30 -07003963bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003964 const cricket::ServerAddresses& stun_servers,
3965 const std::vector<cricket::RelayServerConfig>& turn_servers,
3966 IceTransportsType type,
3967 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003968 bool prune_turn_ports,
3969 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003970 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003971 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003972 // Call this last since it may create pooled allocator sessions using the
3973 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003974 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003975 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3976 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003977}
3978
Steve Antonba818672017-11-06 10:21:57 -08003979cricket::ChannelManager* PeerConnection::channel_manager() const {
3980 return factory_->channel_manager();
3981}
3982
3983MetricsObserverInterface* PeerConnection::metrics_observer() const {
3984 return uma_observer_;
3985}
3986
Elad Alon99c3fe52017-10-13 16:29:40 +02003987bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003988 std::unique_ptr<RtcEventLogOutput> output,
3989 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003990 if (!event_log_) {
3991 return false;
3992 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003993 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003994}
3995
3996void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003997 if (event_log_) {
3998 event_log_->StopLogging();
3999 }
ivoc14d5dbe2016-07-04 07:06:55 -07004000}
nisseeaabdf62017-05-05 02:23:02 -07004001
Steve Anton75737c02017-11-06 10:37:17 -08004002cricket::BaseChannel* PeerConnection::GetChannel(
4003 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004004 for (auto transceiver : transceivers_) {
4005 cricket::BaseChannel* channel = transceiver->internal()->channel();
4006 if (channel && channel->content_name() == content_name) {
4007 return channel;
4008 }
Steve Anton75737c02017-11-06 10:37:17 -08004009 }
4010 if (rtp_data_channel() &&
4011 rtp_data_channel()->content_name() == content_name) {
4012 return rtp_data_channel();
4013 }
4014 return nullptr;
4015}
4016
4017bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4018 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004019 RTC_LOG(LS_INFO)
4020 << "Local and Remote descriptions must be applied to get the "
4021 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004022 return false;
4023 }
4024 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004025 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4026 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004027 return false;
4028 }
4029
4030 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4031}
4032
4033bool PeerConnection::GetSslRole(const std::string& content_name,
4034 rtc::SSLRole* role) {
4035 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004036 RTC_LOG(LS_INFO)
4037 << "Local and Remote descriptions must be applied to get the "
4038 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004039 return false;
4040 }
4041
4042 return transport_controller_->GetSslRole(GetTransportName(content_name),
4043 role);
4044}
4045
Steve Anton75737c02017-11-06 10:37:17 -08004046// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4047// vector of BaseChannel pointers instead of separate voice and video channel
4048// vectors. At that point, this will become a simple getter.
4049std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4050 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004051 if (voice_channel()) {
4052 channels.push_back(voice_channel());
4053 }
4054 if (video_channel()) {
4055 channels.push_back(video_channel());
4056 }
Steve Anton75737c02017-11-06 10:37:17 -08004057 if (rtp_data_channel_) {
4058 channels.push_back(rtp_data_channel_);
4059 }
4060 return channels;
4061}
4062
Steve Antonf8470812017-12-04 10:46:21 -08004063void PeerConnection::SetSessionError(SessionError error,
4064 const std::string& error_desc) {
4065 RTC_DCHECK_RUN_ON(signaling_thread());
4066 if (error != session_error_) {
4067 session_error_ = error;
4068 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004069 }
4070}
4071
Steve Anton3828c062017-12-06 10:34:51 -08004072RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004073 cricket::ContentSource source) {
4074 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004075
4076 // If there's already a pending error then no state transition should happen.
4077 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004078 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004079
4080 // If this is an answer then we know whether to BUNDLE or not. If both the
4081 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004082 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004083 const cricket::ContentGroup* local_bundle =
4084 local_description()->description()->GetGroupByName(
4085 cricket::GROUP_TYPE_BUNDLE);
4086 const cricket::ContentGroup* remote_bundle =
4087 remote_description()->description()->GetGroupByName(
4088 cricket::GROUP_TYPE_BUNDLE);
4089 if (local_bundle && remote_bundle) {
4090 // The answerer decides the transport to bundle on.
4091 const cricket::ContentGroup* answer_bundle =
4092 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4093 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004094 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4095 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004096 }
4097 }
Steve Anton75737c02017-11-06 10:37:17 -08004098 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004099
4100 // Only push down the transport description after potentially enabling BUNDLE;
4101 // we don't want to push down a description on a transport about to be
4102 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004103 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004104 if (!error.ok()) {
4105 return error;
4106 }
4107
4108 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004109 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004110 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004111 }
4112
4113 // Update the signaling state according to the specified state machine (see
4114 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004115 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004116 ChangeSignalingState(source == cricket::CS_LOCAL
4117 ? PeerConnectionInterface::kHaveLocalOffer
4118 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004119 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004120 ChangeSignalingState(source == cricket::CS_LOCAL
4121 ? PeerConnectionInterface::kHaveLocalPrAnswer
4122 : PeerConnectionInterface::kHaveRemotePrAnswer);
4123 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004124 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004125 ChangeSignalingState(PeerConnectionInterface::kStable);
4126 }
4127
4128 // Update internal objects according to the session description's media
4129 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004130 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004131 if (!error.ok()) {
4132 SetSessionError(SessionError::kContent, error.message());
4133 }
4134 if (session_error() != SessionError::kNone) {
4135 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4136 }
4137
Steve Anton8a006912017-12-04 15:25:56 -08004138 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004139}
4140
Steve Anton8a006912017-12-04 15:25:56 -08004141RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004142 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004143 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004144 const SessionDescriptionInterface* sdesc =
4145 (source == cricket::CS_LOCAL ? local_description()
4146 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004147 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004148
4149 // Push down the new SDP media section for each audio/video transceiver.
4150 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004151 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004152 FindMediaSectionForTransceiver(transceiver, sdesc);
4153 cricket::BaseChannel* channel = transceiver->internal()->channel();
4154 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004155 continue;
4156 }
4157 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004158 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004159 if (!content_desc) {
4160 continue;
4161 }
4162 std::string error;
4163 bool success =
4164 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004165 ? channel->SetLocalContent(content_desc, type, &error)
4166 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004167 if (!success) {
4168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4169 }
4170 }
4171
4172 // If using the RtpDataChannel, push down the new SDP section for it too.
4173 if (rtp_data_channel_) {
4174 const ContentInfo* data_content =
4175 cricket::GetFirstDataContent(sdesc->description());
4176 if (data_content && !data_content->rejected) {
4177 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004178 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004179 if (data_desc) {
4180 std::string error;
4181 bool success =
4182 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004183 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4184 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004185 &error);
4186 if (!success) {
4187 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4188 std::move(error));
4189 }
Steve Anton75737c02017-11-06 10:37:17 -08004190 }
4191 }
4192 }
Steve Antoned10bd92017-12-05 10:52:59 -08004193
Steve Anton75737c02017-11-06 10:37:17 -08004194 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4195 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4196 if (sctp_transport_ && local_description() && remote_description() &&
4197 cricket::GetFirstDataContent(local_description()->description()) &&
4198 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004199 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004200 RTC_FROM_HERE,
4201 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004202 if (!success) {
4203 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4204 "Failed to push down SCTP parameters.");
4205 }
Steve Anton75737c02017-11-06 10:37:17 -08004206 }
Steve Antoned10bd92017-12-05 10:52:59 -08004207
Steve Anton8a006912017-12-04 15:25:56 -08004208 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004209}
4210
4211bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4212 RTC_DCHECK(network_thread()->IsCurrent());
4213 RTC_DCHECK(local_description());
4214 RTC_DCHECK(remote_description());
4215 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4216 // When we support "max-message-size", that would also be pushed down here.
4217 return sctp_transport_->Start(
4218 GetSctpPort(local_description()->description()),
4219 GetSctpPort(remote_description()->description()));
4220}
4221
Steve Anton8a006912017-12-04 15:25:56 -08004222RTCError PeerConnection::PushdownTransportDescription(
4223 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004224 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004225 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004226
Steve Anton8a006912017-12-04 15:25:56 -08004227 const SessionDescriptionInterface* sdesc =
4228 (source == cricket::CS_LOCAL ? local_description()
4229 : remote_description());
4230 RTC_DCHECK(sdesc);
4231 for (const cricket::TransportInfo& tinfo :
4232 sdesc->description()->transport_infos()) {
4233 std::string error;
4234 bool success;
4235 if (source == cricket::CS_LOCAL) {
4236 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004237 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004238 } else {
4239 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004240 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004241 }
4242 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004243 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4244 "Failed to push down transport description for " +
4245 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004246 }
4247 }
4248
Steve Anton8a006912017-12-04 15:25:56 -08004249 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004250}
4251
4252bool PeerConnection::GetTransportDescription(
4253 const SessionDescription* description,
4254 const std::string& content_name,
4255 cricket::TransportDescription* tdesc) {
4256 if (!description || !tdesc) {
4257 return false;
4258 }
4259 const TransportInfo* transport_info =
4260 description->GetTransportInfoByName(content_name);
4261 if (!transport_info) {
4262 return false;
4263 }
4264 *tdesc = transport_info->description;
4265 return true;
4266}
4267
4268bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4269 const std::string* first_content_name = bundle.FirstContentName();
4270 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004271 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004272 return false;
4273 }
4274 const std::string& transport_name = *first_content_name;
4275
4276 auto maybe_set_transport = [this, bundle,
4277 transport_name](cricket::BaseChannel* ch) {
4278 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004279 return;
Steve Anton75737c02017-11-06 10:37:17 -08004280 }
4281
4282 std::string old_transport_name = ch->transport_name();
4283 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004284 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4285 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004286 return;
Steve Anton75737c02017-11-06 10:37:17 -08004287 }
4288
4289 cricket::DtlsTransportInternal* rtp_dtls_transport =
4290 transport_controller_->CreateDtlsTransport(
4291 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4292 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4293 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4294 if (need_rtcp) {
4295 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4296 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4297 }
4298
4299 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004300 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4301 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004302 transport_controller_->DestroyDtlsTransport(
4303 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4304 // If the channel needs rtcp, it means that the channel used to have a
4305 // rtcp transport which needs to be deleted now.
4306 if (need_rtcp) {
4307 transport_controller_->DestroyDtlsTransport(
4308 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4309 }
Steve Anton75737c02017-11-06 10:37:17 -08004310 };
4311
Steve Antoned10bd92017-12-05 10:52:59 -08004312 for (auto transceiver : transceivers_) {
4313 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004314 }
Steve Antoned10bd92017-12-05 10:52:59 -08004315 maybe_set_transport(rtp_data_channel_);
4316
Steve Anton75737c02017-11-06 10:37:17 -08004317 // For SCTP, transport creation/deletion happens here instead of in the
4318 // object itself.
4319 if (sctp_transport_) {
4320 RTC_DCHECK(sctp_transport_name_);
4321 RTC_DCHECK(sctp_content_name_);
4322 if (transport_name != *sctp_transport_name_ &&
4323 bundle.HasContentName(*sctp_content_name_)) {
4324 network_thread()->Invoke<void>(
4325 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4326 transport_name));
4327 }
4328 }
4329
4330 return true;
4331}
4332
Steve Anton75737c02017-11-06 10:37:17 -08004333cricket::IceConfig PeerConnection::ParseIceConfig(
4334 const PeerConnectionInterface::RTCConfiguration& config) const {
4335 cricket::ContinualGatheringPolicy gathering_policy;
4336 // TODO(honghaiz): Add the third continual gathering policy in
4337 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4338 switch (config.continual_gathering_policy) {
4339 case PeerConnectionInterface::GATHER_ONCE:
4340 gathering_policy = cricket::GATHER_ONCE;
4341 break;
4342 case PeerConnectionInterface::GATHER_CONTINUALLY:
4343 gathering_policy = cricket::GATHER_CONTINUALLY;
4344 break;
4345 default:
4346 RTC_NOTREACHED();
4347 gathering_policy = cricket::GATHER_ONCE;
4348 }
4349 cricket::IceConfig ice_config;
4350 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4351 ice_config.prioritize_most_likely_candidate_pairs =
4352 config.prioritize_most_likely_ice_candidate_pairs;
4353 ice_config.backup_connection_ping_interval =
4354 config.ice_backup_candidate_pair_ping_interval;
4355 ice_config.continual_gathering_policy = gathering_policy;
4356 ice_config.presume_writable_when_fully_relayed =
4357 config.presume_writable_when_fully_relayed;
4358 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4359 ice_config.regather_all_networks_interval_range =
4360 config.ice_regather_interval_range;
4361 return ice_config;
4362}
4363
Steve Anton75737c02017-11-06 10:37:17 -08004364bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4365 std::string* track_id) {
4366 if (!local_description()) {
4367 return false;
4368 }
4369 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4370 track_id);
4371}
4372
4373bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4374 std::string* track_id) {
4375 if (!remote_description()) {
4376 return false;
4377 }
4378 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4379 track_id);
4380}
4381
4382bool PeerConnection::SendData(const cricket::SendDataParams& params,
4383 const rtc::CopyOnWriteBuffer& payload,
4384 cricket::SendDataResult* result) {
4385 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004386 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4387 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004388 return false;
4389 }
4390 return rtp_data_channel_
4391 ? rtp_data_channel_->SendData(params, payload, result)
4392 : network_thread()->Invoke<bool>(
4393 RTC_FROM_HERE,
4394 Bind(&cricket::SctpTransportInternal::SendData,
4395 sctp_transport_.get(), params, payload, result));
4396}
4397
4398bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4399 if (!rtp_data_channel_ && !sctp_transport_) {
4400 // Don't log an error here, because DataChannels are expected to call
4401 // ConnectDataChannel in this state. It's the only way to initially tell
4402 // whether or not the underlying transport is ready.
4403 return false;
4404 }
4405 if (rtp_data_channel_) {
4406 rtp_data_channel_->SignalReadyToSendData.connect(
4407 webrtc_data_channel, &DataChannel::OnChannelReady);
4408 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4409 &DataChannel::OnDataReceived);
4410 } else {
4411 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4412 &DataChannel::OnChannelReady);
4413 SignalSctpDataReceived.connect(webrtc_data_channel,
4414 &DataChannel::OnDataReceived);
4415 SignalSctpStreamClosedRemotely.connect(
4416 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4417 }
4418 return true;
4419}
4420
4421void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4422 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004423 RTC_LOG(LS_ERROR)
4424 << "DisconnectDataChannel called when rtp_data_channel_ and "
4425 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004426 return;
4427 }
4428 if (rtp_data_channel_) {
4429 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4430 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4431 } else {
4432 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4433 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4434 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4435 }
4436}
4437
4438void PeerConnection::AddSctpDataStream(int sid) {
4439 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004440 RTC_LOG(LS_ERROR)
4441 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004442 return;
4443 }
4444 network_thread()->Invoke<void>(
4445 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4446 sctp_transport_.get(), sid));
4447}
4448
4449void PeerConnection::RemoveSctpDataStream(int sid) {
4450 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004451 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4452 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004453 return;
4454 }
4455 network_thread()->Invoke<void>(
4456 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4457 sctp_transport_.get(), sid));
4458}
4459
4460bool PeerConnection::ReadyToSendData() const {
4461 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4462 sctp_ready_to_send_data_;
4463}
4464
4465std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4466 RTC_DCHECK(signaling_thread()->IsCurrent());
4467 ChannelNamePairs channel_name_pairs;
4468 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004469 channel_name_pairs.voice = ChannelNamePair(
4470 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004471 }
4472 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004473 channel_name_pairs.video = ChannelNamePair(
4474 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004475 }
4476 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004477 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004478 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004479 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004480 }
4481 if (sctp_transport_) {
4482 RTC_DCHECK(sctp_content_name_);
4483 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004484 channel_name_pairs.data =
4485 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004486 }
4487 return GetSessionStats(channel_name_pairs);
4488}
4489
4490std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4491 const ChannelNamePairs& channel_name_pairs) {
4492 if (network_thread()->IsCurrent()) {
4493 return GetSessionStats_n(channel_name_pairs);
4494 }
4495 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4496 RTC_FROM_HERE,
4497 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4498}
4499
4500bool PeerConnection::GetLocalCertificate(
4501 const std::string& transport_name,
4502 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4503 return transport_controller_->GetLocalCertificate(transport_name,
4504 certificate);
4505}
4506
4507std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4508 const std::string& transport_name) {
4509 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4510}
4511
4512cricket::DataChannelType PeerConnection::data_channel_type() const {
4513 return data_channel_type_;
4514}
4515
4516bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4517 return pending_ice_restarts_.find(content_name) !=
4518 pending_ice_restarts_.end();
4519}
4520
Steve Anton75737c02017-11-06 10:37:17 -08004521bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4522 return transport_controller_->NeedsIceRestart(content_name);
4523}
4524
4525void PeerConnection::OnCertificateReady(
4526 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4527 transport_controller_->SetLocalCertificate(certificate);
4528}
4529
4530void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004531 SetSessionError(SessionError::kTransport,
4532 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004533}
4534
4535void PeerConnection::OnTransportControllerConnectionState(
4536 cricket::IceConnectionState state) {
4537 switch (state) {
4538 case cricket::kIceConnectionConnecting:
4539 // If the current state is Connected or Completed, then there were
4540 // writable channels but now there are not, so the next state must
4541 // be Disconnected.
4542 // kIceConnectionConnecting is currently used as the default,
4543 // un-connected state by the TransportController, so its only use is
4544 // detecting disconnections.
4545 if (ice_connection_state_ ==
4546 PeerConnectionInterface::kIceConnectionConnected ||
4547 ice_connection_state_ ==
4548 PeerConnectionInterface::kIceConnectionCompleted) {
4549 SetIceConnectionState(
4550 PeerConnectionInterface::kIceConnectionDisconnected);
4551 }
4552 break;
4553 case cricket::kIceConnectionFailed:
4554 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4555 break;
4556 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004557 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4558 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004559 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4560 break;
4561 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004562 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4563 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004564 if (ice_connection_state_ !=
4565 PeerConnectionInterface::kIceConnectionConnected) {
4566 // If jumping directly from "checking" to "connected",
4567 // signal "connected" first.
4568 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4569 }
4570 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4571 if (metrics_observer()) {
4572 ReportTransportStats();
4573 }
4574 break;
4575 default:
4576 RTC_NOTREACHED();
4577 }
4578}
4579
4580void PeerConnection::OnTransportControllerCandidatesGathered(
4581 const std::string& transport_name,
4582 const cricket::Candidates& candidates) {
4583 RTC_DCHECK(signaling_thread()->IsCurrent());
4584 int sdp_mline_index;
4585 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004586 RTC_LOG(LS_ERROR)
4587 << "OnTransportControllerCandidatesGathered: content name "
4588 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004589 return;
4590 }
4591
4592 for (cricket::Candidates::const_iterator citer = candidates.begin();
4593 citer != candidates.end(); ++citer) {
4594 // Use transport_name as the candidate media id.
4595 std::unique_ptr<JsepIceCandidate> candidate(
4596 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4597 if (local_description()) {
4598 mutable_local_description()->AddCandidate(candidate.get());
4599 }
4600 OnIceCandidate(std::move(candidate));
4601 }
4602}
4603
4604void PeerConnection::OnTransportControllerCandidatesRemoved(
4605 const std::vector<cricket::Candidate>& candidates) {
4606 RTC_DCHECK(signaling_thread()->IsCurrent());
4607 // Sanity check.
4608 for (const cricket::Candidate& candidate : candidates) {
4609 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004610 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4611 << "empty content name in candidate "
4612 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004613 return;
4614 }
4615 }
4616
4617 if (local_description()) {
4618 mutable_local_description()->RemoveCandidates(candidates);
4619 }
4620 OnIceCandidatesRemoved(candidates);
4621}
4622
4623void PeerConnection::OnTransportControllerDtlsHandshakeError(
4624 rtc::SSLHandshakeError error) {
4625 if (metrics_observer()) {
4626 metrics_observer()->IncrementEnumCounter(
4627 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4628 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4629 }
4630}
4631
Steve Antoned10bd92017-12-05 10:52:59 -08004632void PeerConnection::EnableSending() {
4633 for (auto transceiver : transceivers_) {
4634 cricket::BaseChannel* channel = transceiver->internal()->channel();
4635 if (channel && !channel->enabled()) {
4636 channel->Enable(true);
4637 }
Steve Anton75737c02017-11-06 10:37:17 -08004638 }
4639
Steve Anton4171afb2017-11-20 10:20:22 -08004640 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004641 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004642 }
Steve Anton75737c02017-11-06 10:37:17 -08004643}
4644
4645// Returns the media index for a local ice candidate given the content name.
4646bool PeerConnection::GetLocalCandidateMediaIndex(
4647 const std::string& content_name,
4648 int* sdp_mline_index) {
4649 if (!local_description() || !sdp_mline_index) {
4650 return false;
4651 }
4652
4653 bool content_found = false;
4654 const ContentInfos& contents = local_description()->description()->contents();
4655 for (size_t index = 0; index < contents.size(); ++index) {
4656 if (contents[index].name == content_name) {
4657 *sdp_mline_index = static_cast<int>(index);
4658 content_found = true;
4659 break;
4660 }
4661 }
4662 return content_found;
4663}
4664
4665bool PeerConnection::UseCandidatesInSessionDescription(
4666 const SessionDescriptionInterface* remote_desc) {
4667 if (!remote_desc) {
4668 return true;
4669 }
4670 bool ret = true;
4671
4672 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4673 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4674 for (size_t n = 0; n < candidates->count(); ++n) {
4675 const IceCandidateInterface* candidate = candidates->at(n);
4676 bool valid = false;
4677 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4678 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004679 RTC_LOG(LS_INFO)
4680 << "UseCandidatesInSessionDescription: Not ready to use "
4681 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004682 }
4683 continue;
4684 }
4685 ret = UseCandidate(candidate);
4686 if (!ret) {
4687 break;
4688 }
4689 }
4690 }
4691 return ret;
4692}
4693
4694bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4695 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4696 size_t remote_content_size =
4697 remote_description()->description()->contents().size();
4698 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004699 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004700 return false;
4701 }
4702
4703 cricket::ContentInfo content =
4704 remote_description()->description()->contents()[mediacontent_index];
4705 std::vector<cricket::Candidate> candidates;
4706 candidates.push_back(candidate->candidate());
4707 // Invoking BaseSession method to handle remote candidates.
4708 std::string error;
4709 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4710 &error)) {
4711 // Candidates successfully submitted for checking.
4712 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4713 ice_connection_state_ ==
4714 PeerConnectionInterface::kIceConnectionDisconnected) {
4715 // If state is New, then the session has just gotten its first remote ICE
4716 // candidates, so go to Checking.
4717 // If state is Disconnected, the session is re-using old candidates or
4718 // receiving additional ones, so go to Checking.
4719 // If state is Connected, stay Connected.
4720 // TODO(bemasc): If state is Connected, and the new candidates are for a
4721 // newly added transport, then the state actually _should_ move to
4722 // checking. Add a way to distinguish that case.
4723 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4724 }
4725 // TODO(bemasc): If state is Completed, go back to Connected.
4726 } else {
4727 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004728 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004729 }
4730 }
4731 return true;
4732}
4733
4734void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004735 // Destroy video channel first since it may have a pointer to the
4736 // voice channel.
4737 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004738 if (!video_info || video_info->rejected) {
4739 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
4741
Steve Anton6fec8802017-12-04 10:37:29 -08004742 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4743 if (!audio_info || audio_info->rejected) {
4744 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004745 }
4746
4747 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4748 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004749 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004750 }
4751}
4752
Steve Antoneda6ccd2017-12-04 10:21:55 -08004753std::string PeerConnection::GetTransportNameForMediaSection(
4754 const std::string& mid,
4755 const cricket::ContentGroup* bundle_group) const {
4756 if (!bundle_group) {
4757 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004758 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004759 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004760 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004761 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004762 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004763 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004764 if (!bundle_group->HasContentName(mid)) {
4765 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4766 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004767 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004768 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4769 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004770}
4771
Steve Antondcc3c022017-12-22 16:02:54 -08004772RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4773 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004774 const cricket::ContentGroup* bundle_group = nullptr;
4775 if (configuration_.bundle_policy ==
4776 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004777 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004778 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004779 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4780 "max-bundle configured but session description "
4781 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004782 }
4783 }
Steve Antondcc3c022017-12-22 16:02:54 -08004784 return std::move(bundle_group);
4785}
4786
4787RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4788 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4789 if (!bundle_group_or_error.ok()) {
4790 return bundle_group_or_error.MoveError();
4791 }
4792 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004793
Steve Antoneda6ccd2017-12-04 10:21:55 -08004794 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004795 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004796 if (voice && !voice->rejected &&
4797 !GetAudioTransceiver()->internal()->channel()) {
4798 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4799 voice->name,
4800 GetTransportNameForMediaSection(voice->name, bundle_group));
4801 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004802 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4803 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004804 }
4805 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4806 }
4807
Steve Antondcc3c022017-12-22 16:02:54 -08004808 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004809 if (video && !video->rejected &&
4810 !GetVideoTransceiver()->internal()->channel()) {
4811 cricket::VideoChannel* video_channel = CreateVideoChannel(
4812 video->name,
4813 GetTransportNameForMediaSection(video->name, bundle_group));
4814 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004815 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4816 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004817 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004818 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004819 }
4820
Steve Antondcc3c022017-12-22 16:02:54 -08004821 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004822 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4823 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004824 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4825 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004826 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4827 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004828 }
4829 }
4830
Steve Anton8a006912017-12-04 15:25:56 -08004831 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004832}
4833
Steve Anton4171afb2017-11-20 10:20:22 -08004834// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004835cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4836 const std::string& mid,
4837 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004838 cricket::DtlsTransportInternal* rtp_dtls_transport =
4839 transport_controller_->CreateDtlsTransport(
4840 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4841 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4842 if (configuration_.rtcp_mux_policy !=
4843 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4844 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4845 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4846 }
4847
4848 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4849 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004850 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4851 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004852 if (!voice_channel) {
4853 transport_controller_->DestroyDtlsTransport(
4854 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4855 if (rtcp_dtls_transport) {
4856 transport_controller_->DestroyDtlsTransport(
4857 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4858 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004859 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004860 }
Steve Anton75737c02017-11-06 10:37:17 -08004861 voice_channel->SignalRtcpMuxFullyActive.connect(
4862 this, &PeerConnection::DestroyRtcpTransport_n);
4863 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4864 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004865 voice_channel->SignalSentPacket.connect(this,
4866 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004867
Steve Antoneda6ccd2017-12-04 10:21:55 -08004868 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004869}
4870
Steve Anton4171afb2017-11-20 10:20:22 -08004871// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004872cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4873 const std::string& mid,
4874 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004875 cricket::DtlsTransportInternal* rtp_dtls_transport =
4876 transport_controller_->CreateDtlsTransport(
4877 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4878 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4879 if (configuration_.rtcp_mux_policy !=
4880 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4881 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4882 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4883 }
4884
4885 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4886 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004887 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4888 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004889
4890 if (!video_channel) {
4891 transport_controller_->DestroyDtlsTransport(
4892 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4893 if (rtcp_dtls_transport) {
4894 transport_controller_->DestroyDtlsTransport(
4895 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4896 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004897 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004898 }
Steve Anton75737c02017-11-06 10:37:17 -08004899 video_channel->SignalRtcpMuxFullyActive.connect(
4900 this, &PeerConnection::DestroyRtcpTransport_n);
4901 video_channel->SignalDtlsSrtpSetupFailure.connect(
4902 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004903 video_channel->SignalSentPacket.connect(this,
4904 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004905
Steve Antoneda6ccd2017-12-04 10:21:55 -08004906 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004907}
4908
Steve Antoneda6ccd2017-12-04 10:21:55 -08004909bool PeerConnection::CreateDataChannel(const std::string& mid,
4910 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004911 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4912 if (sctp) {
4913 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004914 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004915 << "Trying to create SCTP transport, but didn't compile with "
4916 "SCTP support (HAVE_SCTP)";
4917 return false;
4918 }
4919 if (!network_thread()->Invoke<bool>(
4920 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004921 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004922 return false;
4923 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004924 for (const auto& channel : sctp_data_channels_) {
4925 channel->OnTransportChannelCreated();
4926 }
Steve Anton75737c02017-11-06 10:37:17 -08004927 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004928 cricket::DtlsTransportInternal* rtp_dtls_transport =
4929 transport_controller_->CreateDtlsTransport(
4930 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4931 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4932 if (configuration_.rtcp_mux_policy !=
4933 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4934 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4935 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4936 }
4937
4938 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4939 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004940 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004941
4942 if (!rtp_data_channel_) {
4943 transport_controller_->DestroyDtlsTransport(
4944 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4945 if (rtcp_dtls_transport) {
4946 transport_controller_->DestroyDtlsTransport(
4947 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4948 }
4949 return false;
4950 }
4951
4952 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4953 this, &PeerConnection::DestroyRtcpTransport_n);
4954 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4955 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4956 rtp_data_channel_->SignalSentPacket.connect(
4957 this, &PeerConnection::OnSentPacket_w);
4958 }
4959
Steve Anton75737c02017-11-06 10:37:17 -08004960 return true;
4961}
4962
4963Call::Stats PeerConnection::GetCallStats() {
4964 if (!worker_thread()->IsCurrent()) {
4965 return worker_thread()->Invoke<Call::Stats>(
4966 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4967 }
4968 if (call_) {
4969 return call_->GetStats();
4970 } else {
4971 return Call::Stats();
4972 }
4973}
4974
4975std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4976 const ChannelNamePairs& channel_name_pairs) {
4977 RTC_DCHECK(network_thread()->IsCurrent());
4978 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4979 for (const auto channel_name_pair :
4980 {&channel_name_pairs.voice, &channel_name_pairs.video,
4981 &channel_name_pairs.data}) {
4982 if (*channel_name_pair) {
4983 cricket::TransportStats transport_stats;
4984 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4985 &transport_stats)) {
4986 return nullptr;
4987 }
Steve Anton75737c02017-11-06 10:37:17 -08004988 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4989 std::move(transport_stats);
4990 }
4991 }
4992 return session_stats;
4993}
4994
4995bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4996 const std::string& transport_name) {
4997 RTC_DCHECK(network_thread()->IsCurrent());
4998 RTC_DCHECK(sctp_factory_);
4999 cricket::DtlsTransportInternal* tc =
5000 transport_controller_->CreateDtlsTransport_n(
5001 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5002 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5003 RTC_DCHECK(sctp_transport_);
5004 sctp_invoker_.reset(new rtc::AsyncInvoker());
5005 sctp_transport_->SignalReadyToSendData.connect(
5006 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5007 sctp_transport_->SignalDataReceived.connect(
5008 this, &PeerConnection::OnSctpTransportDataReceived_n);
5009 sctp_transport_->SignalStreamClosedRemotely.connect(
5010 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005011 sctp_transport_name_ = transport_name;
5012 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005013 return true;
5014}
5015
5016void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5017 RTC_DCHECK(network_thread()->IsCurrent());
5018 RTC_DCHECK(sctp_transport_);
5019 RTC_DCHECK(sctp_transport_name_);
5020 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005021 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005022 cricket::DtlsTransportInternal* tc =
5023 transport_controller_->CreateDtlsTransport_n(
5024 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5025 sctp_transport_->SetTransportChannel(tc);
5026 transport_controller_->DestroyDtlsTransport_n(
5027 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5028}
5029
5030void PeerConnection::DestroySctpTransport_n() {
5031 RTC_DCHECK(network_thread()->IsCurrent());
5032 sctp_transport_.reset(nullptr);
5033 sctp_content_name_.reset();
5034 sctp_transport_name_.reset();
5035 sctp_invoker_.reset(nullptr);
5036 sctp_ready_to_send_data_ = false;
5037}
5038
5039void PeerConnection::OnSctpTransportReadyToSendData_n() {
5040 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5041 RTC_DCHECK(network_thread()->IsCurrent());
5042 // Note: Cannot use rtc::Bind here because it will grab a reference to
5043 // PeerConnection and potentially cause PeerConnection to live longer than
5044 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5045 // be destroyed before PeerConnection is destroyed, and at that point all
5046 // pending tasks will be cleared.
5047 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5048 OnSctpTransportReadyToSendData_s(true);
5049 });
5050}
5051
5052void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5053 RTC_DCHECK(signaling_thread()->IsCurrent());
5054 sctp_ready_to_send_data_ = ready;
5055 SignalSctpReadyToSendData(ready);
5056}
5057
5058void PeerConnection::OnSctpTransportDataReceived_n(
5059 const cricket::ReceiveDataParams& params,
5060 const rtc::CopyOnWriteBuffer& payload) {
5061 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5062 RTC_DCHECK(network_thread()->IsCurrent());
5063 // Note: Cannot use rtc::Bind here because it will grab a reference to
5064 // PeerConnection and potentially cause PeerConnection to live longer than
5065 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5066 // be destroyed before PeerConnection is destroyed, and at that point all
5067 // pending tasks will be cleared.
5068 sctp_invoker_->AsyncInvoke<void>(
5069 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5070 OnSctpTransportDataReceived_s(params, payload);
5071 });
5072}
5073
5074void PeerConnection::OnSctpTransportDataReceived_s(
5075 const cricket::ReceiveDataParams& params,
5076 const rtc::CopyOnWriteBuffer& payload) {
5077 RTC_DCHECK(signaling_thread()->IsCurrent());
5078 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5079 // Received OPEN message; parse and signal that a new data channel should
5080 // be created.
5081 std::string label;
5082 InternalDataChannelInit config;
5083 config.id = params.ssrc;
5084 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005085 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5086 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005087 return;
5088 }
5089 config.open_handshake_role = InternalDataChannelInit::kAcker;
5090 OnDataChannelOpenMessage(label, config);
5091 } else {
5092 // Otherwise just forward the signal.
5093 SignalSctpDataReceived(params, payload);
5094 }
5095}
5096
5097void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5098 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5099 RTC_DCHECK(network_thread()->IsCurrent());
5100 sctp_invoker_->AsyncInvoke<void>(
5101 RTC_FROM_HERE, signaling_thread(),
5102 rtc::Bind(&sigslot::signal1<int>::operator(),
5103 &SignalSctpStreamClosedRemotely, sid));
5104}
5105
5106// Returns false if bundle is enabled and rtcp_mux is disabled.
5107bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5108 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5109 if (!bundle_enabled)
5110 return true;
5111
5112 const cricket::ContentGroup* bundle_group =
5113 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5114 RTC_DCHECK(bundle_group != NULL);
5115
5116 const cricket::ContentInfos& contents = desc->contents();
5117 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5118 citer != contents.end(); ++citer) {
5119 const cricket::ContentInfo* content = (&*citer);
5120 RTC_DCHECK(content != NULL);
5121 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005122 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005123 if (!HasRtcpMuxEnabled(content))
5124 return false;
5125 }
5126 }
5127 // RTCP-MUX is enabled in all the contents.
5128 return true;
5129}
5130
5131bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005132 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005133}
5134
Steve Anton8a006912017-12-04 15:25:56 -08005135RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005136 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005137 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005138 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005139 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
5141
5142 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005144 }
5145
Steve Anton3828c062017-12-06 10:34:51 -08005146 SdpType type = sdesc->GetType();
5147 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5148 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005149 LOG_AND_RETURN_ERROR(
5150 RTCErrorType::INVALID_PARAMETER,
5151 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005152 }
5153
5154 // Verify crypto settings.
5155 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005156 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5157 dtls_enabled_) {
5158 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
5159 if (!crypto_error.ok()) {
5160 return crypto_error;
5161 }
Steve Anton75737c02017-11-06 10:37:17 -08005162 }
5163
5164 // Verify ice-ufrag and ice-pwd.
5165 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005166 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5167 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005168 }
5169
5170 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005171 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5172 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005173 }
5174
5175 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5176 // m-lines that do not rtcp-mux enabled.
5177
5178 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005179 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005180 const cricket::SessionDescription* offer_desc =
5181 (source == cricket::CS_LOCAL) ? remote_description()->description()
5182 : local_description()->description();
5183 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5184 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005185 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5186 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005187 }
5188 } else {
5189 const cricket::SessionDescription* current_desc = nullptr;
5190 if (source == cricket::CS_LOCAL && local_description()) {
5191 current_desc = local_description()->description();
5192 } else if (source == cricket::CS_REMOTE && remote_description()) {
5193 current_desc = remote_description()->description();
5194 }
5195 // The re-offers should respect the order of m= sections in current
5196 // description. See RFC3264 Section 8 paragraph 4 for more details.
5197 if (current_desc &&
5198 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005199 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5200 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005201 }
5202 }
5203
Steve Anton8a006912017-12-04 15:25:56 -08005204 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005205}
5206
Steve Anton3828c062017-12-06 10:34:51 -08005207bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005208 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005209 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005210 return (state == PeerConnectionInterface::kStable) ||
5211 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005212 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005213 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005214 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5215 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5216 }
5217}
5218
Steve Anton3828c062017-12-06 10:34:51 -08005219bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005220 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005221 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005222 return (state == PeerConnectionInterface::kStable) ||
5223 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005224 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005225 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005226 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5227 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5228 }
5229}
5230
Steve Antonf8470812017-12-04 10:46:21 -08005231const char* PeerConnection::SessionErrorToString(SessionError error) const {
5232 switch (error) {
5233 case SessionError::kNone:
5234 return "ERROR_NONE";
5235 case SessionError::kContent:
5236 return "ERROR_CONTENT";
5237 case SessionError::kTransport:
5238 return "ERROR_TRANSPORT";
5239 }
5240 RTC_NOTREACHED();
5241 return "";
5242}
5243
Steve Anton75737c02017-11-06 10:37:17 -08005244std::string PeerConnection::GetSessionErrorMsg() {
5245 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005246 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5247 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005248 return desc.str();
5249}
5250
5251// We need to check the local/remote description for the Transport instead of
5252// the session, because a new Transport added during renegotiation may have
5253// them unset while the session has them set from the previous negotiation.
5254// Not doing so may trigger the auto generation of transport description and
5255// mess up DTLS identity information, ICE credential, etc.
5256bool PeerConnection::ReadyToUseRemoteCandidate(
5257 const IceCandidateInterface* candidate,
5258 const SessionDescriptionInterface* remote_desc,
5259 bool* valid) {
5260 *valid = true;
5261
5262 const SessionDescriptionInterface* current_remote_desc =
5263 remote_desc ? remote_desc : remote_description();
5264
5265 if (!current_remote_desc) {
5266 return false;
5267 }
5268
5269 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5270 size_t remote_content_size =
5271 current_remote_desc->description()->contents().size();
5272 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005273 RTC_LOG(LS_ERROR)
5274 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5275 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005276
5277 *valid = false;
5278 return false;
5279 }
5280
5281 cricket::ContentInfo content =
5282 current_remote_desc->description()->contents()[mediacontent_index];
5283
5284 const std::string transport_name = GetTransportName(content.name);
5285 if (transport_name.empty()) {
5286 return false;
5287 }
5288 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5289}
5290
5291bool PeerConnection::SrtpRequired() const {
5292 return dtls_enabled_ ||
5293 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5294}
5295
5296void PeerConnection::OnTransportControllerGatheringState(
5297 cricket::IceGatheringState state) {
5298 RTC_DCHECK(signaling_thread()->IsCurrent());
5299 if (state == cricket::kIceGatheringGathering) {
5300 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5301 } else if (state == cricket::kIceGatheringComplete) {
5302 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5303 }
5304}
5305
5306void PeerConnection::ReportTransportStats() {
5307 // Use a set so we don't report the same stats twice if two channels share
5308 // a transport.
5309 std::set<std::string> transport_names;
5310 if (voice_channel()) {
5311 transport_names.insert(voice_channel()->transport_name());
5312 }
5313 if (video_channel()) {
5314 transport_names.insert(video_channel()->transport_name());
5315 }
5316 if (rtp_data_channel()) {
5317 transport_names.insert(rtp_data_channel()->transport_name());
5318 }
5319 if (sctp_transport_name_) {
5320 transport_names.insert(*sctp_transport_name_);
5321 }
5322 for (const auto& name : transport_names) {
5323 cricket::TransportStats stats;
5324 if (transport_controller_->GetStats(name, &stats)) {
5325 ReportBestConnectionState(stats);
5326 ReportNegotiatedCiphers(stats);
5327 }
5328 }
5329}
5330// Walk through the ConnectionInfos to gather best connection usage
5331// for IPv4 and IPv6.
5332void PeerConnection::ReportBestConnectionState(
5333 const cricket::TransportStats& stats) {
5334 RTC_DCHECK(metrics_observer());
5335 for (cricket::TransportChannelStatsList::const_iterator it =
5336 stats.channel_stats.begin();
5337 it != stats.channel_stats.end(); ++it) {
5338 for (cricket::ConnectionInfos::const_iterator it_info =
5339 it->connection_infos.begin();
5340 it_info != it->connection_infos.end(); ++it_info) {
5341 if (!it_info->best_connection) {
5342 continue;
5343 }
5344
5345 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5346 const cricket::Candidate& local = it_info->local_candidate;
5347 const cricket::Candidate& remote = it_info->remote_candidate;
5348
5349 // Increment the counter for IceCandidatePairType.
5350 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5351 (local.type() == RELAY_PORT_TYPE &&
5352 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5353 type = kEnumCounterIceCandidatePairTypeTcp;
5354 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5355 type = kEnumCounterIceCandidatePairTypeUdp;
5356 } else {
5357 RTC_CHECK(0);
5358 }
5359 metrics_observer()->IncrementEnumCounter(
5360 type, GetIceCandidatePairCounter(local, remote),
5361 kIceCandidatePairMax);
5362
5363 // Increment the counter for IP type.
5364 if (local.address().family() == AF_INET) {
5365 metrics_observer()->IncrementEnumCounter(
5366 kEnumCounterAddressFamily, kBestConnections_IPv4,
5367 kPeerConnectionAddressFamilyCounter_Max);
5368
5369 } else if (local.address().family() == AF_INET6) {
5370 metrics_observer()->IncrementEnumCounter(
5371 kEnumCounterAddressFamily, kBestConnections_IPv6,
5372 kPeerConnectionAddressFamilyCounter_Max);
5373 } else {
5374 RTC_CHECK(0);
5375 }
5376
5377 return;
5378 }
5379 }
5380}
5381
5382void PeerConnection::ReportNegotiatedCiphers(
5383 const cricket::TransportStats& stats) {
5384 RTC_DCHECK(metrics_observer());
5385 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5386 return;
5387 }
5388
5389 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5390 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5391 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5392 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5393 return;
5394 }
5395
5396 PeerConnectionEnumCounterType srtp_counter_type;
5397 PeerConnectionEnumCounterType ssl_counter_type;
5398 if (stats.transport_name == cricket::CN_AUDIO) {
5399 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5400 ssl_counter_type = kEnumCounterAudioSslCipher;
5401 } else if (stats.transport_name == cricket::CN_VIDEO) {
5402 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5403 ssl_counter_type = kEnumCounterVideoSslCipher;
5404 } else if (stats.transport_name == cricket::CN_DATA) {
5405 srtp_counter_type = kEnumCounterDataSrtpCipher;
5406 ssl_counter_type = kEnumCounterDataSslCipher;
5407 } else {
5408 RTC_NOTREACHED();
5409 return;
5410 }
5411
5412 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5413 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5414 srtp_crypto_suite);
5415 }
5416 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5417 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5418 ssl_cipher_suite);
5419 }
5420}
5421
5422void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5423 RTC_DCHECK(worker_thread()->IsCurrent());
5424 RTC_DCHECK(call_);
5425 call_->OnSentPacket(sent_packet);
5426}
5427
5428const std::string PeerConnection::GetTransportName(
5429 const std::string& content_name) {
5430 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005431 if (channel) {
5432 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
Steve Anton6fec8802017-12-04 10:37:29 -08005434 if (sctp_transport_) {
5435 RTC_DCHECK(sctp_content_name_);
5436 RTC_DCHECK(sctp_transport_name_);
5437 if (content_name == *sctp_content_name_) {
5438 return *sctp_transport_name_;
5439 }
5440 }
5441 // Return an empty string if failed to retrieve the transport name.
5442 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005443}
5444
5445void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5446 RTC_DCHECK(network_thread()->IsCurrent());
5447 transport_controller_->DestroyDtlsTransport_n(
5448 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5449}
5450
Steve Anton6fec8802017-12-04 10:37:29 -08005451void PeerConnection::DestroyTransceiverChannel(
5452 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5453 transceiver) {
5454 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005455
Steve Anton6fec8802017-12-04 10:37:29 -08005456 cricket::BaseChannel* channel = transceiver->internal()->channel();
5457 if (channel) {
5458 transceiver->internal()->SetChannel(nullptr);
5459 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005460 }
5461}
5462
5463void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005464 if (rtp_data_channel_) {
5465 OnDataChannelDestroyed();
5466 DestroyBaseChannel(rtp_data_channel_);
5467 rtp_data_channel_ = nullptr;
5468 }
5469
5470 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5471 // grab a reference to this PeerConnection. If this is called from the
5472 // PeerConnection destructor, the RefCountedObject vtable will have already
5473 // been destroyed (since it is a subclass of PeerConnection) and using
5474 // rtc::Bind will cause "Pure virtual function called" error to appear.
5475
5476 if (sctp_transport_) {
5477 OnDataChannelDestroyed();
5478 network_thread()->Invoke<void>(RTC_FROM_HERE,
5479 [this] { DestroySctpTransport_n(); });
5480 }
5481}
5482
5483void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5484 RTC_DCHECK(channel);
5485 RTC_DCHECK(channel->rtp_dtls_transport());
5486
5487 // Need to cache these before destroying the base channel so that we do not
5488 // access uninitialized memory.
5489 const std::string transport_name =
5490 channel->rtp_dtls_transport()->transport_name();
5491 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5492
5493 switch (channel->media_type()) {
5494 case cricket::MEDIA_TYPE_AUDIO:
5495 channel_manager()->DestroyVoiceChannel(
5496 static_cast<cricket::VoiceChannel*>(channel));
5497 break;
5498 case cricket::MEDIA_TYPE_VIDEO:
5499 channel_manager()->DestroyVideoChannel(
5500 static_cast<cricket::VideoChannel*>(channel));
5501 break;
5502 case cricket::MEDIA_TYPE_DATA:
5503 channel_manager()->DestroyRtpDataChannel(
5504 static_cast<cricket::RtpDataChannel*>(channel));
5505 break;
5506 default:
5507 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5508 break;
5509 }
5510
5511 // |channel| can no longer be used.
5512
Steve Anton75737c02017-11-06 10:37:17 -08005513 transport_controller_->DestroyDtlsTransport(
5514 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5515 if (need_to_delete_rtcp) {
5516 transport_controller_->DestroyDtlsTransport(
5517 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5518 }
5519}
5520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005521} // namespace webrtc