blob: 01f31dd0dc7e09fc4bd05b4814f7eb383f7aaae8 [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 Anton75737c02017-11-06 10:37:17 -080014#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/jsepicecandidate.h"
19#include "api/jsepsessiondescription.h"
20#include "api/mediaconstraintsinterface.h"
21#include "api/mediastreamproxy.h"
22#include "api/mediastreamtrackproxy.h"
23#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020024#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "logging/rtc_event_log/rtc_event_log.h"
26#include "media/sctp/sctptransport.h"
27#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080028#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "pc/channelmanager.h"
30#include "pc/dtmfsender.h"
31#include "pc/mediastream.h"
32#include "pc/mediastreamobserver.h"
33#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080034#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "pc/rtpreceiver.h"
36#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080037#include "pc/sctputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/streamcollection.h"
39#include "pc/videocapturertracksource.h"
40#include "pc/videotrack.h"
41#include "rtc_base/bind.h"
42#include "rtc_base/checks.h"
43#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010044#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020045#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/stringencode.h"
47#include "rtc_base/stringutils.h"
48#include "rtc_base/trace_event.h"
49#include "system_wrappers/include/clock.h"
50#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
Steve Anton75737c02017-11-06 10:37:17 -080052using cricket::ContentInfo;
53using cricket::ContentInfos;
54using cricket::MediaContentDescription;
55using cricket::SessionDescription;
56using cricket::TransportInfo;
57
58using cricket::LOCAL_PORT_TYPE;
59using cricket::STUN_PORT_TYPE;
60using cricket::RELAY_PORT_TYPE;
61using cricket::PRFLX_PORT_TYPE;
62
Steve Antonba818672017-11-06 10:21:57 -080063namespace webrtc {
64
Steve Anton75737c02017-11-06 10:37:17 -080065// Error messages
66const char kBundleWithoutRtcpMux[] =
67 "rtcp-mux must be enabled when BUNDLE "
68 "is enabled.";
69const char kCreateChannelFailed[] = "Failed to create channels.";
70const char kInvalidCandidates[] = "Description contains invalid candidates.";
71const char kInvalidSdp[] = "Invalid session description.";
72const char kMlineMismatchInAnswer[] =
73 "The order of m-lines in answer doesn't match order in offer. Rejecting "
74 "answer.";
75const char kMlineMismatchInSubsequentOffer[] =
76 "The order of m-lines in subsequent offer doesn't match order from "
77 "previous offer/answer.";
78const char kPushDownTDFailed[] = "Failed to push down transport description:";
79const char kSdpWithoutDtlsFingerprint[] =
80 "Called with SDP without DTLS fingerprint.";
81const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
82const char kSdpWithoutIceUfragPwd[] =
83 "Called with SDP without ice-ufrag and ice-pwd.";
84const char kSessionError[] = "Session error code: ";
85const char kSessionErrorDesc[] = "Session error description: ";
86const char kDtlsSrtpSetupFailureRtp[] =
87 "Couldn't set up DTLS-SRTP on RTP channel.";
88const char kDtlsSrtpSetupFailureRtcp[] =
89 "Couldn't set up DTLS-SRTP on RTCP channel.";
90const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
Steve Anton75737c02017-11-06 10:37:17 -080092namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
deadbeefab9b2d12015-10-14 11:33:11 -070094static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080095static const char kDefaultAudioSenderId[] = "defaulta0";
96static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070097
zhihuang8f65cdf2016-05-06 18:40:30 -070098// The length of RTCP CNAMEs.
99static const int kRtcpCnameLength = 16;
100
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000102 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700104 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800106 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107};
108
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000109struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 explicit SetSessionDescriptionMsg(
111 webrtc::SetSessionDescriptionObserver* observer)
112 : observer(observer) {
113 }
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 std::string error;
117};
118
deadbeefab9b2d12015-10-14 11:33:11 -0700119struct CreateSessionDescriptionMsg : public rtc::MessageData {
120 explicit CreateSessionDescriptionMsg(
121 webrtc::CreateSessionDescriptionObserver* observer)
122 : observer(observer) {}
123
124 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
125 std::string error;
126};
127
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000128struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000129 GetStatsMsg(webrtc::StatsObserver* observer,
130 webrtc::MediaStreamTrackInterface* track)
131 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
deadbeefab9b2d12015-10-14 11:33:11 -0700137// Check if we can send |new_stream| on a PeerConnection.
138bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
139 webrtc::MediaStreamInterface* new_stream) {
140 if (!new_stream || !current_streams) {
141 return false;
142 }
143 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100144 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
145 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700146 return false;
147 }
148 return true;
149}
150
deadbeef5e97fb52015-10-15 12:49:08 -0700151// If the direction is "recvonly" or "inactive", treat the description
152// as containing no streams.
153// See: https://code.google.com/p/webrtc/issues/detail?id=5054
154std::vector<cricket::StreamParams> GetActiveStreams(
155 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800156 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700157 ? desc->streams()
158 : std::vector<cricket::StreamParams>();
159}
160
deadbeefab9b2d12015-10-14 11:33:11 -0700161bool IsValidOfferToReceiveMedia(int value) {
162 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
163 return (value >= Options::kUndefined) &&
164 (value <= Options::kMaxOfferToReceiveMedia);
165}
166
zhihuang1c378ed2017-08-17 14:10:50 -0700167// Add options to |[audio/video]_media_description_options| from |senders|.
168void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700169 const std::vector<rtc::scoped_refptr<
170 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700171 cricket::MediaDescriptionOptions* audio_media_description_options,
172 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700173 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
175 if (audio_media_description_options) {
176 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700177 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700178 }
179 } else {
180 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
181 if (video_media_description_options) {
182 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700186 }
zhihuang1c378ed2017-08-17 14:10:50 -0700187}
olka3c747662017-08-17 06:50:32 -0700188
zhihuang1c378ed2017-08-17 14:10:50 -0700189// Add options to |session_options| from |rtp_data_channels|.
190void AddRtpDataChannelOptions(
191 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
192 rtp_data_channels,
193 cricket::MediaDescriptionOptions* data_media_description_options) {
194 if (!data_media_description_options) {
195 return;
196 }
deadbeefab9b2d12015-10-14 11:33:11 -0700197 // Check for data channels.
198 for (const auto& kv : rtp_data_channels) {
199 const DataChannel* channel = kv.second;
200 if (channel->state() == DataChannel::kConnecting ||
201 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 // Legacy RTP data channels are signaled with the track/stream ID set to
203 // the data channel's label.
204 data_media_description_options->AddRtpDataChannel(channel->label(),
205 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700206 }
207 }
208}
209
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210uint32_t ConvertIceTransportTypeToCandidateFilter(
211 PeerConnectionInterface::IceTransportsType type) {
212 switch (type) {
213 case PeerConnectionInterface::kNone:
214 return cricket::CF_NONE;
215 case PeerConnectionInterface::kRelay:
216 return cricket::CF_RELAY;
217 case PeerConnectionInterface::kNoHost:
218 return (cricket::CF_ALL & ~cricket::CF_HOST);
219 case PeerConnectionInterface::kAll:
220 return cricket::CF_ALL;
221 default:
nissec80e7412017-01-11 05:56:46 -0800222 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223 }
224 return cricket::CF_NONE;
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
Steve Antonba818672017-11-06 10:21:57 -0800242std::string GetSignalingStateString(
243 PeerConnectionInterface::SignalingState state) {
244 switch (state) {
245 case PeerConnectionInterface::kStable:
246 return "kStable";
247 case PeerConnectionInterface::kHaveLocalOffer:
248 return "kHaveLocalOffer";
249 case PeerConnectionInterface::kHaveLocalPrAnswer:
250 return "kHavePrAnswer";
251 case PeerConnectionInterface::kHaveRemoteOffer:
252 return "kHaveRemoteOffer";
253 case PeerConnectionInterface::kHaveRemotePrAnswer:
254 return "kHaveRemotePrAnswer";
255 case PeerConnectionInterface::kClosed:
256 return "kClosed";
257 }
258 RTC_NOTREACHED();
259 return "";
260}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261
Steve Anton75737c02017-11-06 10:37:17 -0800262IceCandidatePairType GetIceCandidatePairCounter(
263 const cricket::Candidate& local,
264 const cricket::Candidate& remote) {
265 const auto& l = local.type();
266 const auto& r = remote.type();
267 const auto& host = LOCAL_PORT_TYPE;
268 const auto& srflx = STUN_PORT_TYPE;
269 const auto& relay = RELAY_PORT_TYPE;
270 const auto& prflx = PRFLX_PORT_TYPE;
271 if (l == host && r == host) {
272 bool local_private = IPIsPrivate(local.address().ipaddr());
273 bool remote_private = IPIsPrivate(remote.address().ipaddr());
274 if (local_private) {
275 if (remote_private) {
276 return kIceCandidatePairHostPrivateHostPrivate;
277 } else {
278 return kIceCandidatePairHostPrivateHostPublic;
279 }
280 } else {
281 if (remote_private) {
282 return kIceCandidatePairHostPublicHostPrivate;
283 } else {
284 return kIceCandidatePairHostPublicHostPublic;
285 }
286 }
287 }
288 if (l == host && r == srflx)
289 return kIceCandidatePairHostSrflx;
290 if (l == host && r == relay)
291 return kIceCandidatePairHostRelay;
292 if (l == host && r == prflx)
293 return kIceCandidatePairHostPrflx;
294 if (l == srflx && r == host)
295 return kIceCandidatePairSrflxHost;
296 if (l == srflx && r == srflx)
297 return kIceCandidatePairSrflxSrflx;
298 if (l == srflx && r == relay)
299 return kIceCandidatePairSrflxRelay;
300 if (l == srflx && r == prflx)
301 return kIceCandidatePairSrflxPrflx;
302 if (l == relay && r == host)
303 return kIceCandidatePairRelayHost;
304 if (l == relay && r == srflx)
305 return kIceCandidatePairRelaySrflx;
306 if (l == relay && r == relay)
307 return kIceCandidatePairRelayRelay;
308 if (l == relay && r == prflx)
309 return kIceCandidatePairRelayPrflx;
310 if (l == prflx && r == host)
311 return kIceCandidatePairPrflxHost;
312 if (l == prflx && r == srflx)
313 return kIceCandidatePairPrflxSrflx;
314 if (l == prflx && r == relay)
315 return kIceCandidatePairPrflxRelay;
316 return kIceCandidatePairMax;
317}
318
319// Verify that the order of media sections in |new_desc| matches
320// |existing_desc|. The number of m= sections in |new_desc| should be no less
321// than |existing_desc|.
322bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
323 const SessionDescription* new_desc) {
324 if (!existing_desc || !new_desc) {
325 return false;
326 }
327
328 if (existing_desc->contents().size() > new_desc->contents().size()) {
329 return false;
330 }
331
332 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
333 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
334 return false;
335 }
336 const MediaContentDescription* new_desc_mdesc =
337 static_cast<const MediaContentDescription*>(
338 new_desc->contents()[i].description);
339 const MediaContentDescription* existing_desc_mdesc =
340 static_cast<const MediaContentDescription*>(
341 existing_desc->contents()[i].description);
342 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
343 return false;
344 }
345 }
346 return true;
347}
348
349bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
350 const SessionDescription* desc2) {
351 if (!desc1 || !desc2) {
352 return false;
353 }
354 return desc1->contents().size() == desc2->contents().size();
355}
356
357// Checks that each non-rejected content has SDES crypto keys or a DTLS
358// fingerprint, unless it's in a BUNDLE group, in which case only the
359// BUNDLE-tag section (first media section/description in the BUNDLE group)
360// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
361// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
362// by Channel's |srtp_required| check.
363bool VerifyCrypto(const SessionDescription* desc,
364 bool dtls_enabled,
365 std::string* error) {
366 const cricket::ContentGroup* bundle =
367 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
368 const ContentInfos& contents = desc->contents();
369 for (size_t index = 0; index < contents.size(); ++index) {
370 const ContentInfo* cinfo = &contents[index];
371 if (cinfo->rejected) {
372 continue;
373 }
374 if (bundle && bundle->HasContentName(cinfo->name) &&
375 cinfo->name != *(bundle->FirstContentName())) {
376 // This isn't the first media section in the BUNDLE group, so it's not
377 // required to have crypto attributes, since only the crypto attributes
378 // from the first section actually get used.
379 continue;
380 }
381
382 // If the content isn't rejected or bundled into another m= section, crypto
383 // must be present.
384 const MediaContentDescription* media =
385 static_cast<const MediaContentDescription*>(cinfo->description);
386 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
387 if (!media || !tinfo) {
388 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100389 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800390 *error = kInvalidSdp;
391 return false;
392 }
393 if (dtls_enabled) {
394 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100395 RTC_LOG(LS_WARNING)
396 << "Session description must have DTLS fingerprint if "
397 "DTLS enabled.";
Steve Anton75737c02017-11-06 10:37:17 -0800398 *error = kSdpWithoutDtlsFingerprint;
399 return false;
400 }
401 } else {
402 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100403 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800404 << "Session description must have SDES when DTLS disabled.";
405 *error = kSdpWithoutSdesCrypto;
406 return false;
407 }
408 }
409 }
410
411 return true;
412}
413
414// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
415// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
416// media section/description in the BUNDLE group) needs a ufrag and pwd.
417bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
418 const cricket::ContentGroup* bundle =
419 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
420 const ContentInfos& contents = desc->contents();
421 for (size_t index = 0; index < contents.size(); ++index) {
422 const ContentInfo* cinfo = &contents[index];
423 if (cinfo->rejected) {
424 continue;
425 }
426 if (bundle && bundle->HasContentName(cinfo->name) &&
427 cinfo->name != *(bundle->FirstContentName())) {
428 // This isn't the first media section in the BUNDLE group, so it's not
429 // required to have ufrag/password, since only the ufrag/password from
430 // the first section actually get used.
431 continue;
432 }
433
434 // If the content isn't rejected or bundled into another m= section,
435 // ice-ufrag and ice-pwd must be present.
436 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
437 if (!tinfo) {
438 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800440 return false;
441 }
442 if (tinfo->description.ice_ufrag.empty() ||
443 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100444 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800445 return false;
446 }
447 }
448 return true;
449}
450
451bool GetTrackIdBySsrc(const SessionDescription* session_description,
452 uint32_t ssrc,
453 std::string* track_id) {
454 RTC_DCHECK(track_id != NULL);
455
456 const cricket::ContentInfo* audio_info =
457 cricket::GetFirstAudioContent(session_description);
458 if (audio_info) {
459 const cricket::MediaContentDescription* audio_content =
460 static_cast<const cricket::MediaContentDescription*>(
461 audio_info->description);
462
463 const auto* found =
464 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470
471 const cricket::ContentInfo* video_info =
472 cricket::GetFirstVideoContent(session_description);
473 if (video_info) {
474 const cricket::MediaContentDescription* video_content =
475 static_cast<const cricket::MediaContentDescription*>(
476 video_info->description);
477
478 const auto* found =
479 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
480 if (found) {
481 *track_id = found->id;
482 return true;
483 }
484 }
485 return false;
486}
487
488// Get the SCTP port out of a SessionDescription.
489// Return -1 if not found.
490int GetSctpPort(const SessionDescription* session_description) {
491 const ContentInfo* content_info = GetFirstDataContent(session_description);
492 RTC_DCHECK(content_info);
493 if (!content_info) {
494 return -1;
495 }
496 const cricket::DataContentDescription* data =
497 static_cast<const cricket::DataContentDescription*>(
498 (content_info->description));
499 std::string value;
500 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
501 cricket::kGoogleSctpDataCodecName);
502 for (const cricket::DataCodec& codec : data->codecs()) {
503 if (!codec.Matches(match_pattern)) {
504 continue;
505 }
506 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
507 return rtc::FromString<int>(value);
508 }
509 }
510 return -1;
511}
512
513bool BadSdp(const std::string& source,
514 const std::string& type,
515 const std::string& reason,
516 std::string* err_desc) {
517 std::ostringstream desc;
518 desc << "Failed to set " << source;
519 if (!type.empty()) {
520 desc << " " << type;
521 }
522 desc << " sdp: " << reason;
523
524 if (err_desc) {
525 *err_desc = desc.str();
526 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100527 RTC_LOG(LS_ERROR) << desc.str();
Steve Anton75737c02017-11-06 10:37:17 -0800528 return false;
529}
530
531bool BadSdp(cricket::ContentSource source,
532 const std::string& type,
533 const std::string& reason,
534 std::string* err_desc) {
535 if (source == cricket::CS_LOCAL) {
536 return BadSdp("local", type, reason, err_desc);
537 } else {
538 return BadSdp("remote", type, reason, err_desc);
539 }
540}
541
542bool BadLocalSdp(const std::string& type,
543 const std::string& reason,
544 std::string* err_desc) {
545 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
546}
547
548bool BadRemoteSdp(const std::string& type,
549 const std::string& reason,
550 std::string* err_desc) {
551 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
552}
553
554bool BadOfferSdp(cricket::ContentSource source,
555 const std::string& reason,
556 std::string* err_desc) {
557 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
558}
559
560bool BadPranswerSdp(cricket::ContentSource source,
561 const std::string& reason,
562 std::string* err_desc) {
563 return BadSdp(source, SessionDescriptionInterface::kPrAnswer, reason,
564 err_desc);
565}
566
567bool BadAnswerSdp(cricket::ContentSource source,
568 const std::string& reason,
569 std::string* err_desc) {
570 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
571}
572
573std::string BadStateErrMsg(PeerConnectionInterface::SignalingState state) {
574 std::ostringstream desc;
575 desc << "Called in wrong state: " << GetSignalingStateString(state);
576 return desc.str();
577}
578
579#define GET_STRING_OF_ERROR_CODE(err) \
580 case webrtc::PeerConnection::err: \
581 result = #err; \
582 break;
583
584std::string GetErrorCodeString(webrtc::PeerConnection::Error err) {
585 std::string result;
586 switch (err) {
587 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
588 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
589 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
590 default:
591 RTC_NOTREACHED();
592 break;
593 }
594 return result;
595}
596
597std::string MakeErrorString(const std::string& error, const std::string& desc) {
598 std::ostringstream ret;
599 ret << error << " " << desc;
600 return ret.str();
601}
602
603std::string MakeTdErrorString(const std::string& desc) {
604 return MakeErrorString(kPushDownTDFailed, desc);
605}
606
607// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
608bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
609 const SessionDescriptionInterface* new_desc,
610 const std::string& content_name) {
611 if (!old_desc) {
612 return false;
613 }
614 const SessionDescription* new_sd = new_desc->description();
615 const SessionDescription* old_sd = old_desc->description();
616 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
617 if (!cinfo || cinfo->rejected) {
618 return false;
619 }
620 // If the content isn't rejected, check if ufrag and password has changed.
621 const cricket::TransportDescription* new_transport_desc =
622 new_sd->GetTransportDescriptionByName(content_name);
623 const cricket::TransportDescription* old_transport_desc =
624 old_sd->GetTransportDescriptionByName(content_name);
625 if (!new_transport_desc || !old_transport_desc) {
626 // No transport description exists. This is not an ICE restart.
627 return false;
628 }
629 if (cricket::IceCredentialsChanged(
630 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
631 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100632 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
633 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800634 return true;
635 }
636 return false;
637}
638
639} // namespace
640
Henrik Boström31638672017-11-23 17:48:32 +0100641// Upon completion, posts a task to execute the callback of the
642// SetSessionDescriptionObserver asynchronously on the same thread. At this
643// point, the state of the peer connection might no longer reflect the effects
644// of the SetRemoteDescription operation, as the peer connection could have been
645// modified during the post.
646// TODO(hbos): Remove this class once we remove the version of
647// PeerConnectionInterface::SetRemoteDescription() that takes a
648// SetSessionDescriptionObserver as an argument.
649class PeerConnection::SetRemoteDescriptionObserverAdapter
650 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
651 public:
652 SetRemoteDescriptionObserverAdapter(
653 rtc::scoped_refptr<PeerConnection> pc,
654 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
655 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
656
657 // SetRemoteDescriptionObserverInterface implementation.
658 void OnSetRemoteDescriptionComplete(RTCError error) override {
659 if (error.ok())
660 pc_->PostSetSessionDescriptionSuccess(wrapper_);
661 else
662 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
663 }
664
665 private:
666 rtc::scoped_refptr<PeerConnection> pc_;
667 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
668};
669
deadbeef293e9262017-01-11 12:28:30 -0800670bool PeerConnectionInterface::RTCConfiguration::operator==(
671 const PeerConnectionInterface::RTCConfiguration& o) const {
672 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700673 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800674 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000675 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800677 BundlePolicy bundle_policy;
678 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700679 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
680 int ice_candidate_pool_size;
681 bool disable_ipv6;
682 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700683 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700684 bool enable_rtp_data_channel;
685 rtc::Optional<int> screencast_min_bitrate;
686 rtc::Optional<bool> combined_audio_video_bwe;
687 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800688 TcpCandidatePolicy tcp_candidate_policy;
689 CandidateNetworkPolicy candidate_network_policy;
690 int audio_jitter_buffer_max_packets;
691 bool audio_jitter_buffer_fast_accelerate;
692 int ice_connection_receiving_timeout;
693 int ice_backup_candidate_pair_ping_interval;
694 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800695 bool prioritize_most_likely_ice_candidate_pairs;
696 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800697 bool prune_turn_ports;
698 bool presume_writable_when_fully_relayed;
699 bool enable_ice_renomination;
700 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800701 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700702 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200703 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800704 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800705 };
706 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
707 "Did you add something to RTCConfiguration and forget to "
708 "update operator==?");
709 return type == o.type && servers == o.servers &&
710 bundle_policy == o.bundle_policy &&
711 rtcp_mux_policy == o.rtcp_mux_policy &&
712 tcp_candidate_policy == o.tcp_candidate_policy &&
713 candidate_network_policy == o.candidate_network_policy &&
714 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
715 audio_jitter_buffer_fast_accelerate ==
716 o.audio_jitter_buffer_fast_accelerate &&
717 ice_connection_receiving_timeout ==
718 o.ice_connection_receiving_timeout &&
719 ice_backup_candidate_pair_ping_interval ==
720 o.ice_backup_candidate_pair_ping_interval &&
721 continual_gathering_policy == o.continual_gathering_policy &&
722 certificates == o.certificates &&
723 prioritize_most_likely_ice_candidate_pairs ==
724 o.prioritize_most_likely_ice_candidate_pairs &&
725 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800726 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700727 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800728 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800729 screencast_min_bitrate == o.screencast_min_bitrate &&
730 combined_audio_video_bwe == o.combined_audio_video_bwe &&
731 enable_dtls_srtp == o.enable_dtls_srtp &&
732 ice_candidate_pool_size == o.ice_candidate_pool_size &&
733 prune_turn_ports == o.prune_turn_ports &&
734 presume_writable_when_fully_relayed ==
735 o.presume_writable_when_fully_relayed &&
736 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800737 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200739 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800740 turn_customizer == o.turn_customizer &&
741 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800742}
743
744bool PeerConnectionInterface::RTCConfiguration::operator!=(
745 const PeerConnectionInterface::RTCConfiguration& o) const {
746 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800747}
748
zhihuang8f65cdf2016-05-06 18:40:30 -0700749// Generate a RTCP CNAME when a PeerConnection is created.
750std::string GenerateRtcpCname() {
751 std::string cname;
752 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800754 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700755 }
756 return cname;
757}
758
zhihuang1c378ed2017-08-17 14:10:50 -0700759bool ValidateOfferAnswerOptions(
760 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
761 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
762 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700763}
764
zhihuang1c378ed2017-08-17 14:10:50 -0700765// From |rtc_options|, fill parts of |session_options| shared by all generated
766// m= sections (in other words, nothing that involves a map/array).
767void ExtractSharedMediaSessionOptions(
768 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
769 cricket::MediaSessionOptions* session_options) {
770 session_options->vad_enabled = rtc_options.voice_activity_detection;
771 session_options->bundle_enabled = rtc_options.use_rtp_mux;
772}
zhihuanga77e6bb2017-08-14 18:17:48 -0700773
zhihuang1c378ed2017-08-17 14:10:50 -0700774bool ConvertConstraintsToOfferAnswerOptions(
775 const MediaConstraintsInterface* constraints,
776 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700777 if (!constraints) {
778 return true;
779 }
zhihuang1c378ed2017-08-17 14:10:50 -0700780
781 bool value = false;
782 size_t mandatory_constraints_satisfied = 0;
783
784 if (FindConstraint(constraints,
785 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
786 &mandatory_constraints_satisfied)) {
787 offer_answer_options->offer_to_receive_audio =
788 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
789 kOfferToReceiveMediaTrue
790 : 0;
791 }
792
793 if (FindConstraint(constraints,
794 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
795 &mandatory_constraints_satisfied)) {
796 offer_answer_options->offer_to_receive_video =
797 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
798 kOfferToReceiveMediaTrue
799 : 0;
800 }
801 if (FindConstraint(constraints,
802 MediaConstraintsInterface::kVoiceActivityDetection, &value,
803 &mandatory_constraints_satisfied)) {
804 offer_answer_options->voice_activity_detection = value;
805 }
806 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->use_rtp_mux = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
811 &value, &mandatory_constraints_satisfied)) {
812 offer_answer_options->ice_restart = value;
813 }
814
deadbeefab9b2d12015-10-14 11:33:11 -0700815 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
816}
817
zhihuang38ede132017-06-15 12:52:32 -0700818PeerConnection::PeerConnection(PeerConnectionFactory* factory,
819 std::unique_ptr<RtcEventLog> event_log,
820 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700822 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700823 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700824 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700825 remote_streams_(StreamCollection::Create()),
826 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827
828PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100829 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800830 RTC_DCHECK_RUN_ON(signaling_thread());
831
832 // Need to detach RTP transceivers from PeerConnection, since it's about to be
833 // destroyed.
834 for (auto transceiver : transceivers_) {
835 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700836 }
Steve Anton4171afb2017-11-20 10:20:22 -0800837
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700838 // Destroy stats_ because it depends on session_.
839 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800840 if (stats_collector_) {
841 stats_collector_->WaitForPendingRequest();
842 stats_collector_ = nullptr;
843 }
Steve Anton75737c02017-11-06 10:37:17 -0800844
845 // Destroy video channels first since they may have a pointer to a voice
846 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800847 for (auto transceiver : transceivers_) {
848 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO &&
849 transceiver->internal()->channel()) {
850 DestroyVideoChannel(static_cast<cricket::VideoChannel*>(
851 transceiver->internal()->channel()));
852 }
Steve Anton75737c02017-11-06 10:37:17 -0800853 }
Steve Anton4171afb2017-11-20 10:20:22 -0800854 for (auto transceiver : transceivers_) {
855 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO &&
856 transceiver->internal()->channel()) {
857 DestroyVoiceChannel(static_cast<cricket::VoiceChannel*>(
858 transceiver->internal()->channel()));
859 }
Steve Anton75737c02017-11-06 10:37:17 -0800860 }
861 if (rtp_data_channel_) {
862 DestroyDataChannel();
863 }
864
865 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
866 // grab a reference to this PeerConnection. The RefCountedObject vtable will
867 // have already been destroyed (since it is a subclass of PeerConnection) and
868 // using rtc::Bind will cause "Pure virtual function called" error to appear.
869
870 if (sctp_transport_) {
871 OnDataChannelDestroyed();
872 network_thread()->Invoke<void>(RTC_FROM_HERE,
873 [this] { DestroySctpTransport_n(); });
874 }
875
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800877
878 webrtc_session_desc_factory_.reset();
879 sctp_invoker_.reset();
880 sctp_factory_.reset();
881 transport_controller_.reset();
882
deadbeef91dd5672016-05-18 16:55:30 -0700883 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700884 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700885 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700886 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700887 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700888 call_.reset();
889 event_log_.reset();
890 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891}
892
893bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000894 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700895 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200896 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800897 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100898 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700899
900 RTCError config_error = ValidateConfiguration(configuration);
901 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700903 return false;
904 }
905
deadbeef293e9262017-01-11 12:28:30 -0800906 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR)
908 << "PeerConnection initialized without a PortAllocator? "
909 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800910 return false;
911 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200912
deadbeef653b8e02015-11-11 12:55:10 -0800913 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800914 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100915 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
916 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800917 return false;
918 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000919 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800920 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800921
deadbeef91dd5672016-05-18 16:55:30 -0700922 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700923 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700924 if (!network_thread()->Invoke<bool>(
925 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
926 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 return false;
928 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929
Steve Anton75737c02017-11-06 10:37:17 -0800930 // RFC 3264: The numeric value of the session id and version in the
931 // o line MUST be representable with a "64 bit signed integer".
932 // Due to this constraint session id |session_id_| is max limited to
933 // LLONG_MAX.
934 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
935 transport_controller_.reset(factory_->CreateTransportController(
936 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
937 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
938 transport_controller_->SignalConnectionState.connect(
939 this, &PeerConnection::OnTransportControllerConnectionState);
940 transport_controller_->SignalGatheringState.connect(
941 this, &PeerConnection::OnTransportControllerGatheringState);
942 transport_controller_->SignalCandidatesGathered.connect(
943 this, &PeerConnection::OnTransportControllerCandidatesGathered);
944 transport_controller_->SignalCandidatesRemoved.connect(
945 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
946 transport_controller_->SignalDtlsHandshakeError.connect(
947 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
948
949 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700950
deadbeefab9b2d12015-10-14 11:33:11 -0700951 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700952 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953
Steve Antonba818672017-11-06 10:21:57 -0800954 configuration_ = configuration;
955
Steve Anton75737c02017-11-06 10:37:17 -0800956 const PeerConnectionFactoryInterface::Options& options = factory_->options();
957
958 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
959
960 // Obtain a certificate from RTCConfiguration if any were provided (optional).
961 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
962 if (!configuration.certificates.empty()) {
963 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
964 // just picking the first one. The decision should be made based on the DTLS
965 // handshake. The DTLS negotiations need to know about all certificates.
966 certificate = configuration.certificates[0];
967 }
968
Steve Antond25da372017-11-06 14:50:29 -0800969 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800970
971 if (options.disable_encryption) {
972 dtls_enabled_ = false;
973 } else {
974 // Enable DTLS by default if we have an identity store or a certificate.
975 dtls_enabled_ = (cert_generator || certificate);
976 // |configuration| can override the default |dtls_enabled_| value.
977 if (configuration.enable_dtls_srtp) {
978 dtls_enabled_ = *(configuration.enable_dtls_srtp);
979 }
980 }
981
982 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
983 // It takes precendence over the disable_sctp_data_channels
984 // PeerConnectionFactoryInterface::Options.
985 if (configuration.enable_rtp_data_channel) {
986 data_channel_type_ = cricket::DCT_RTP;
987 } else {
988 // DTLS has to be enabled to use SCTP.
989 if (!options.disable_sctp_data_channels && dtls_enabled_) {
990 data_channel_type_ = cricket::DCT_SCTP;
991 }
992 }
993
994 video_options_.screencast_min_bitrate_kbps =
995 configuration.screencast_min_bitrate;
996 audio_options_.combined_audio_video_bwe =
997 configuration.combined_audio_video_bwe;
998
999 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001000 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001001
1002 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 // Whether the certificate generator/certificate is null or not determines
1006 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1007 // the right instructions by clearing the variables if needed.
1008 if (!dtls_enabled_) {
1009 cert_generator.reset();
1010 certificate = nullptr;
1011 } else if (certificate) {
1012 // Favor generated certificate over the certificate generator.
1013 cert_generator.reset();
1014 }
1015
1016 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1017 signaling_thread(), channel_manager(), this, session_id(),
1018 std::move(cert_generator), certificate));
1019 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1020 this, &PeerConnection::OnCertificateReady);
1021
1022 if (options.disable_encryption) {
1023 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1024 }
1025
1026 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1027 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
Steve Anton4171afb2017-11-20 10:20:22 -08001029 // Add default audio/video transceivers for Plan B SDP.
1030 if (!IsUnifiedPlan()) {
1031 transceivers_.push_back(
1032 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1033 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1037 }
1038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 return true;
1040}
1041
Steve Anton038834f2017-07-14 15:59:59 -07001042RTCError PeerConnection::ValidateConfiguration(
1043 const RTCConfiguration& config) const {
1044 if (config.ice_regather_interval_range &&
1045 config.continual_gathering_policy == GATHER_ONCE) {
1046 return RTCError(RTCErrorType::INVALID_PARAMETER,
1047 "ice_regather_interval_range specified but continual "
1048 "gathering policy is GATHER_ONCE");
1049 }
1050 return RTCError::OK();
1051}
1052
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001053rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001055 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056}
1057
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001058rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001060 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061}
1062
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001063bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001064 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 if (IsClosed()) {
1066 return false;
1067 }
deadbeefab9b2d12015-10-14 11:33:11 -07001068 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001069 return false;
1070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071
1072 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001073 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1074 observer->SignalAudioTrackAdded.connect(this,
1075 &PeerConnection::OnAudioTrackAdded);
1076 observer->SignalAudioTrackRemoved.connect(
1077 this, &PeerConnection::OnAudioTrackRemoved);
1078 observer->SignalVideoTrackAdded.connect(this,
1079 &PeerConnection::OnVideoTrackAdded);
1080 observer->SignalVideoTrackRemoved.connect(
1081 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001082 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001083
deadbeefab9b2d12015-10-14 11:33:11 -07001084 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001085 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
1087 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001088 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001089 }
1090
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001091 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 observer_->OnRenegotiationNeeded();
1093 return true;
1094}
1095
1096void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001097 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001098 if (!IsClosed()) {
1099 for (const auto& track : local_stream->GetAudioTracks()) {
1100 RemoveAudioTrack(track.get(), local_stream);
1101 }
1102 for (const auto& track : local_stream->GetVideoTracks()) {
1103 RemoveVideoTrack(track.get(), local_stream);
1104 }
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
deadbeefab9b2d12015-10-14 11:33:11 -07001106 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001107 stream_observers_.erase(
1108 std::remove_if(
1109 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001110 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001111 return observer->stream()->label().compare(local_stream->label()) ==
1112 0;
1113 }),
1114 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001115
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116 if (IsClosed()) {
1117 return;
1118 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 observer_->OnRenegotiationNeeded();
1120}
1121
deadbeefe1f9d832016-01-14 15:35:42 -08001122rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1123 MediaStreamTrackInterface* track,
1124 std::vector<MediaStreamInterface*> streams) {
1125 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1126 if (IsClosed()) {
1127 return nullptr;
1128 }
1129 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001130 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001131 << "Adding a track with two streams is not currently supported.";
1132 return nullptr;
1133 }
Steve Anton4171afb2017-11-20 10:20:22 -08001134 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001135 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1136 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001137 return nullptr;
1138 }
1139
1140 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001141 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001142 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001143 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001144 signaling_thread(),
1145 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001146 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001147 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001148 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001149 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001150 }
Steve Anton4171afb2017-11-20 10:20:22 -08001151 const RtpSenderInfo* sender_info =
1152 FindSenderInfo(local_audio_sender_infos_,
1153 new_sender->internal()->stream_id(), track->id());
1154 if (sender_info) {
1155 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001156 }
1157 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001158 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001159 signaling_thread(),
1160 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001161 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001162 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001163 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001164 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 const RtpSenderInfo* sender_info =
1167 FindSenderInfo(local_video_sender_infos_,
1168 new_sender->internal()->stream_id(), track->id());
1169 if (sender_info) {
1170 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001171 }
1172 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001173 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1174 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001175 return rtc::scoped_refptr<RtpSenderInterface>();
1176 }
1177
deadbeefe1f9d832016-01-14 15:35:42 -08001178 observer_->OnRenegotiationNeeded();
1179 return new_sender;
1180}
1181
1182bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1183 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1184 if (IsClosed()) {
1185 return false;
1186 }
1187
Steve Anton4171afb2017-11-20 10:20:22 -08001188 bool removed;
1189 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1190 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1191 } else {
1192 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1193 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1194 }
1195 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001196 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1197 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001198 return false;
1199 }
deadbeefe1f9d832016-01-14 15:35:42 -08001200
1201 observer_->OnRenegotiationNeeded();
1202 return true;
1203}
1204
Steve Anton9158ef62017-11-27 13:01:52 -08001205RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1206PeerConnection::AddTransceiver(
1207 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1208 return AddTransceiver(track, RtpTransceiverInit());
1209}
1210
1211RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1212PeerConnection::AddTransceiver(
1213 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1214 const RtpTransceiverInit& init) {
1215 if (!IsUnifiedPlan()) {
1216 LOG_AND_RETURN_ERROR(
1217 RTCErrorType::INTERNAL_ERROR,
1218 "AddTransceiver only supported when Unified Plan is enabled.");
1219 }
1220 if (!track) {
1221 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1222 }
1223 cricket::MediaType media_type;
1224 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1225 media_type = cricket::MEDIA_TYPE_AUDIO;
1226 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1227 media_type = cricket::MEDIA_TYPE_VIDEO;
1228 } else {
1229 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1230 "Track kind is not audio or video");
1231 }
1232 return AddTransceiver(media_type, track, init);
1233}
1234
1235RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1236PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1237 return AddTransceiver(media_type, RtpTransceiverInit());
1238}
1239
1240RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1241PeerConnection::AddTransceiver(cricket::MediaType media_type,
1242 const RtpTransceiverInit& init) {
1243 if (!IsUnifiedPlan()) {
1244 LOG_AND_RETURN_ERROR(
1245 RTCErrorType::INTERNAL_ERROR,
1246 "AddTransceiver only supported when Unified Plan is enabled.");
1247 }
1248 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1249 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1250 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1251 "media type is not audio or video");
1252 }
1253 return AddTransceiver(media_type, nullptr, init);
1254}
1255
1256RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1257PeerConnection::AddTransceiver(
1258 cricket::MediaType media_type,
1259 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1260 const RtpTransceiverInit& init) {
1261 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1262 media_type == cricket::MEDIA_TYPE_VIDEO));
1263 if (track) {
1264 RTC_DCHECK_EQ(media_type,
1265 (track->kind() == MediaStreamTrackInterface::kAudioKind
1266 ? cricket::MEDIA_TYPE_AUDIO
1267 : cricket::MEDIA_TYPE_VIDEO));
1268 }
1269
1270 // TODO(bugs.webrtc.org/7600): Verify init.
1271
1272 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1273 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1274 receiver;
1275 std::string receiver_id = rtc::CreateRandomUuid();
1276 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1277 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1278 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1279 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1280 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1281 } else {
1282 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1283 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1284 signaling_thread(), new VideoRtpSender(nullptr));
1285 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1286 signaling_thread(),
1287 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1288 }
1289 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1290 // channel prevents users from calling SetParameters on them, which is needed
1291 // to be in compliance with the spec.
1292
1293 if (track) {
1294 sender->SetTrack(track);
1295 }
1296
1297 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1298 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1299 signaling_thread(), new RtpTransceiver(sender, receiver));
1300 transceiver->SetDirection(init.direction);
1301
1302 transceivers_.push_back(transceiver);
1303
1304 observer_->OnRenegotiationNeeded();
1305
1306 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1307}
1308
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001309rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001311 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001312 if (IsClosed()) {
1313 return nullptr;
1314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001316 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001317 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 }
Steve Anton4171afb2017-11-20 10:20:22 -08001319 auto track_sender = FindSenderForTrack(track);
1320 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001321 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001322 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 }
1324
Steve Anton4171afb2017-11-20 10:20:22 -08001325 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326}
1327
deadbeeffac06552015-11-25 11:26:01 -08001328rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001329 const std::string& kind,
1330 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001331 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001332 if (IsClosed()) {
1333 return nullptr;
1334 }
Steve Anton4171afb2017-11-20 10:20:22 -08001335
1336 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001337 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001338 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001339 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001340 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001341 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001342 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001343 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001344 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001345 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001346 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001347 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001348 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001349 }
Steve Anton4171afb2017-11-20 10:20:22 -08001350
deadbeefbd7d8f72015-12-18 16:58:44 -08001351 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001352 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001353 }
Steve Anton4171afb2017-11-20 10:20:22 -08001354
deadbeefe1f9d832016-01-14 15:35:42 -08001355 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001356}
1357
deadbeef70ab1a12015-09-28 16:53:55 -07001358std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1359 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001360 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001361 for (auto sender : GetSendersInternal()) {
1362 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001363 }
1364 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001365}
1366
Steve Anton4171afb2017-11-20 10:20:22 -08001367std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1368PeerConnection::GetSendersInternal() const {
1369 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1370 all_senders;
1371 for (auto transceiver : transceivers_) {
1372 auto senders = transceiver->internal()->senders();
1373 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1374 }
1375 return all_senders;
1376}
1377
deadbeef70ab1a12015-09-28 16:53:55 -07001378std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1379PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001380 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001381 for (const auto& receiver : GetReceiversInternal()) {
1382 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001383 }
1384 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001385}
1386
Steve Anton4171afb2017-11-20 10:20:22 -08001387std::vector<
1388 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1389PeerConnection::GetReceiversInternal() const {
1390 std::vector<
1391 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1392 all_receivers;
1393 for (auto transceiver : transceivers_) {
1394 auto receivers = transceiver->internal()->receivers();
1395 all_receivers.insert(all_receivers.end(), receivers.begin(),
1396 receivers.end());
1397 }
1398 return all_receivers;
1399}
1400
Steve Anton9158ef62017-11-27 13:01:52 -08001401std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1402PeerConnection::GetTransceivers() const {
1403 RTC_DCHECK(IsUnifiedPlan());
1404 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1405 for (auto transceiver : transceivers_) {
1406 all_transceivers.push_back(transceiver);
1407 }
1408 return all_transceivers;
1409}
1410
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001412 MediaStreamTrackInterface* track,
1413 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001414 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001415 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001416 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001417 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 return false;
1419 }
1420
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001421 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001422 // The StatsCollector is used to tell if a track is valid because it may
1423 // remember tracks that the PeerConnection previously removed.
1424 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001425 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1426 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001427 return false;
1428 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001429 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001430 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431 return true;
1432}
1433
hbos74e1a4f2016-09-15 23:33:01 -07001434void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1435 RTC_DCHECK(stats_collector_);
1436 stats_collector_->GetStatsReport(callback);
1437}
1438
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001439PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1440 return signaling_state_;
1441}
1442
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443PeerConnectionInterface::IceConnectionState
1444PeerConnection::ice_connection_state() {
1445 return ice_connection_state_;
1446}
1447
1448PeerConnectionInterface::IceGatheringState
1449PeerConnection::ice_gathering_state() {
1450 return ice_gathering_state_;
1451}
1452
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001453rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454PeerConnection::CreateDataChannel(
1455 const std::string& label,
1456 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001457 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001458
deadbeefab9b2d12015-10-14 11:33:11 -07001459 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001460
kwibergd1fe2812016-04-27 06:47:29 -07001461 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001462 if (config) {
1463 internal_config.reset(new InternalDataChannelInit(*config));
1464 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001465 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001466 InternalCreateDataChannel(label, internal_config.get()));
1467 if (!channel.get()) {
1468 return nullptr;
1469 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001471 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1472 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001473 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001474 observer_->OnRenegotiationNeeded();
1475 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477 return DataChannelProxy::Create(signaling_thread(), channel.get());
1478}
1479
1480void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1481 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001482 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001483
zhihuang1c378ed2017-08-17 14:10:50 -07001484 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1485 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1486 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1487 // compares the mandatory fields parsed with the mandatory fields added in the
1488 // |constraints| and some downstream applications might create offers with
1489 // mandatory fields which would not be parsed in the helper method. For
1490 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1491 // |constraints| as a mandatory field but it is not parsed.
1492 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001493
zhihuang1c378ed2017-08-17 14:10:50 -07001494 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001495}
1496
1497void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1498 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001499 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001500
nisse7ce109a2017-01-31 00:57:56 -08001501 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001502 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001503 return;
1504 }
deadbeefab9b2d12015-10-14 11:33:11 -07001505
Steve Anton8d3444d2017-10-20 15:30:51 -07001506 if (IsClosed()) {
1507 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001508 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001509 PostCreateSessionDescriptionFailure(observer, error);
1510 return;
1511 }
1512
zhihuang1c378ed2017-08-17 14:10:50 -07001513 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001514 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001515 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001516 PostCreateSessionDescriptionFailure(observer, error);
1517 return;
1518 }
1519
zhihuang1c378ed2017-08-17 14:10:50 -07001520 cricket::MediaSessionOptions session_options;
1521 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001522 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523}
1524
1525void PeerConnection::CreateAnswer(
1526 CreateSessionDescriptionObserver* observer,
1527 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001528 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001529
nisse7ce109a2017-01-31 00:57:56 -08001530 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001531 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532 return;
1533 }
deadbeefab9b2d12015-10-14 11:33:11 -07001534
zhihuang1c378ed2017-08-17 14:10:50 -07001535 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1536 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1537 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001538 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001539 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001540 PostCreateSessionDescriptionFailure(observer, error);
1541 return;
1542 }
1543
Steve Anton8d3444d2017-10-20 15:30:51 -07001544 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001545}
1546
1547void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1548 const RTCOfferAnswerOptions& options) {
1549 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001550 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001551 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001552 return;
1553 }
1554
Steve Anton8d3444d2017-10-20 15:30:51 -07001555 if (IsClosed()) {
1556 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001557 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001558 PostCreateSessionDescriptionFailure(observer, error);
1559 return;
1560 }
1561
Steve Anton75737c02017-11-06 10:37:17 -08001562 if (remote_description() &&
1563 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001564 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001566 PostCreateSessionDescriptionFailure(observer, error);
1567 return;
1568 }
1569
htaa2a49d92016-03-04 02:51:39 -08001570 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001571 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001572
Steve Antond25da372017-11-06 14:50:29 -08001573 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574}
1575
1576void PeerConnection::SetLocalDescription(
1577 SetSessionDescriptionObserver* observer,
1578 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001579 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001580 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 return;
1583 }
1584 if (!desc) {
1585 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1586 return;
1587 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001588
1589 // Takes the ownership of |desc| regardless of the result.
1590 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1591
1592 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001593 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001594 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001595 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001596 PostSetSessionDescriptionFailure(observer, error);
1597 return;
1598 }
1599
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600 // Update stats here so that we have the most recent stats for tracks and
1601 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001602 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001604 // Takes the ownership of |desc_temp|. On success, local_description() is
1605 // updated to reflect the description that was passed in.
Henrik Boström31638672017-11-23 17:48:32 +01001606 if (!SetCurrentOrPendingLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 PostSetSessionDescriptionFailure(observer, error);
1608 return;
1609 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001610 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001611
1612 // If setting the description decided our SSL role, allocate any necessary
1613 // SCTP sids.
1614 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001615 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001616 AllocateSctpSids(role);
1617 }
1618
1619 // Update state and SSRC of local MediaStreams and DataChannels based on the
1620 // local session description.
1621 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001622 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001623 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001624 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001625 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001626 } else {
1627 const cricket::AudioContentDescription* audio_desc =
1628 static_cast<const cricket::AudioContentDescription*>(
1629 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001630 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001631 }
deadbeefab9b2d12015-10-14 11:33:11 -07001632 }
1633
1634 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001635 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001636 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001637 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001638 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001639 } else {
1640 const cricket::VideoContentDescription* video_desc =
1641 static_cast<const cricket::VideoContentDescription*>(
1642 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001643 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001644 }
deadbeefab9b2d12015-10-14 11:33:11 -07001645 }
1646
1647 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001648 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001649 if (data_content) {
1650 const cricket::DataContentDescription* data_desc =
1651 static_cast<const cricket::DataContentDescription*>(
1652 data_content->description);
1653 if (rtc::starts_with(data_desc->protocol().data(),
1654 cricket::kMediaProtocolRtpPrefix)) {
1655 UpdateLocalRtpDataChannels(data_desc->streams());
1656 }
1657 }
1658
Henrik Boström31638672017-11-23 17:48:32 +01001659 PostSetSessionDescriptionSuccess(observer);
deadbeefab9b2d12015-10-14 11:33:11 -07001660
deadbeef42a42632017-03-10 15:18:00 -08001661 // According to JSEP, after setLocalDescription, changing the candidate pool
1662 // size is not allowed, and changing the set of ICE servers will not result
1663 // in new candidates being gathered.
1664 port_allocator_->FreezeCandidatePool();
1665
deadbeefcbecd352015-09-23 11:50:27 -07001666 // MaybeStartGathering needs to be called after posting
1667 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1668 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001669 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001670
Henrik Boströmfdb92012017-11-09 19:55:44 +01001671 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001672 // TODO(deadbeef): We already had to hop to the network thread for
1673 // MaybeStartGathering...
1674 network_thread()->Invoke<void>(
1675 RTC_FROM_HERE,
1676 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1677 port_allocator_.get()));
1678 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679}
1680
1681void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001682 SetSessionDescriptionObserver* observer,
1683 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001684 SetRemoteDescription(
1685 std::unique_ptr<SessionDescriptionInterface>(desc),
1686 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1687 new SetRemoteDescriptionObserverAdapter(this, observer)));
1688}
1689
1690void PeerConnection::SetRemoteDescription(
1691 std::unique_ptr<SessionDescriptionInterface> desc,
1692 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001693 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001694 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001695 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696 return;
1697 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001699 observer->OnSetRemoteDescriptionComplete(RTCError(
1700 RTCErrorType::UNSUPPORTED_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 return;
1702 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001703
Steve Anton8d3444d2017-10-20 15:30:51 -07001704 if (IsClosed()) {
Henrik Boström31638672017-11-23 17:48:32 +01001705 std::string error = "Failed to set remote " + desc->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001706 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001707 RTC_LOG(LS_ERROR) << error;
Henrik Boström31638672017-11-23 17:48:32 +01001708 observer->OnSetRemoteDescriptionComplete(
1709 RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001710 return;
1711 }
1712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713 // Update stats here so that we have the most recent stats for tracks and
1714 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001715 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 std::string error;
Henrik Boström31638672017-11-23 17:48:32 +01001717 // Takes the ownership of |desc|. On success, remote_description() is updated
1718 // to reflect the description that was passed in.
1719 if (!SetCurrentOrPendingRemoteDescription(std::move(desc), &error)) {
1720 observer->OnSetRemoteDescriptionComplete(
1721 RTCError(RTCErrorType::UNSUPPORTED_PARAMETER, std::move(error)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 return;
1723 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001724 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725
deadbeefab9b2d12015-10-14 11:33:11 -07001726 // If setting the description decided our SSL role, allocate any necessary
1727 // SCTP sids.
1728 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001729 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001730 AllocateSctpSids(role);
1731 }
1732
Henrik Boströmfdb92012017-11-09 19:55:44 +01001733 const cricket::ContentInfo* audio_content =
1734 GetFirstAudioContent(remote_description()->description());
1735 const cricket::ContentInfo* video_content =
1736 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001737 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001738 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001739 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001740 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001741 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001742 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001743
1744 // Check if the descriptions include streams, just in case the peer supports
1745 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001746 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001747 (audio_desc && !audio_desc->streams().empty()) ||
1748 (video_desc && !video_desc->streams().empty())) {
1749 remote_peer_supports_msid_ = true;
1750 }
deadbeefab9b2d12015-10-14 11:33:11 -07001751
1752 // We wait to signal new streams until we finish processing the description,
1753 // since only at that point will new streams have all their tracks.
1754 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1755
Steve Anton8d3444d2017-10-20 15:30:51 -07001756 // TODO(steveanton): When removing RTP senders/receivers in response to a
1757 // rejected media section, there is some cleanup logic that expects the voice/
1758 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001759 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001760 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001761 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001762
deadbeefab9b2d12015-10-14 11:33:11 -07001763 // Find all audio rtp streams and create corresponding remote AudioTracks
1764 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001765 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001766 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001767 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001768 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001769 bool default_audio_track_needed =
1770 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001771 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001772 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001773 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001774 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001775 }
deadbeefab9b2d12015-10-14 11:33:11 -07001776 }
1777
1778 // Find all video rtp streams and create corresponding remote VideoTracks
1779 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001780 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001781 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001782 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001783 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001784 bool default_video_track_needed =
1785 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001786 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001787 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001788 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001789 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001790 }
deadbeefab9b2d12015-10-14 11:33:11 -07001791 }
1792
1793 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001794 if (data_desc) {
1795 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001796 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001797 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001798 }
1799 }
1800
1801 // Iterate new_streams and notify the observer about new MediaStreams.
1802 for (size_t i = 0; i < new_streams->count(); ++i) {
1803 MediaStreamInterface* new_stream = new_streams->at(i);
1804 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001805 observer_->OnAddStream(
1806 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001807 }
1808
deadbeefbda7e0b2015-12-08 17:13:40 -08001809 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001810
Henrik Boström31638672017-11-23 17:48:32 +01001811 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
deadbeef42a42632017-03-10 15:18:00 -08001812
Henrik Boströmfdb92012017-11-09 19:55:44 +01001813 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001814 // TODO(deadbeef): We already had to hop to the network thread for
1815 // MaybeStartGathering...
1816 network_thread()->Invoke<void>(
1817 RTC_FROM_HERE,
1818 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1819 port_allocator_.get()));
1820 }
deadbeeffc648b62015-10-13 16:42:33 -07001821}
1822
deadbeef46c73892016-11-16 19:42:04 -08001823PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1824 return configuration_;
1825}
1826
deadbeef293e9262017-01-11 12:28:30 -08001827bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1828 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001829 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001830
Steve Anton75737c02017-11-06 10:37:17 -08001831 if (local_description() && configuration.ice_candidate_pool_size !=
1832 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001833 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1834 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001835 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001836 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001837
deadbeef293e9262017-01-11 12:28:30 -08001838 // The simplest (and most future-compatible) way to tell if the config was
1839 // modified in an invalid way is to copy each property we do support
1840 // modifying, then use operator==. There are far more properties we don't
1841 // support modifying than those we do, and more could be added.
1842 RTCConfiguration modified_config = configuration_;
1843 modified_config.servers = configuration.servers;
1844 modified_config.type = configuration.type;
1845 modified_config.ice_candidate_pool_size =
1846 configuration.ice_candidate_pool_size;
1847 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001848 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001849 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001850 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001851 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001852 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1853 }
1854
Steve Anton038834f2017-07-14 15:59:59 -07001855 // Validate the modified configuration.
1856 RTCError validate_error = ValidateConfiguration(modified_config);
1857 if (!validate_error.ok()) {
1858 return SafeSetError(std::move(validate_error), error);
1859 }
1860
deadbeef293e9262017-01-11 12:28:30 -08001861 // Note that this isn't possible through chromium, since it's an unsigned
1862 // short in WebIDL.
1863 if (configuration.ice_candidate_pool_size < 0 ||
1864 configuration.ice_candidate_pool_size > UINT16_MAX) {
1865 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1866 }
1867
1868 // Parse ICE servers before hopping to network thread.
1869 cricket::ServerAddresses stun_servers;
1870 std::vector<cricket::RelayServerConfig> turn_servers;
1871 RTCErrorType parse_error =
1872 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1873 if (parse_error != RTCErrorType::NONE) {
1874 return SafeSetError(parse_error, error);
1875 }
1876
1877 // In theory this shouldn't fail.
1878 if (!network_thread()->Invoke<bool>(
1879 RTC_FROM_HERE,
1880 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1881 stun_servers, turn_servers, modified_config.type,
1882 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001883 modified_config.prune_turn_ports,
1884 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001885 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001886 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1887 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001888
deadbeefd1a38b52016-12-10 13:15:33 -08001889 // As described in JSEP, calling setConfiguration with new ICE servers or
1890 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1891 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001892 if (modified_config.servers != configuration_.servers ||
1893 modified_config.type != configuration_.type ||
1894 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001895 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001896 }
skvladd1f5fda2017-02-03 16:54:05 -08001897
1898 if (modified_config.ice_check_min_interval !=
1899 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001900 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001901 }
1902
deadbeef293e9262017-01-11 12:28:30 -08001903 configuration_ = modified_config;
1904 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001905}
1906
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907bool PeerConnection::AddIceCandidate(
1908 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001909 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001910 if (IsClosed()) {
1911 return false;
1912 }
Steve Antond25da372017-11-06 14:50:29 -08001913
1914 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001915 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1916 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001917 return false;
1918 }
1919
1920 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001921 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001922 return false;
1923 }
1924
1925 bool valid = false;
1926 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1927 if (!valid) {
1928 return false;
1929 }
1930
1931 // Add this candidate to the remote session description.
1932 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001933 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001934 return false;
1935 }
1936
1937 if (ready) {
1938 return UseCandidate(ice_candidate);
1939 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001940 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001941 return true;
1942 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943}
1944
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001945bool PeerConnection::RemoveIceCandidates(
1946 const std::vector<cricket::Candidate>& candidates) {
1947 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001948 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001949 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1950 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001951 return false;
1952 }
1953
1954 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001955 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001956 return false;
1957 }
1958
1959 size_t number_removed =
1960 mutable_remote_description()->RemoveCandidates(candidates);
1961 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001962 RTC_LOG(LS_ERROR)
1963 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1964 << "Requested " << candidates.size() << " but only " << number_removed
1965 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001966 }
1967
1968 // Remove the candidates from the transport controller.
1969 std::string error;
1970 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1971 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001973 }
1974 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001975}
1976
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001977void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001978 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001979 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001980
Steve Anton75737c02017-11-06 10:37:17 -08001981 if (transport_controller()) {
1982 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001983 }
1984
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001985 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001986 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001987 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001988 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001989 uma_observer_->IncrementEnumCounter(
1990 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1991 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001992 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001993 uma_observer_->IncrementEnumCounter(
1994 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1995 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001996 }
1997 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001998}
1999
zstein4b979802017-06-02 14:37:37 -07002000RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002001 if (!worker_thread()->IsCurrent()) {
2002 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002003 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2004 }
2005
2006 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2007 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2008 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2009 if (has_min && *bitrate.min_bitrate_bps < 0) {
2010 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2011 "min_bitrate_bps <= 0");
2012 }
2013 if (has_current) {
2014 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2015 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2016 "current_bitrate_bps < min_bitrate_bps");
2017 } else if (*bitrate.current_bitrate_bps < 0) {
2018 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2019 "curent_bitrate_bps < 0");
2020 }
2021 }
2022 if (has_max) {
2023 if (has_current &&
2024 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2025 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2026 "max_bitrate_bps < current_bitrate_bps");
2027 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2028 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2029 "max_bitrate_bps < min_bitrate_bps");
2030 } else if (*bitrate.max_bitrate_bps < 0) {
2031 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2032 "max_bitrate_bps < 0");
2033 }
2034 }
2035
2036 Call::Config::BitrateConfigMask mask;
2037 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2038 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2039 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2040
2041 RTC_DCHECK(call_.get());
2042 call_->SetBitrateConfigMask(mask);
2043
2044 return RTCError::OK();
2045}
2046
Alex Narest78609d52017-10-20 10:37:47 +02002047void PeerConnection::SetBitrateAllocationStrategy(
2048 std::unique_ptr<rtc::BitrateAllocationStrategy>
2049 bitrate_allocation_strategy) {
2050 rtc::Thread* worker_thread = factory_->worker_thread();
2051 if (!worker_thread->IsCurrent()) {
2052 rtc::BitrateAllocationStrategy* strategy_raw =
2053 bitrate_allocation_strategy.release();
2054 auto functor = [this, strategy_raw]() {
2055 call_->SetBitrateAllocationStrategy(
2056 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2057 };
2058 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2059 return;
2060 }
2061 RTC_DCHECK(call_.get());
2062 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2063}
2064
henrika5f6bf242017-11-01 11:06:56 +01002065void PeerConnection::SetAudioPlayout(bool playout) {
2066 if (!worker_thread()->IsCurrent()) {
2067 worker_thread()->Invoke<void>(
2068 RTC_FROM_HERE,
2069 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2070 return;
2071 }
2072 auto audio_state =
2073 factory_->channel_manager()->media_engine()->GetAudioState();
2074 audio_state->SetPlayout(playout);
2075}
2076
2077void PeerConnection::SetAudioRecording(bool recording) {
2078 if (!worker_thread()->IsCurrent()) {
2079 worker_thread()->Invoke<void>(
2080 RTC_FROM_HERE,
2081 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2082 return;
2083 }
2084 auto audio_state =
2085 factory_->channel_manager()->media_engine()->GetAudioState();
2086 audio_state->SetRecording(recording);
2087}
2088
Steve Anton8c0f7a72017-10-03 10:03:10 -07002089std::unique_ptr<rtc::SSLCertificate>
2090PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002091 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002092 return nullptr;
2093 }
Steve Anton75737c02017-11-06 10:37:17 -08002094 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002095}
2096
ivoc14d5dbe2016-07-04 07:06:55 -07002097bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2098 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002099 // TODO(eladalon): It would be better to not allow negative values into PC.
2100 const size_t max_size = (max_size_bytes < 0)
2101 ? RtcEventLog::kUnlimitedOutput
2102 : rtc::saturated_cast<size_t>(max_size_bytes);
2103 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002104 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2105 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002106}
2107
Bjorn Tereliusde939432017-11-20 17:38:14 +01002108bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2109 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002110 // TODO(eladalon): In C++14, this can be done with a lambda.
2111 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002112 bool operator()() {
2113 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2114 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002115 PeerConnection* const pc;
2116 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002117 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002118 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002119 return worker_thread()->Invoke<bool>(
2120 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002121}
2122
2123void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002124 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002125 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2126}
2127
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002129 return pending_local_description_ ? pending_local_description_.get()
2130 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131}
2132
2133const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002134 return pending_remote_description_ ? pending_remote_description_.get()
2135 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136}
2137
deadbeeffe4a8a42016-12-20 17:56:17 -08002138const SessionDescriptionInterface* PeerConnection::current_local_description()
2139 const {
Steve Anton75737c02017-11-06 10:37:17 -08002140 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002141}
2142
2143const SessionDescriptionInterface* PeerConnection::current_remote_description()
2144 const {
Steve Anton75737c02017-11-06 10:37:17 -08002145 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002146}
2147
2148const SessionDescriptionInterface* PeerConnection::pending_local_description()
2149 const {
Steve Anton75737c02017-11-06 10:37:17 -08002150 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002151}
2152
2153const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2154 const {
Steve Anton75737c02017-11-06 10:37:17 -08002155 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002156}
2157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002159 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 // Update stats here so that we have the most recent stats for tracks and
2161 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002162 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163
Steve Anton75737c02017-11-06 10:37:17 -08002164 ChangeSignalingState(PeerConnectionInterface::kClosed);
2165 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002166 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2167 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002168 RTC_DCHECK(!rtp_data_channel_);
2169 RTC_DCHECK(!sctp_transport_);
2170
deadbeef42a42632017-03-10 15:18:00 -08002171 network_thread()->Invoke<void>(
2172 RTC_FROM_HERE,
2173 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2174 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002175
Steve Anton978b8762017-09-29 12:15:02 -07002176 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002177 call_.reset();
2178 // The event log must outlive call (and any other object that uses it).
2179 event_log_.reset();
2180 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181}
2182
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002183void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2186 SetSessionDescriptionMsg* param =
2187 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2188 param->observer->OnSuccess();
2189 delete param;
2190 break;
2191 }
2192 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2193 SetSessionDescriptionMsg* param =
2194 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2195 param->observer->OnFailure(param->error);
2196 delete param;
2197 break;
2198 }
deadbeefab9b2d12015-10-14 11:33:11 -07002199 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2200 CreateSessionDescriptionMsg* param =
2201 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2202 param->observer->OnFailure(param->error);
2203 delete param;
2204 break;
2205 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 case MSG_GETSTATS: {
2207 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002208 StatsReports reports;
2209 stats_->GetStats(param->track, &reports);
2210 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 delete param;
2212 break;
2213 }
deadbeefbd292462015-12-14 18:15:29 -08002214 case MSG_FREE_DATACHANNELS: {
2215 sctp_data_channels_to_free_.clear();
2216 break;
2217 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002219 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 break;
2221 }
2222}
2223
Steve Anton4171afb2017-11-20 10:20:22 -08002224void PeerConnection::CreateAudioReceiver(
2225 MediaStreamInterface* stream,
2226 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002227 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2228 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002229 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2230 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002231 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002232 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002233 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002234 stream->AddTrack(
2235 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002236 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002237 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238}
2239
Steve Anton4171afb2017-11-20 10:20:22 -08002240void PeerConnection::CreateVideoReceiver(
2241 MediaStreamInterface* stream,
2242 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002243 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2244 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002245 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2246 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002247 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002248 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2249 worker_thread(), remote_sender_info.first_ssrc,
2250 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002251 stream->AddTrack(
2252 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002253 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002254 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255}
2256
deadbeef70ab1a12015-09-28 16:53:55 -07002257// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2258// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002259rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002260 const RtpSenderInfo& remote_sender_info) {
2261 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2262 if (!receiver) {
2263 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2264 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002265 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002266 }
Steve Anton4171afb2017-11-20 10:20:22 -08002267 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2268 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2269 } else {
2270 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2271 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002272 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273}
2274
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002275void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2276 MediaStreamInterface* stream) {
2277 RTC_DCHECK(!IsClosed());
2278 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002279 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002280 // We already have a sender for this track, so just change the stream_id
2281 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002282 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002283 return;
2284 }
2285
2286 // Normal case; we've never seen this track before.
2287 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2288 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2289 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002290 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2291 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002292 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002293 // If the sender has already been configured in SDP, we call SetSsrc,
2294 // which will connect the sender to the underlying transport. This can
2295 // occur if a local session description that contains the ID of the sender
2296 // is set before AddStream is called. It can also occur if the local
2297 // session description is not changed and RemoveStream is called, and
2298 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002299 const RtpSenderInfo* sender_info =
2300 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2301 if (sender_info) {
2302 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002303 }
2304}
2305
2306// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2307// indefinitely, when we have unified plan SDP.
2308void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2309 MediaStreamInterface* stream) {
2310 RTC_DCHECK(!IsClosed());
2311 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002312 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002313 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2314 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002315 return;
2316 }
Steve Anton4171afb2017-11-20 10:20:22 -08002317 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002318}
2319
2320void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2321 MediaStreamInterface* stream) {
2322 RTC_DCHECK(!IsClosed());
2323 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002324 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002325 // We already have a sender for this track, so just change the stream_id
2326 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002327 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002328 return;
2329 }
2330
2331 // Normal case; we've never seen this track before.
2332 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2333 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002334 signaling_thread(),
2335 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002336 GetVideoTransceiver()->internal()->AddSender(new_sender);
2337 const RtpSenderInfo* sender_info =
2338 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2339 if (sender_info) {
2340 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002341 }
2342}
2343
2344void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2345 MediaStreamInterface* stream) {
2346 RTC_DCHECK(!IsClosed());
2347 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002348 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002349 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2350 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002351 return;
2352 }
Steve Anton4171afb2017-11-20 10:20:22 -08002353 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002354}
2355
Steve Antonba818672017-11-06 10:21:57 -08002356void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002357 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002358 if (ice_connection_state_ == new_state) {
2359 return;
2360 }
2361
deadbeefcbecd352015-09-23 11:50:27 -07002362 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002363 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002364 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002365 return;
2366 }
Steve Antonba818672017-11-06 10:21:57 -08002367
Mirko Bonadei675513b2017-11-09 11:09:25 +01002368 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2369 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002370 RTC_DCHECK(ice_connection_state_ !=
2371 PeerConnectionInterface::kIceConnectionClosed);
2372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002374 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375}
2376
2377void PeerConnection::OnIceGatheringChange(
2378 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002379 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 if (IsClosed()) {
2381 return;
2382 }
2383 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002384 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385}
2386
jbauch81bf7b02017-03-25 08:31:12 -07002387void PeerConnection::OnIceCandidate(
2388 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002389 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002390 if (IsClosed()) {
2391 return;
2392 }
jbauch81bf7b02017-03-25 08:31:12 -07002393 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394}
2395
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002396void PeerConnection::OnIceCandidatesRemoved(
2397 const std::vector<cricket::Candidate>& candidates) {
2398 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002399 if (IsClosed()) {
2400 return;
2401 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002402 observer_->OnIceCandidatesRemoved(candidates);
2403}
2404
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405void PeerConnection::ChangeSignalingState(
2406 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002407 RTC_DCHECK(signaling_thread()->IsCurrent());
2408 if (signaling_state_ == signaling_state) {
2409 return;
2410 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002411 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2412 << GetSignalingStateString(signaling_state_)
2413 << " New state: "
2414 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415 signaling_state_ = signaling_state;
2416 if (signaling_state == kClosed) {
2417 ice_connection_state_ = kIceConnectionClosed;
2418 observer_->OnIceConnectionChange(ice_connection_state_);
2419 if (ice_gathering_state_ != kIceGatheringComplete) {
2420 ice_gathering_state_ = kIceGatheringComplete;
2421 observer_->OnIceGatheringChange(ice_gathering_state_);
2422 }
2423 }
2424 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425}
2426
deadbeefeb459812015-12-15 19:24:43 -08002427void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2428 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002429 if (IsClosed()) {
2430 return;
2431 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002432 AddAudioTrack(track, stream);
2433 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002434}
2435
deadbeefeb459812015-12-15 19:24:43 -08002436void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2437 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002438 if (IsClosed()) {
2439 return;
2440 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002441 RemoveAudioTrack(track, stream);
2442 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002443}
2444
2445void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2446 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002447 if (IsClosed()) {
2448 return;
2449 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002450 AddVideoTrack(track, stream);
2451 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002452}
2453
2454void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2455 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002456 if (IsClosed()) {
2457 return;
2458 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002459 RemoveVideoTrack(track, stream);
2460 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002461}
2462
Henrik Boström31638672017-11-23 17:48:32 +01002463void PeerConnection::PostSetSessionDescriptionSuccess(
2464 SetSessionDescriptionObserver* observer) {
2465 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2466 signaling_thread()->Post(RTC_FROM_HERE, this,
2467 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2468}
2469
deadbeefab9b2d12015-10-14 11:33:11 -07002470void PeerConnection::PostSetSessionDescriptionFailure(
2471 SetSessionDescriptionObserver* observer,
2472 const std::string& error) {
2473 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2474 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002475 signaling_thread()->Post(RTC_FROM_HERE, this,
2476 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002477}
2478
2479void PeerConnection::PostCreateSessionDescriptionFailure(
2480 CreateSessionDescriptionObserver* observer,
2481 const std::string& error) {
2482 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2483 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002484 signaling_thread()->Post(RTC_FROM_HERE, this,
2485 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002486}
2487
zhihuang1c378ed2017-08-17 14:10:50 -07002488void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002489 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2490 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002491 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2492
2493 // Figure out transceiver directional preferences.
2494 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2495 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2496
2497 // By default, generate sendrecv/recvonly m= sections.
2498 bool recv_audio = true;
2499 bool recv_video = true;
2500
2501 // By default, only offer a new m= section if we have media to send with it.
2502 bool offer_new_audio_description = send_audio;
2503 bool offer_new_video_description = send_video;
2504 bool offer_new_data_description = HasDataChannels();
2505
2506 // The "offer_to_receive_X" options allow those defaults to be overridden.
2507 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2508 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2509 offer_new_audio_description =
2510 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2511 }
2512 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2513 recv_video = (rtc_options.offer_to_receive_video > 0);
2514 offer_new_video_description =
2515 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2516 }
2517
2518 rtc::Optional<size_t> audio_index;
2519 rtc::Optional<size_t> video_index;
2520 rtc::Optional<size_t> data_index;
2521 // If a current description exists, generate m= sections in the same order,
2522 // using the first audio/video/data section that appears and rejecting
2523 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002524 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002525 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002526 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002527 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2528 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2529 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002530 }
2531
zhihuang1c378ed2017-08-17 14:10:50 -07002532 // Add audio/video/data m= sections to the end if needed.
2533 if (!audio_index && offer_new_audio_description) {
2534 session_options->media_description_options.push_back(
2535 cricket::MediaDescriptionOptions(
2536 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002537 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2538 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002539 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002540 }
zhihuang1c378ed2017-08-17 14:10:50 -07002541 if (!video_index && offer_new_video_description) {
2542 session_options->media_description_options.push_back(
2543 cricket::MediaDescriptionOptions(
2544 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002545 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2546 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002547 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002548 }
zhihuang1c378ed2017-08-17 14:10:50 -07002549 if (!data_index && offer_new_data_description) {
2550 session_options->media_description_options.push_back(
2551 cricket::MediaDescriptionOptions(
2552 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002553 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002554 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002555 }
2556
2557 cricket::MediaDescriptionOptions* audio_media_description_options =
2558 !audio_index ? nullptr
2559 : &session_options->media_description_options[*audio_index];
2560 cricket::MediaDescriptionOptions* video_media_description_options =
2561 !video_index ? nullptr
2562 : &session_options->media_description_options[*video_index];
2563 cricket::MediaDescriptionOptions* data_media_description_options =
2564 !data_index ? nullptr
2565 : &session_options->media_description_options[*data_index];
2566
2567 // Apply ICE restart flag and renomination flag.
2568 for (auto& options : session_options->media_description_options) {
2569 options.transport_options.ice_restart = rtc_options.ice_restart;
2570 options.transport_options.enable_ice_renomination =
2571 configuration_.enable_ice_renomination;
2572 }
2573
Steve Anton4171afb2017-11-20 10:20:22 -08002574 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002575 video_media_description_options);
2576 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002577
zhihuang9763d562016-08-05 11:14:50 -07002578 // Intentionally unset the data channel type for RTP data channel with the
2579 // second condition. Otherwise the RTP data channels would be successfully
2580 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2581 // when building with chromium. We want to leave RTP data channels broken, so
2582 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002583 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2584 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002585 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002586
2587 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002588 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002589}
2590
zhihuang1c378ed2017-08-17 14:10:50 -07002591void PeerConnection::GetOptionsForAnswer(
2592 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002593 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002594 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002595
zhihuang1c378ed2017-08-17 14:10:50 -07002596 // Figure out transceiver directional preferences.
2597 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2598 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2599
2600 // By default, generate sendrecv/recvonly m= sections. The direction is also
2601 // restricted by the direction in the offer.
2602 bool recv_audio = true;
2603 bool recv_video = true;
2604
2605 // The "offer_to_receive_X" options allow those defaults to be overridden.
2606 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2607 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002608 }
zhihuang1c378ed2017-08-17 14:10:50 -07002609 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2610 recv_video = (rtc_options.offer_to_receive_video > 0);
2611 }
2612
2613 rtc::Optional<size_t> audio_index;
2614 rtc::Optional<size_t> video_index;
2615 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002616 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002617 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002618 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002619 SessionDescriptionInterface::kOffer);
2620 // Generate m= sections that match those in the offer.
2621 // Note that mediasession.cc will handle intersection our preferred
2622 // direction with the offered direction.
2623 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002624 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002625 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2626 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2627 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002628 }
zhihuang1c378ed2017-08-17 14:10:50 -07002629
2630 cricket::MediaDescriptionOptions* audio_media_description_options =
2631 !audio_index ? nullptr
2632 : &session_options->media_description_options[*audio_index];
2633 cricket::MediaDescriptionOptions* video_media_description_options =
2634 !video_index ? nullptr
2635 : &session_options->media_description_options[*video_index];
2636 cricket::MediaDescriptionOptions* data_media_description_options =
2637 !data_index ? nullptr
2638 : &session_options->media_description_options[*data_index];
2639
2640 // Apply ICE renomination flag.
2641 for (auto& options : session_options->media_description_options) {
2642 options.transport_options.enable_ice_renomination =
2643 configuration_.enable_ice_renomination;
2644 }
2645
Steve Anton4171afb2017-11-20 10:20:22 -08002646 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002647 video_media_description_options);
2648 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2649
zhihuang9763d562016-08-05 11:14:50 -07002650 // Intentionally unset the data channel type for RTP data channel. Otherwise
2651 // the RTP data channels would be successfully negotiated by default and the
2652 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2653 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002654 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2655 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002656 }
zhihuangaf388472016-11-02 16:49:48 -07002657
zhihuang1c378ed2017-08-17 14:10:50 -07002658 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002659 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002660}
2661
zhihuang1c378ed2017-08-17 14:10:50 -07002662void PeerConnection::GenerateMediaDescriptionOptions(
2663 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002664 RtpTransceiverDirection audio_direction,
2665 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002666 rtc::Optional<size_t>* audio_index,
2667 rtc::Optional<size_t>* video_index,
2668 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002669 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002670 for (const cricket::ContentInfo& content :
2671 session_desc->description()->contents()) {
2672 if (IsAudioContent(&content)) {
2673 // If we already have an audio m= section, reject this extra one.
2674 if (*audio_index) {
2675 session_options->media_description_options.push_back(
2676 cricket::MediaDescriptionOptions(
2677 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002678 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002679 } else {
2680 session_options->media_description_options.push_back(
2681 cricket::MediaDescriptionOptions(
2682 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002683 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002684 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002685 }
2686 } else if (IsVideoContent(&content)) {
2687 // If we already have an video m= section, reject this extra one.
2688 if (*video_index) {
2689 session_options->media_description_options.push_back(
2690 cricket::MediaDescriptionOptions(
2691 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002692 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002693 } else {
2694 session_options->media_description_options.push_back(
2695 cricket::MediaDescriptionOptions(
2696 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002697 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002698 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002699 }
2700 } else {
2701 RTC_DCHECK(IsDataContent(&content));
2702 // If we already have an data m= section, reject this extra one.
2703 if (*data_index) {
2704 session_options->media_description_options.push_back(
2705 cricket::MediaDescriptionOptions(
2706 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002707 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002708 } else {
2709 session_options->media_description_options.push_back(
2710 cricket::MediaDescriptionOptions(
2711 cricket::MEDIA_TYPE_DATA, content.name,
2712 // Direction for data sections is meaningless, but legacy
2713 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002714 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002715 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002716 }
2717 }
htaa2a49d92016-03-04 02:51:39 -08002718 }
deadbeefab9b2d12015-10-14 11:33:11 -07002719}
2720
Steve Anton4171afb2017-11-20 10:20:22 -08002721void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2722 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2723 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002724 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002725}
2726
Steve Anton4171afb2017-11-20 10:20:22 -08002727void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002728 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002729 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002730 cricket::MediaType media_type,
2731 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002732 std::vector<RtpSenderInfo>* current_senders =
2733 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002734
Steve Anton4171afb2017-11-20 10:20:22 -08002735 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002736 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002737 for (auto sender_it = current_senders->begin();
2738 sender_it != current_senders->end();
2739 /* incremented manually */) {
2740 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002741 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002742 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2743 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002744 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002745 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2746 sender_exists) {
2747 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002748 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002749 OnRemoteSenderRemoved(info, media_type);
2750 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002751 }
2752 }
2753
Steve Anton4171afb2017-11-20 10:20:22 -08002754 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002755 for (const cricket::StreamParams& params : streams) {
2756 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002757 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002758 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002759 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002760 uint32_t ssrc = params.first_ssrc();
2761
2762 rtc::scoped_refptr<MediaStreamInterface> stream =
2763 remote_streams_->find(stream_label);
2764 if (!stream) {
2765 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002766 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2767 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002768 remote_streams_->AddStream(stream);
2769 new_streams->AddStream(stream);
2770 }
2771
Steve Anton4171afb2017-11-20 10:20:22 -08002772 const RtpSenderInfo* sender_info =
2773 FindSenderInfo(*current_senders, stream_label, sender_id);
2774 if (!sender_info) {
2775 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2776 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002777 }
2778 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002779
Steve Anton4171afb2017-11-20 10:20:22 -08002780 // Add default sender if necessary.
2781 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002782 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2783 remote_streams_->find(kDefaultStreamLabel);
2784 if (!default_stream) {
2785 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002786 default_stream = MediaStreamProxy::Create(
2787 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002788 remote_streams_->AddStream(default_stream);
2789 new_streams->AddStream(default_stream);
2790 }
Steve Anton4171afb2017-11-20 10:20:22 -08002791 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2792 ? kDefaultAudioSenderId
2793 : kDefaultVideoSenderId;
2794 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2795 *current_senders, kDefaultStreamLabel, default_sender_id);
2796 if (!default_sender_info) {
2797 current_senders->push_back(
2798 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2799 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002800 }
2801 }
deadbeefab9b2d12015-10-14 11:33:11 -07002802}
2803
Steve Anton4171afb2017-11-20 10:20:22 -08002804void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2805 cricket::MediaType media_type) {
2806 MediaStreamInterface* stream =
2807 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002808
2809 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002810 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002811 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002812 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002813 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002814 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002815 }
2816}
2817
Steve Anton4171afb2017-11-20 10:20:22 -08002818void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2819 cricket::MediaType media_type) {
2820 MediaStreamInterface* stream =
2821 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002822
Henrik Boström933d8b02017-10-10 10:05:16 -07002823 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002824 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002825 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2826 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002827 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002828 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002829 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002830 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002831 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002832 }
2833 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002834 // Stopping or destroying a VideoRtpReceiver will end the
2835 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002836 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002837 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002838 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002839 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002840 // There's no guarantee the track is still available, e.g. the track may
2841 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002842 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002843 }
2844 } else {
nisseede5da42017-01-12 05:15:36 -08002845 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002846 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002847 if (receiver) {
2848 observer_->OnRemoveTrack(receiver);
2849 }
deadbeefab9b2d12015-10-14 11:33:11 -07002850}
2851
2852void PeerConnection::UpdateEndedRemoteMediaStreams() {
2853 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2854 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2855 MediaStreamInterface* stream = remote_streams_->at(i);
2856 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2857 streams_to_remove.push_back(stream);
2858 }
2859 }
2860
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002861 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002862 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002863 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002864 }
2865}
2866
Steve Anton4171afb2017-11-20 10:20:22 -08002867void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002868 const std::vector<cricket::StreamParams>& streams,
2869 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002870 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002871
2872 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2873 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002874 for (auto sender_it = current_senders->begin();
2875 sender_it != current_senders->end();
2876 /* incremented manually */) {
2877 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002878 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002879 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2880 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002881 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002882 OnLocalSenderRemoved(info, media_type);
2883 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002884 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002885 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002886 }
2887 }
2888
Steve Anton4171afb2017-11-20 10:20:22 -08002889 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002890 for (const cricket::StreamParams& params : streams) {
2891 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002892 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002893 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002894 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002895 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002896 const RtpSenderInfo* sender_info =
2897 FindSenderInfo(*current_senders, stream_label, sender_id);
2898 if (!sender_info) {
2899 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2900 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002901 }
2902 }
2903}
2904
Steve Anton4171afb2017-11-20 10:20:22 -08002905void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2906 cricket::MediaType media_type) {
2907 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002908 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002909 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2910 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002911 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002912 return;
2913 }
2914
deadbeeffac06552015-11-25 11:26:01 -08002915 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002916 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2917 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002918 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002919 }
deadbeeffac06552015-11-25 11:26:01 -08002920
Steve Anton4171afb2017-11-20 10:20:22 -08002921 sender->internal()->set_stream_id(sender_info.stream_label);
2922 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002923}
2924
Steve Anton4171afb2017-11-20 10:20:22 -08002925void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2926 cricket::MediaType media_type) {
2927 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002928 if (!sender) {
2929 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002930 // SessionDescriptions has been renegotiated.
2931 return;
2932 }
deadbeeffac06552015-11-25 11:26:01 -08002933
2934 // A sender has been removed from the SessionDescription but it's still
2935 // associated with the PeerConnection. This only occurs if the SDP doesn't
2936 // match with the calls to CreateSender, AddStream and RemoveStream.
2937 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002938 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2939 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002940 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002941 }
deadbeeffac06552015-11-25 11:26:01 -08002942
Steve Anton4171afb2017-11-20 10:20:22 -08002943 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002944}
2945
2946void PeerConnection::UpdateLocalRtpDataChannels(
2947 const cricket::StreamParamsVec& streams) {
2948 std::vector<std::string> existing_channels;
2949
2950 // Find new and active data channels.
2951 for (const cricket::StreamParams& params : streams) {
2952 // |it->sync_label| is actually the data channel label. The reason is that
2953 // we use the same naming of data channels as we do for
2954 // MediaStreams and Tracks.
2955 // For MediaStreams, the sync_label is the MediaStream label and the
2956 // track label is the same as |streamid|.
2957 const std::string& channel_label = params.sync_label;
2958 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002959 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002960 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002961 continue;
2962 }
2963 // Set the SSRC the data channel should use for sending.
2964 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2965 existing_channels.push_back(data_channel_it->first);
2966 }
2967
2968 UpdateClosingRtpDataChannels(existing_channels, true);
2969}
2970
2971void PeerConnection::UpdateRemoteRtpDataChannels(
2972 const cricket::StreamParamsVec& streams) {
2973 std::vector<std::string> existing_channels;
2974
2975 // Find new and active data channels.
2976 for (const cricket::StreamParams& params : streams) {
2977 // The data channel label is either the mslabel or the SSRC if the mslabel
2978 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2979 std::string label = params.sync_label.empty()
2980 ? rtc::ToString(params.first_ssrc())
2981 : params.sync_label;
2982 auto data_channel_it = rtp_data_channels_.find(label);
2983 if (data_channel_it == rtp_data_channels_.end()) {
2984 // This is a new data channel.
2985 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2986 } else {
2987 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2988 }
2989 existing_channels.push_back(label);
2990 }
2991
2992 UpdateClosingRtpDataChannels(existing_channels, false);
2993}
2994
2995void PeerConnection::UpdateClosingRtpDataChannels(
2996 const std::vector<std::string>& active_channels,
2997 bool is_local_update) {
2998 auto it = rtp_data_channels_.begin();
2999 while (it != rtp_data_channels_.end()) {
3000 DataChannel* data_channel = it->second;
3001 if (std::find(active_channels.begin(), active_channels.end(),
3002 data_channel->label()) != active_channels.end()) {
3003 ++it;
3004 continue;
3005 }
3006
3007 if (is_local_update) {
3008 data_channel->SetSendSsrc(0);
3009 } else {
3010 data_channel->RemotePeerRequestClose();
3011 }
3012
3013 if (data_channel->state() == DataChannel::kClosed) {
3014 rtp_data_channels_.erase(it);
3015 it = rtp_data_channels_.begin();
3016 } else {
3017 ++it;
3018 }
3019 }
3020}
3021
3022void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3023 uint32_t remote_ssrc) {
3024 rtc::scoped_refptr<DataChannel> channel(
3025 InternalCreateDataChannel(label, nullptr));
3026 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003027 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3028 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003029 return;
3030 }
3031 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003032 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3033 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003034 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003035}
3036
3037rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3038 const std::string& label,
3039 const InternalDataChannelInit* config) {
3040 if (IsClosed()) {
3041 return nullptr;
3042 }
Steve Anton75737c02017-11-06 10:37:17 -08003043 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003044 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003045 << "InternalCreateDataChannel: Data is not supported in this call.";
3046 return nullptr;
3047 }
3048 InternalDataChannelInit new_config =
3049 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003050 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003051 if (new_config.id < 0) {
3052 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003053 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003054 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003055 RTC_LOG(LS_ERROR)
3056 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003057 return nullptr;
3058 }
3059 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003060 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3061 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003062 return nullptr;
3063 }
3064 }
3065
Steve Anton75737c02017-11-06 10:37:17 -08003066 rtc::scoped_refptr<DataChannel> channel(
3067 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003068 if (!channel) {
3069 sid_allocator_.ReleaseSid(new_config.id);
3070 return nullptr;
3071 }
3072
3073 if (channel->data_channel_type() == cricket::DCT_RTP) {
3074 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003075 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3076 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003077 return nullptr;
3078 }
3079 rtp_data_channels_[channel->label()] = channel;
3080 } else {
3081 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3082 sctp_data_channels_.push_back(channel);
3083 channel->SignalClosed.connect(this,
3084 &PeerConnection::OnSctpDataChannelClosed);
3085 }
3086
hbos82ebe022016-11-14 01:41:09 -08003087 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003088 return channel;
3089}
3090
3091bool PeerConnection::HasDataChannels() const {
3092 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3093}
3094
3095void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3096 for (const auto& channel : sctp_data_channels_) {
3097 if (channel->id() < 0) {
3098 int sid;
3099 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003100 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003101 continue;
3102 }
3103 channel->SetSctpSid(sid);
3104 }
3105 }
3106}
3107
3108void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003109 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003110 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3111 ++it) {
3112 if (it->get() == channel) {
3113 if (channel->id() >= 0) {
3114 sid_allocator_.ReleaseSid(channel->id());
3115 }
deadbeefbd292462015-12-14 18:15:29 -08003116 // Since this method is triggered by a signal from the DataChannel,
3117 // we can't free it directly here; we need to free it asynchronously.
3118 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003119 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003120 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3121 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003122 return;
3123 }
3124 }
3125}
3126
deadbeefab9b2d12015-10-14 11:33:11 -07003127void PeerConnection::OnDataChannelDestroyed() {
3128 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3129 // DataChannel may callback to us and try to modify the list.
3130 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3131 temp_rtp_dcs.swap(rtp_data_channels_);
3132 for (const auto& kv : temp_rtp_dcs) {
3133 kv.second->OnTransportChannelDestroyed();
3134 }
3135
3136 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3137 temp_sctp_dcs.swap(sctp_data_channels_);
3138 for (const auto& channel : temp_sctp_dcs) {
3139 channel->OnTransportChannelDestroyed();
3140 }
3141}
3142
3143void PeerConnection::OnDataChannelOpenMessage(
3144 const std::string& label,
3145 const InternalDataChannelInit& config) {
3146 rtc::scoped_refptr<DataChannel> channel(
3147 InternalCreateDataChannel(label, &config));
3148 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003149 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003150 return;
3151 }
3152
deadbeefa601f5c2016-06-06 14:27:39 -07003153 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3154 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003155 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003156}
3157
Steve Anton4171afb2017-11-20 10:20:22 -08003158rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3159PeerConnection::GetAudioTransceiver() const {
3160 // This method only works with Plan B SDP, where there is a single
3161 // audio/video transceiver.
3162 RTC_DCHECK(!IsUnifiedPlan());
3163 for (auto transceiver : transceivers_) {
3164 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3165 return transceiver;
3166 }
3167 }
3168 RTC_NOTREACHED();
3169 return nullptr;
3170}
3171
3172rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3173PeerConnection::GetVideoTransceiver() const {
3174 // This method only works with Plan B SDP, where there is a single
3175 // audio/video transceiver.
3176 RTC_DCHECK(!IsUnifiedPlan());
3177 for (auto transceiver : transceivers_) {
3178 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3179 return transceiver;
3180 }
3181 }
3182 RTC_NOTREACHED();
3183 return nullptr;
3184}
3185
3186// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3187// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003188bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003189 switch (type) {
3190 case cricket::MEDIA_TYPE_AUDIO:
3191 return !GetAudioTransceiver()->internal()->senders().empty();
3192 case cricket::MEDIA_TYPE_VIDEO:
3193 return !GetVideoTransceiver()->internal()->senders().empty();
3194 case cricket::MEDIA_TYPE_DATA:
3195 return false;
3196 }
3197 RTC_NOTREACHED();
3198 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003199}
3200
Steve Anton4171afb2017-11-20 10:20:22 -08003201rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3202PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3203 for (auto transceiver : transceivers_) {
3204 for (auto sender : transceiver->internal()->senders()) {
3205 if (sender->track() == track) {
3206 return sender;
3207 }
3208 }
3209 }
3210 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003211}
3212
Steve Anton4171afb2017-11-20 10:20:22 -08003213rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3214PeerConnection::FindSenderById(const std::string& sender_id) const {
3215 for (auto transceiver : transceivers_) {
3216 for (auto sender : transceiver->internal()->senders()) {
3217 if (sender->id() == sender_id) {
3218 return sender;
3219 }
3220 }
3221 }
3222 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003223}
3224
Steve Anton4171afb2017-11-20 10:20:22 -08003225rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3226PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3227 for (auto transceiver : transceivers_) {
3228 for (auto receiver : transceiver->internal()->receivers()) {
3229 if (receiver->id() == receiver_id) {
3230 return receiver;
3231 }
3232 }
3233 }
3234 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003235}
3236
Steve Anton4171afb2017-11-20 10:20:22 -08003237std::vector<PeerConnection::RtpSenderInfo>*
3238PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3239 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3240 media_type == cricket::MEDIA_TYPE_VIDEO);
3241 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3242 ? &remote_audio_sender_infos_
3243 : &remote_video_sender_infos_;
3244}
3245
3246std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003247 cricket::MediaType media_type) {
3248 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3249 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003250 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3251 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003252}
3253
Steve Anton4171afb2017-11-20 10:20:22 -08003254const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3255 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003256 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003257 const std::string sender_id) const {
3258 for (const RtpSenderInfo& sender_info : infos) {
3259 if (sender_info.stream_label == stream_label &&
3260 sender_info.sender_id == sender_id) {
3261 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003262 }
3263 }
3264 return nullptr;
3265}
3266
3267DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3268 for (const auto& channel : sctp_data_channels_) {
3269 if (channel->id() == sid) {
3270 return channel;
3271 }
3272 }
3273 return nullptr;
3274}
3275
deadbeef91dd5672016-05-18 16:55:30 -07003276bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003277 const RTCConfiguration& configuration) {
3278 cricket::ServerAddresses stun_servers;
3279 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003280 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3281 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003282 return false;
3283 }
3284
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003285 port_allocator_->Initialize();
3286
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003287 // To handle both internal and externally created port allocator, we will
3288 // enable BUNDLE here.
3289 int portallocator_flags = port_allocator_->flags();
3290 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003291 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3292 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003293 // If the disable-IPv6 flag was specified, we'll not override it
3294 // by experiment.
3295 if (configuration.disable_ipv6) {
3296 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003297 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3298 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003299 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3300 }
3301
zhihuangb09b3f92017-03-07 14:40:51 -08003302 if (configuration.disable_ipv6_on_wifi) {
3303 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003304 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003305 }
3306
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003307 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3308 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003309 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003310 }
3311
honghaiz60347052016-05-31 18:29:12 -07003312 if (configuration.candidate_network_policy ==
3313 kCandidateNetworkPolicyLowCost) {
3314 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003315 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003316 }
3317
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003318 port_allocator_->set_flags(portallocator_flags);
3319 // No step delay is used while allocating ports.
3320 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3321 port_allocator_->set_candidate_filter(
3322 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003323 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003324
3325 // Call this last since it may create pooled allocator sessions using the
3326 // properties set above.
3327 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003328 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003329 configuration.prune_turn_ports,
3330 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003331 return true;
3332}
3333
deadbeef91dd5672016-05-18 16:55:30 -07003334bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003335 const cricket::ServerAddresses& stun_servers,
3336 const std::vector<cricket::RelayServerConfig>& turn_servers,
3337 IceTransportsType type,
3338 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003339 bool prune_turn_ports,
3340 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003341 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003342 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003343 // Call this last since it may create pooled allocator sessions using the
3344 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003345 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003346 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3347 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003348}
3349
Steve Antonba818672017-11-06 10:21:57 -08003350cricket::ChannelManager* PeerConnection::channel_manager() const {
3351 return factory_->channel_manager();
3352}
3353
3354MetricsObserverInterface* PeerConnection::metrics_observer() const {
3355 return uma_observer_;
3356}
3357
Elad Alon99c3fe52017-10-13 16:29:40 +02003358bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003359 std::unique_ptr<RtcEventLogOutput> output,
3360 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003361 if (!event_log_) {
3362 return false;
3363 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003364 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003365}
3366
3367void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003368 if (event_log_) {
3369 event_log_->StopLogging();
3370 }
ivoc14d5dbe2016-07-04 07:06:55 -07003371}
nisseeaabdf62017-05-05 02:23:02 -07003372
Steve Anton75737c02017-11-06 10:37:17 -08003373cricket::BaseChannel* PeerConnection::GetChannel(
3374 const std::string& content_name) {
3375 if (voice_channel() && voice_channel()->content_name() == content_name) {
3376 return voice_channel();
3377 }
3378 if (video_channel() && video_channel()->content_name() == content_name) {
3379 return video_channel();
3380 }
3381 if (rtp_data_channel() &&
3382 rtp_data_channel()->content_name() == content_name) {
3383 return rtp_data_channel();
3384 }
3385 return nullptr;
3386}
3387
3388bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3389 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003390 RTC_LOG(LS_INFO)
3391 << "Local and Remote descriptions must be applied to get the "
3392 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003393 return false;
3394 }
3395 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003396 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3397 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003398 return false;
3399 }
3400
3401 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3402}
3403
3404bool PeerConnection::GetSslRole(const std::string& content_name,
3405 rtc::SSLRole* role) {
3406 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003407 RTC_LOG(LS_INFO)
3408 << "Local and Remote descriptions must be applied to get the "
3409 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003410 return false;
3411 }
3412
3413 return transport_controller_->GetSslRole(GetTransportName(content_name),
3414 role);
3415}
3416
Henrik Boström31638672017-11-23 17:48:32 +01003417bool PeerConnection::SetCurrentOrPendingLocalDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003418 std::unique_ptr<SessionDescriptionInterface> desc,
3419 std::string* err_desc) {
3420 RTC_DCHECK(signaling_thread()->IsCurrent());
3421
3422 // Validate SDP.
3423 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3424 return false;
3425 }
3426
3427 // Update the initial_offerer flag if this session is the initial_offerer.
3428 Action action = GetAction(desc->type());
3429 if (!initial_offerer_.has_value()) {
3430 initial_offerer_.emplace(action == kOffer);
3431 if (*initial_offerer_) {
3432 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3433 } else {
3434 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3435 }
3436 }
3437
3438 if (action == kAnswer) {
3439 current_local_description_ = std::move(desc);
3440 pending_local_description_ = nullptr;
3441 current_remote_description_ = std::move(pending_remote_description_);
3442 } else {
3443 pending_local_description_ = std::move(desc);
3444 }
3445
3446 // Transport and Media channels will be created only when offer is set.
3447 if (action == kOffer && !CreateChannels(local_description()->description())) {
3448 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3449 // is applied. Restore back to old description.
3450 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3451 err_desc);
3452 }
3453
3454 // Remove unused channels if MediaContentDescription is rejected.
3455 RemoveUnusedChannels(local_description()->description());
3456
3457 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3458 return false;
3459 }
3460 if (remote_description()) {
3461 // Now that we have a local description, we can push down remote candidates.
3462 UseCandidatesInSessionDescription(remote_description());
3463 }
3464
3465 pending_ice_restarts_.clear();
3466 if (error() != ERROR_NONE) {
3467 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3468 err_desc);
3469 }
3470 return true;
3471}
3472
Henrik Boström31638672017-11-23 17:48:32 +01003473bool PeerConnection::SetCurrentOrPendingRemoteDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003474 std::unique_ptr<SessionDescriptionInterface> desc,
3475 std::string* err_desc) {
3476 RTC_DCHECK(signaling_thread()->IsCurrent());
3477
3478 // Validate SDP.
3479 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3480 return false;
3481 }
3482
3483 // Hold this pointer so candidates can be copied to it later in the method.
3484 SessionDescriptionInterface* desc_ptr = desc.get();
3485
3486 const SessionDescriptionInterface* old_remote_description =
3487 remote_description();
3488 // Grab ownership of the description being replaced for the remainder of this
3489 // method, since it's used below as |old_remote_description|.
3490 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3491 Action action = GetAction(desc->type());
3492 if (action == kAnswer) {
3493 replaced_remote_description = pending_remote_description_
3494 ? std::move(pending_remote_description_)
3495 : std::move(current_remote_description_);
3496 current_remote_description_ = std::move(desc);
3497 pending_remote_description_ = nullptr;
3498 current_local_description_ = std::move(pending_local_description_);
3499 } else {
3500 replaced_remote_description = std::move(pending_remote_description_);
3501 pending_remote_description_ = std::move(desc);
3502 }
3503
3504 // Transport and Media channels will be created only when offer is set.
3505 if (action == kOffer &&
3506 !CreateChannels(remote_description()->description())) {
3507 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3508 // is applied. Restore back to old description.
3509 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3510 err_desc);
3511 }
3512
3513 // Remove unused channels if MediaContentDescription is rejected.
3514 RemoveUnusedChannels(remote_description()->description());
3515
3516 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3517 // is called.
3518 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3519 return false;
3520 }
3521
3522 if (local_description() &&
3523 !UseCandidatesInSessionDescription(remote_description())) {
3524 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3525 err_desc);
3526 }
3527
3528 if (old_remote_description) {
3529 for (const cricket::ContentInfo& content :
3530 old_remote_description->description()->contents()) {
3531 // Check if this new SessionDescription contains new ICE ufrag and
3532 // password that indicates the remote peer requests an ICE restart.
3533 // TODO(deadbeef): When we start storing both the current and pending
3534 // remote description, this should reset pending_ice_restarts and compare
3535 // against the current description.
3536 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3537 content.name)) {
3538 if (action == kOffer) {
3539 pending_ice_restarts_.insert(content.name);
3540 }
3541 } else {
3542 // We retain all received candidates only if ICE is not restarted.
3543 // When ICE is restarted, all previous candidates belong to an old
3544 // generation and should not be kept.
3545 // TODO(deadbeef): This goes against the W3C spec which says the remote
3546 // description should only contain candidates from the last set remote
3547 // description plus any candidates added since then. We should remove
3548 // this once we're sure it won't break anything.
3549 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3550 old_remote_description, content.name, desc_ptr);
3551 }
3552 }
3553 }
3554
3555 if (error() != ERROR_NONE) {
3556 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3557 err_desc);
3558 }
3559
3560 // Set the the ICE connection state to connecting since the connection may
3561 // become writable with peer reflexive candidates before any remote candidate
3562 // is signaled.
3563 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3564 // is to have a new signal the indicates a change in checking state from the
3565 // transport and expose a new checking() member from transport that can be
3566 // read to determine the current checking state. The existing SignalConnecting
3567 // actually means "gathering candidates", so cannot be be used here.
3568 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3569 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3570 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3571 }
3572 return true;
3573}
3574
3575// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3576// vector of BaseChannel pointers instead of separate voice and video channel
3577// vectors. At that point, this will become a simple getter.
3578std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3579 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003580 if (voice_channel()) {
3581 channels.push_back(voice_channel());
3582 }
3583 if (video_channel()) {
3584 channels.push_back(video_channel());
3585 }
Steve Anton75737c02017-11-06 10:37:17 -08003586 if (rtp_data_channel_) {
3587 channels.push_back(rtp_data_channel_);
3588 }
3589 return channels;
3590}
3591
3592void PeerConnection::SetError(Error error, const std::string& error_desc) {
3593 RTC_DCHECK(signaling_thread()->IsCurrent());
3594 if (error != error_) {
3595 error_ = error;
3596 error_desc_ = error_desc;
3597 }
3598}
3599
3600bool PeerConnection::UpdateSessionState(Action action,
3601 cricket::ContentSource source,
3602 std::string* err_desc) {
3603 RTC_DCHECK(signaling_thread()->IsCurrent());
3604
3605 // If there's already a pending error then no state transition should happen.
3606 // But all call-sites should be verifying this before calling us!
3607 RTC_DCHECK(error() == ERROR_NONE);
3608 std::string td_err;
3609 if (action == kOffer) {
3610 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3611 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3612 }
3613 ChangeSignalingState(source == cricket::CS_LOCAL
3614 ? PeerConnectionInterface::kHaveLocalOffer
3615 : PeerConnectionInterface::kHaveRemoteOffer);
3616 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3617 SetError(ERROR_CONTENT, *err_desc);
3618 }
3619 if (error() != ERROR_NONE) {
3620 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3621 }
3622 } else if (action == kPrAnswer) {
3623 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3624 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3625 }
3626 EnableChannels();
3627 ChangeSignalingState(source == cricket::CS_LOCAL
3628 ? PeerConnectionInterface::kHaveLocalPrAnswer
3629 : PeerConnectionInterface::kHaveRemotePrAnswer);
3630 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3631 SetError(ERROR_CONTENT, *err_desc);
3632 }
3633 if (error() != ERROR_NONE) {
3634 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3635 }
3636 } else if (action == kAnswer) {
3637 const cricket::ContentGroup* local_bundle =
3638 local_description()->description()->GetGroupByName(
3639 cricket::GROUP_TYPE_BUNDLE);
3640 const cricket::ContentGroup* remote_bundle =
3641 remote_description()->description()->GetGroupByName(
3642 cricket::GROUP_TYPE_BUNDLE);
3643 if (local_bundle && remote_bundle) {
3644 // The answerer decides the transport to bundle on.
3645 const cricket::ContentGroup* answer_bundle =
3646 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3647 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003648 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003649 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3650 }
3651 }
3652 // Only push down the transport description after enabling BUNDLE; we don't
3653 // want to push down a description on a transport about to be destroyed.
3654 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3655 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3656 }
3657 EnableChannels();
3658 ChangeSignalingState(PeerConnectionInterface::kStable);
3659 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3660 SetError(ERROR_CONTENT, *err_desc);
3661 }
3662 if (error() != ERROR_NONE) {
3663 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3664 }
3665 }
3666 return true;
3667}
3668
3669PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3670 if (type == SessionDescriptionInterface::kOffer) {
3671 return PeerConnection::kOffer;
3672 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3673 return PeerConnection::kPrAnswer;
3674 } else if (type == SessionDescriptionInterface::kAnswer) {
3675 return PeerConnection::kAnswer;
3676 }
3677 RTC_NOTREACHED() << "unknown action type";
3678 return PeerConnection::kOffer;
3679}
3680
3681bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3682 cricket::ContentSource source,
3683 std::string* err) {
3684 const SessionDescription* sdesc =
3685 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3686 ->description();
3687 RTC_DCHECK(sdesc);
3688 bool all_success = true;
3689 for (auto* channel : Channels()) {
3690 // TODO(steveanton): Add support for multiple channels of the same type.
3691 const ContentInfo* content_info =
3692 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3693 if (!content_info) {
3694 continue;
3695 }
3696 const MediaContentDescription* content_desc =
3697 static_cast<const MediaContentDescription*>(content_info->description);
3698 if (content_desc && !content_info->rejected) {
3699 bool success = (source == cricket::CS_LOCAL)
3700 ? channel->SetLocalContent(content_desc, action, err)
3701 : channel->SetRemoteContent(content_desc, action, err);
3702 if (!success) {
3703 all_success = false;
3704 break;
3705 }
3706 }
3707 }
3708 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3709 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3710 if (sctp_transport_ && local_description() && remote_description() &&
3711 cricket::GetFirstDataContent(local_description()->description()) &&
3712 cricket::GetFirstDataContent(remote_description()->description())) {
3713 all_success &= network_thread()->Invoke<bool>(
3714 RTC_FROM_HERE,
3715 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3716 }
3717 return all_success;
3718}
3719
3720bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3721 RTC_DCHECK(network_thread()->IsCurrent());
3722 RTC_DCHECK(local_description());
3723 RTC_DCHECK(remote_description());
3724 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3725 // When we support "max-message-size", that would also be pushed down here.
3726 return sctp_transport_->Start(
3727 GetSctpPort(local_description()->description()),
3728 GetSctpPort(remote_description()->description()));
3729}
3730
3731bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3732 cricket::ContentAction action,
3733 std::string* error_desc) {
3734 RTC_DCHECK(signaling_thread()->IsCurrent());
3735
3736 if (source == cricket::CS_LOCAL) {
3737 return PushdownLocalTransportDescription(local_description()->description(),
3738 action, error_desc);
3739 }
3740 return PushdownRemoteTransportDescription(remote_description()->description(),
3741 action, error_desc);
3742}
3743
3744bool PeerConnection::PushdownLocalTransportDescription(
3745 const SessionDescription* sdesc,
3746 cricket::ContentAction action,
3747 std::string* err) {
3748 RTC_DCHECK(signaling_thread()->IsCurrent());
3749
3750 if (!sdesc) {
3751 return false;
3752 }
3753
3754 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3755 if (!transport_controller_->SetLocalTransportDescription(
3756 tinfo.content_name, tinfo.description, action, err)) {
3757 return false;
3758 }
3759 }
3760
3761 return true;
3762}
3763
3764bool PeerConnection::PushdownRemoteTransportDescription(
3765 const SessionDescription* sdesc,
3766 cricket::ContentAction action,
3767 std::string* err) {
3768 RTC_DCHECK(signaling_thread()->IsCurrent());
3769
3770 if (!sdesc) {
3771 return false;
3772 }
3773
3774 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3775 if (!transport_controller_->SetRemoteTransportDescription(
3776 tinfo.content_name, tinfo.description, action, err)) {
3777 return false;
3778 }
3779 }
3780
3781 return true;
3782}
3783
3784bool PeerConnection::GetTransportDescription(
3785 const SessionDescription* description,
3786 const std::string& content_name,
3787 cricket::TransportDescription* tdesc) {
3788 if (!description || !tdesc) {
3789 return false;
3790 }
3791 const TransportInfo* transport_info =
3792 description->GetTransportInfoByName(content_name);
3793 if (!transport_info) {
3794 return false;
3795 }
3796 *tdesc = transport_info->description;
3797 return true;
3798}
3799
3800bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3801 const std::string* first_content_name = bundle.FirstContentName();
3802 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003803 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003804 return false;
3805 }
3806 const std::string& transport_name = *first_content_name;
3807
3808 auto maybe_set_transport = [this, bundle,
3809 transport_name](cricket::BaseChannel* ch) {
3810 if (!ch || !bundle.HasContentName(ch->content_name())) {
3811 return true;
3812 }
3813
3814 std::string old_transport_name = ch->transport_name();
3815 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003816 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3817 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003818 return true;
3819 }
3820
3821 cricket::DtlsTransportInternal* rtp_dtls_transport =
3822 transport_controller_->CreateDtlsTransport(
3823 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3824 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3825 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3826 if (need_rtcp) {
3827 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3828 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3829 }
3830
3831 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003832 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3833 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003834 transport_controller_->DestroyDtlsTransport(
3835 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3836 // If the channel needs rtcp, it means that the channel used to have a
3837 // rtcp transport which needs to be deleted now.
3838 if (need_rtcp) {
3839 transport_controller_->DestroyDtlsTransport(
3840 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3841 }
3842 return true;
3843 };
3844
3845 if (!maybe_set_transport(voice_channel()) ||
3846 !maybe_set_transport(video_channel()) ||
3847 !maybe_set_transport(rtp_data_channel())) {
3848 return false;
3849 }
3850 // For SCTP, transport creation/deletion happens here instead of in the
3851 // object itself.
3852 if (sctp_transport_) {
3853 RTC_DCHECK(sctp_transport_name_);
3854 RTC_DCHECK(sctp_content_name_);
3855 if (transport_name != *sctp_transport_name_ &&
3856 bundle.HasContentName(*sctp_content_name_)) {
3857 network_thread()->Invoke<void>(
3858 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3859 transport_name));
3860 }
3861 }
3862
3863 return true;
3864}
3865
Steve Anton75737c02017-11-06 10:37:17 -08003866cricket::IceConfig PeerConnection::ParseIceConfig(
3867 const PeerConnectionInterface::RTCConfiguration& config) const {
3868 cricket::ContinualGatheringPolicy gathering_policy;
3869 // TODO(honghaiz): Add the third continual gathering policy in
3870 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3871 switch (config.continual_gathering_policy) {
3872 case PeerConnectionInterface::GATHER_ONCE:
3873 gathering_policy = cricket::GATHER_ONCE;
3874 break;
3875 case PeerConnectionInterface::GATHER_CONTINUALLY:
3876 gathering_policy = cricket::GATHER_CONTINUALLY;
3877 break;
3878 default:
3879 RTC_NOTREACHED();
3880 gathering_policy = cricket::GATHER_ONCE;
3881 }
3882 cricket::IceConfig ice_config;
3883 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3884 ice_config.prioritize_most_likely_candidate_pairs =
3885 config.prioritize_most_likely_ice_candidate_pairs;
3886 ice_config.backup_connection_ping_interval =
3887 config.ice_backup_candidate_pair_ping_interval;
3888 ice_config.continual_gathering_policy = gathering_policy;
3889 ice_config.presume_writable_when_fully_relayed =
3890 config.presume_writable_when_fully_relayed;
3891 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3892 ice_config.regather_all_networks_interval_range =
3893 config.ice_regather_interval_range;
3894 return ice_config;
3895}
3896
Steve Anton75737c02017-11-06 10:37:17 -08003897bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3898 std::string* track_id) {
3899 if (!local_description()) {
3900 return false;
3901 }
3902 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3903 track_id);
3904}
3905
3906bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3907 std::string* track_id) {
3908 if (!remote_description()) {
3909 return false;
3910 }
3911 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3912 track_id);
3913}
3914
3915bool PeerConnection::SendData(const cricket::SendDataParams& params,
3916 const rtc::CopyOnWriteBuffer& payload,
3917 cricket::SendDataResult* result) {
3918 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003919 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3920 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003921 return false;
3922 }
3923 return rtp_data_channel_
3924 ? rtp_data_channel_->SendData(params, payload, result)
3925 : network_thread()->Invoke<bool>(
3926 RTC_FROM_HERE,
3927 Bind(&cricket::SctpTransportInternal::SendData,
3928 sctp_transport_.get(), params, payload, result));
3929}
3930
3931bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3932 if (!rtp_data_channel_ && !sctp_transport_) {
3933 // Don't log an error here, because DataChannels are expected to call
3934 // ConnectDataChannel in this state. It's the only way to initially tell
3935 // whether or not the underlying transport is ready.
3936 return false;
3937 }
3938 if (rtp_data_channel_) {
3939 rtp_data_channel_->SignalReadyToSendData.connect(
3940 webrtc_data_channel, &DataChannel::OnChannelReady);
3941 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3942 &DataChannel::OnDataReceived);
3943 } else {
3944 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3945 &DataChannel::OnChannelReady);
3946 SignalSctpDataReceived.connect(webrtc_data_channel,
3947 &DataChannel::OnDataReceived);
3948 SignalSctpStreamClosedRemotely.connect(
3949 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3950 }
3951 return true;
3952}
3953
3954void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3955 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003956 RTC_LOG(LS_ERROR)
3957 << "DisconnectDataChannel called when rtp_data_channel_ and "
3958 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003959 return;
3960 }
3961 if (rtp_data_channel_) {
3962 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3963 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3964 } else {
3965 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3966 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3967 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3968 }
3969}
3970
3971void PeerConnection::AddSctpDataStream(int sid) {
3972 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003973 RTC_LOG(LS_ERROR)
3974 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003975 return;
3976 }
3977 network_thread()->Invoke<void>(
3978 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3979 sctp_transport_.get(), sid));
3980}
3981
3982void PeerConnection::RemoveSctpDataStream(int sid) {
3983 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003984 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3985 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003986 return;
3987 }
3988 network_thread()->Invoke<void>(
3989 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3990 sctp_transport_.get(), sid));
3991}
3992
3993bool PeerConnection::ReadyToSendData() const {
3994 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3995 sctp_ready_to_send_data_;
3996}
3997
3998std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3999 RTC_DCHECK(signaling_thread()->IsCurrent());
4000 ChannelNamePairs channel_name_pairs;
4001 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004002 channel_name_pairs.voice = ChannelNamePair(
4003 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004004 }
4005 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004006 channel_name_pairs.video = ChannelNamePair(
4007 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004008 }
4009 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004010 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004011 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004012 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004013 }
4014 if (sctp_transport_) {
4015 RTC_DCHECK(sctp_content_name_);
4016 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004017 channel_name_pairs.data =
4018 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004019 }
4020 return GetSessionStats(channel_name_pairs);
4021}
4022
4023std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4024 const ChannelNamePairs& channel_name_pairs) {
4025 if (network_thread()->IsCurrent()) {
4026 return GetSessionStats_n(channel_name_pairs);
4027 }
4028 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4029 RTC_FROM_HERE,
4030 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4031}
4032
4033bool PeerConnection::GetLocalCertificate(
4034 const std::string& transport_name,
4035 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4036 return transport_controller_->GetLocalCertificate(transport_name,
4037 certificate);
4038}
4039
4040std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4041 const std::string& transport_name) {
4042 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4043}
4044
4045cricket::DataChannelType PeerConnection::data_channel_type() const {
4046 return data_channel_type_;
4047}
4048
4049bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4050 return pending_ice_restarts_.find(content_name) !=
4051 pending_ice_restarts_.end();
4052}
4053
Steve Anton75737c02017-11-06 10:37:17 -08004054bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4055 return transport_controller_->NeedsIceRestart(content_name);
4056}
4057
4058void PeerConnection::OnCertificateReady(
4059 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4060 transport_controller_->SetLocalCertificate(certificate);
4061}
4062
4063void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
4064 SetError(ERROR_TRANSPORT,
4065 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
4066}
4067
4068void PeerConnection::OnTransportControllerConnectionState(
4069 cricket::IceConnectionState state) {
4070 switch (state) {
4071 case cricket::kIceConnectionConnecting:
4072 // If the current state is Connected or Completed, then there were
4073 // writable channels but now there are not, so the next state must
4074 // be Disconnected.
4075 // kIceConnectionConnecting is currently used as the default,
4076 // un-connected state by the TransportController, so its only use is
4077 // detecting disconnections.
4078 if (ice_connection_state_ ==
4079 PeerConnectionInterface::kIceConnectionConnected ||
4080 ice_connection_state_ ==
4081 PeerConnectionInterface::kIceConnectionCompleted) {
4082 SetIceConnectionState(
4083 PeerConnectionInterface::kIceConnectionDisconnected);
4084 }
4085 break;
4086 case cricket::kIceConnectionFailed:
4087 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4088 break;
4089 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004090 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4091 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004092 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4093 break;
4094 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004095 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4096 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004097 if (ice_connection_state_ !=
4098 PeerConnectionInterface::kIceConnectionConnected) {
4099 // If jumping directly from "checking" to "connected",
4100 // signal "connected" first.
4101 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4102 }
4103 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4104 if (metrics_observer()) {
4105 ReportTransportStats();
4106 }
4107 break;
4108 default:
4109 RTC_NOTREACHED();
4110 }
4111}
4112
4113void PeerConnection::OnTransportControllerCandidatesGathered(
4114 const std::string& transport_name,
4115 const cricket::Candidates& candidates) {
4116 RTC_DCHECK(signaling_thread()->IsCurrent());
4117 int sdp_mline_index;
4118 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004119 RTC_LOG(LS_ERROR)
4120 << "OnTransportControllerCandidatesGathered: content name "
4121 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004122 return;
4123 }
4124
4125 for (cricket::Candidates::const_iterator citer = candidates.begin();
4126 citer != candidates.end(); ++citer) {
4127 // Use transport_name as the candidate media id.
4128 std::unique_ptr<JsepIceCandidate> candidate(
4129 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4130 if (local_description()) {
4131 mutable_local_description()->AddCandidate(candidate.get());
4132 }
4133 OnIceCandidate(std::move(candidate));
4134 }
4135}
4136
4137void PeerConnection::OnTransportControllerCandidatesRemoved(
4138 const std::vector<cricket::Candidate>& candidates) {
4139 RTC_DCHECK(signaling_thread()->IsCurrent());
4140 // Sanity check.
4141 for (const cricket::Candidate& candidate : candidates) {
4142 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004143 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4144 << "empty content name in candidate "
4145 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004146 return;
4147 }
4148 }
4149
4150 if (local_description()) {
4151 mutable_local_description()->RemoveCandidates(candidates);
4152 }
4153 OnIceCandidatesRemoved(candidates);
4154}
4155
4156void PeerConnection::OnTransportControllerDtlsHandshakeError(
4157 rtc::SSLHandshakeError error) {
4158 if (metrics_observer()) {
4159 metrics_observer()->IncrementEnumCounter(
4160 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4161 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4162 }
4163}
4164
4165// Enabling voice and video (and RTP data) channels.
4166void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004167 if (voice_channel() && !voice_channel()->enabled()) {
4168 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004169 }
4170
Steve Anton4171afb2017-11-20 10:20:22 -08004171 if (video_channel() && !video_channel()->enabled()) {
4172 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004173 }
4174
Steve Anton4171afb2017-11-20 10:20:22 -08004175 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004176 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004177 }
Steve Anton75737c02017-11-06 10:37:17 -08004178}
4179
4180// Returns the media index for a local ice candidate given the content name.
4181bool PeerConnection::GetLocalCandidateMediaIndex(
4182 const std::string& content_name,
4183 int* sdp_mline_index) {
4184 if (!local_description() || !sdp_mline_index) {
4185 return false;
4186 }
4187
4188 bool content_found = false;
4189 const ContentInfos& contents = local_description()->description()->contents();
4190 for (size_t index = 0; index < contents.size(); ++index) {
4191 if (contents[index].name == content_name) {
4192 *sdp_mline_index = static_cast<int>(index);
4193 content_found = true;
4194 break;
4195 }
4196 }
4197 return content_found;
4198}
4199
4200bool PeerConnection::UseCandidatesInSessionDescription(
4201 const SessionDescriptionInterface* remote_desc) {
4202 if (!remote_desc) {
4203 return true;
4204 }
4205 bool ret = true;
4206
4207 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4208 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4209 for (size_t n = 0; n < candidates->count(); ++n) {
4210 const IceCandidateInterface* candidate = candidates->at(n);
4211 bool valid = false;
4212 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4213 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004214 RTC_LOG(LS_INFO)
4215 << "UseCandidatesInSessionDescription: Not ready to use "
4216 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004217 }
4218 continue;
4219 }
4220 ret = UseCandidate(candidate);
4221 if (!ret) {
4222 break;
4223 }
4224 }
4225 }
4226 return ret;
4227}
4228
4229bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4230 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4231 size_t remote_content_size =
4232 remote_description()->description()->contents().size();
4233 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004234 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004235 return false;
4236 }
4237
4238 cricket::ContentInfo content =
4239 remote_description()->description()->contents()[mediacontent_index];
4240 std::vector<cricket::Candidate> candidates;
4241 candidates.push_back(candidate->candidate());
4242 // Invoking BaseSession method to handle remote candidates.
4243 std::string error;
4244 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4245 &error)) {
4246 // Candidates successfully submitted for checking.
4247 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4248 ice_connection_state_ ==
4249 PeerConnectionInterface::kIceConnectionDisconnected) {
4250 // If state is New, then the session has just gotten its first remote ICE
4251 // candidates, so go to Checking.
4252 // If state is Disconnected, the session is re-using old candidates or
4253 // receiving additional ones, so go to Checking.
4254 // If state is Connected, stay Connected.
4255 // TODO(bemasc): If state is Connected, and the new candidates are for a
4256 // newly added transport, then the state actually _should_ move to
4257 // checking. Add a way to distinguish that case.
4258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4259 }
4260 // TODO(bemasc): If state is Completed, go back to Connected.
4261 } else {
4262 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004263 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004264 }
4265 }
4266 return true;
4267}
4268
4269void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4270 // TODO(steveanton): Add support for multiple audio/video channels.
4271 // Destroy video channel first since it may have a pointer to the
4272 // voice channel.
4273 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4274 if ((!video_info || video_info->rejected) && video_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004275 DestroyVideoChannel(video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004276 }
4277
4278 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4279 if ((!voice_info || voice_info->rejected) && voice_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004280 DestroyVoiceChannel(voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004281 }
4282
4283 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4284 if (!data_info || data_info->rejected) {
4285 if (rtp_data_channel_) {
4286 DestroyDataChannel();
4287 }
4288 if (sctp_transport_) {
4289 OnDataChannelDestroyed();
4290 network_thread()->Invoke<void>(
4291 RTC_FROM_HERE,
4292 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4293 }
4294 }
4295}
4296
4297// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4298// if the channel is not part of any bundle.
4299const std::string* PeerConnection::GetBundleTransportName(
4300 const cricket::ContentInfo* content,
4301 const cricket::ContentGroup* bundle) {
4302 if (!bundle) {
4303 return nullptr;
4304 }
4305 const std::string* first_content_name = bundle->FirstContentName();
4306 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004307 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004308 return nullptr;
4309 }
4310 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004312 return nullptr;
4313 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004314 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4315 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004316 return first_content_name;
4317}
4318
4319bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4320 // TODO(steveanton): Add support for multiple audio/video channels.
4321 const cricket::ContentGroup* bundle_group = nullptr;
4322 if (configuration_.bundle_policy ==
4323 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4324 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4325 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004326 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004327 return false;
4328 }
4329 }
4330 // Creating the media channels and transport proxies.
4331 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4332 if (voice && !voice->rejected && !voice_channel()) {
4333 if (!CreateVoiceChannel(voice,
4334 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004335 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004336 return false;
4337 }
4338 }
4339
4340 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4341 if (video && !video->rejected && !video_channel()) {
4342 if (!CreateVideoChannel(video,
4343 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004344 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004345 return false;
4346 }
4347 }
4348
4349 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4350 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4351 !rtp_data_channel_ && !sctp_transport_) {
4352 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004353 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004354 return false;
4355 }
4356 }
4357
4358 return true;
4359}
4360
Steve Anton4171afb2017-11-20 10:20:22 -08004361// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004362bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4363 const std::string* bundle_transport) {
4364 // TODO(steveanton): Check to see if it's safe to create multiple voice
4365 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004366 RTC_DCHECK(!voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004367
4368 std::string transport_name =
4369 bundle_transport ? *bundle_transport : content->name;
4370
4371 cricket::DtlsTransportInternal* rtp_dtls_transport =
4372 transport_controller_->CreateDtlsTransport(
4373 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4374 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4375 if (configuration_.rtcp_mux_policy !=
4376 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4377 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4378 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4379 }
4380
4381 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4382 call_.get(), configuration_.media_config, rtp_dtls_transport,
4383 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4384 content->name, SrtpRequired(), audio_options_);
4385 if (!voice_channel) {
4386 transport_controller_->DestroyDtlsTransport(
4387 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4388 if (rtcp_dtls_transport) {
4389 transport_controller_->DestroyDtlsTransport(
4390 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4391 }
4392 return false;
4393 }
Steve Anton75737c02017-11-06 10:37:17 -08004394 voice_channel->SignalRtcpMuxFullyActive.connect(
4395 this, &PeerConnection::DestroyRtcpTransport_n);
4396 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4397 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004398 voice_channel->SignalSentPacket.connect(this,
4399 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004400
4401 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4402
Steve Anton75737c02017-11-06 10:37:17 -08004403 return true;
4404}
4405
Steve Anton4171afb2017-11-20 10:20:22 -08004406// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004407bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4408 const std::string* bundle_transport) {
4409 // TODO(steveanton): Check to see if it's safe to create multiple video
4410 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004411 RTC_DCHECK(!video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004412
4413 std::string transport_name =
4414 bundle_transport ? *bundle_transport : content->name;
4415
4416 cricket::DtlsTransportInternal* rtp_dtls_transport =
4417 transport_controller_->CreateDtlsTransport(
4418 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4419 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4420 if (configuration_.rtcp_mux_policy !=
4421 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4422 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4423 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4424 }
4425
4426 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4427 call_.get(), configuration_.media_config, rtp_dtls_transport,
4428 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4429 content->name, SrtpRequired(), video_options_);
4430
4431 if (!video_channel) {
4432 transport_controller_->DestroyDtlsTransport(
4433 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4434 if (rtcp_dtls_transport) {
4435 transport_controller_->DestroyDtlsTransport(
4436 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4437 }
4438 return false;
4439 }
Steve Anton75737c02017-11-06 10:37:17 -08004440 video_channel->SignalRtcpMuxFullyActive.connect(
4441 this, &PeerConnection::DestroyRtcpTransport_n);
4442 video_channel->SignalDtlsSrtpSetupFailure.connect(
4443 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004444 video_channel->SignalSentPacket.connect(this,
4445 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004446
4447 GetVideoTransceiver()->internal()->SetChannel(video_channel);
4448
Steve Anton75737c02017-11-06 10:37:17 -08004449 return true;
4450}
4451
4452bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4453 const std::string* bundle_transport) {
4454 const std::string transport_name =
4455 bundle_transport ? *bundle_transport : content->name;
4456 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4457 if (sctp) {
4458 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004459 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004460 << "Trying to create SCTP transport, but didn't compile with "
4461 "SCTP support (HAVE_SCTP)";
4462 return false;
4463 }
4464 if (!network_thread()->Invoke<bool>(
4465 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4466 this, content->name, transport_name))) {
4467 return false;
4468 }
4469 } else {
4470 std::string transport_name =
4471 bundle_transport ? *bundle_transport : content->name;
4472 cricket::DtlsTransportInternal* rtp_dtls_transport =
4473 transport_controller_->CreateDtlsTransport(
4474 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4475 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4476 if (configuration_.rtcp_mux_policy !=
4477 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4478 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4479 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4480 }
4481
4482 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4483 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4484 transport_controller_->signaling_thread(), content->name,
4485 SrtpRequired());
4486
4487 if (!rtp_data_channel_) {
4488 transport_controller_->DestroyDtlsTransport(
4489 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4490 if (rtcp_dtls_transport) {
4491 transport_controller_->DestroyDtlsTransport(
4492 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4493 }
4494 return false;
4495 }
4496
4497 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4498 this, &PeerConnection::DestroyRtcpTransport_n);
4499 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4500 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4501 rtp_data_channel_->SignalSentPacket.connect(
4502 this, &PeerConnection::OnSentPacket_w);
4503 }
4504
Steve Antond25da372017-11-06 14:50:29 -08004505 for (const auto& channel : sctp_data_channels_) {
4506 channel->OnTransportChannelCreated();
4507 }
Steve Anton75737c02017-11-06 10:37:17 -08004508
4509 return true;
4510}
4511
4512Call::Stats PeerConnection::GetCallStats() {
4513 if (!worker_thread()->IsCurrent()) {
4514 return worker_thread()->Invoke<Call::Stats>(
4515 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4516 }
4517 if (call_) {
4518 return call_->GetStats();
4519 } else {
4520 return Call::Stats();
4521 }
4522}
4523
4524std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4525 const ChannelNamePairs& channel_name_pairs) {
4526 RTC_DCHECK(network_thread()->IsCurrent());
4527 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4528 for (const auto channel_name_pair :
4529 {&channel_name_pairs.voice, &channel_name_pairs.video,
4530 &channel_name_pairs.data}) {
4531 if (*channel_name_pair) {
4532 cricket::TransportStats transport_stats;
4533 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4534 &transport_stats)) {
4535 return nullptr;
4536 }
4537 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4538 (*channel_name_pair)->transport_name;
4539 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4540 std::move(transport_stats);
4541 }
4542 }
4543 return session_stats;
4544}
4545
4546bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4547 const std::string& transport_name) {
4548 RTC_DCHECK(network_thread()->IsCurrent());
4549 RTC_DCHECK(sctp_factory_);
4550 cricket::DtlsTransportInternal* tc =
4551 transport_controller_->CreateDtlsTransport_n(
4552 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4553 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4554 RTC_DCHECK(sctp_transport_);
4555 sctp_invoker_.reset(new rtc::AsyncInvoker());
4556 sctp_transport_->SignalReadyToSendData.connect(
4557 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4558 sctp_transport_->SignalDataReceived.connect(
4559 this, &PeerConnection::OnSctpTransportDataReceived_n);
4560 sctp_transport_->SignalStreamClosedRemotely.connect(
4561 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004562 sctp_transport_name_ = transport_name;
4563 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004564 return true;
4565}
4566
4567void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4568 RTC_DCHECK(network_thread()->IsCurrent());
4569 RTC_DCHECK(sctp_transport_);
4570 RTC_DCHECK(sctp_transport_name_);
4571 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004572 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004573 cricket::DtlsTransportInternal* tc =
4574 transport_controller_->CreateDtlsTransport_n(
4575 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4576 sctp_transport_->SetTransportChannel(tc);
4577 transport_controller_->DestroyDtlsTransport_n(
4578 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4579}
4580
4581void PeerConnection::DestroySctpTransport_n() {
4582 RTC_DCHECK(network_thread()->IsCurrent());
4583 sctp_transport_.reset(nullptr);
4584 sctp_content_name_.reset();
4585 sctp_transport_name_.reset();
4586 sctp_invoker_.reset(nullptr);
4587 sctp_ready_to_send_data_ = false;
4588}
4589
4590void PeerConnection::OnSctpTransportReadyToSendData_n() {
4591 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4592 RTC_DCHECK(network_thread()->IsCurrent());
4593 // Note: Cannot use rtc::Bind here because it will grab a reference to
4594 // PeerConnection and potentially cause PeerConnection to live longer than
4595 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4596 // be destroyed before PeerConnection is destroyed, and at that point all
4597 // pending tasks will be cleared.
4598 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4599 OnSctpTransportReadyToSendData_s(true);
4600 });
4601}
4602
4603void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4604 RTC_DCHECK(signaling_thread()->IsCurrent());
4605 sctp_ready_to_send_data_ = ready;
4606 SignalSctpReadyToSendData(ready);
4607}
4608
4609void PeerConnection::OnSctpTransportDataReceived_n(
4610 const cricket::ReceiveDataParams& params,
4611 const rtc::CopyOnWriteBuffer& payload) {
4612 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4613 RTC_DCHECK(network_thread()->IsCurrent());
4614 // Note: Cannot use rtc::Bind here because it will grab a reference to
4615 // PeerConnection and potentially cause PeerConnection to live longer than
4616 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4617 // be destroyed before PeerConnection is destroyed, and at that point all
4618 // pending tasks will be cleared.
4619 sctp_invoker_->AsyncInvoke<void>(
4620 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4621 OnSctpTransportDataReceived_s(params, payload);
4622 });
4623}
4624
4625void PeerConnection::OnSctpTransportDataReceived_s(
4626 const cricket::ReceiveDataParams& params,
4627 const rtc::CopyOnWriteBuffer& payload) {
4628 RTC_DCHECK(signaling_thread()->IsCurrent());
4629 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4630 // Received OPEN message; parse and signal that a new data channel should
4631 // be created.
4632 std::string label;
4633 InternalDataChannelInit config;
4634 config.id = params.ssrc;
4635 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004636 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4637 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004638 return;
4639 }
4640 config.open_handshake_role = InternalDataChannelInit::kAcker;
4641 OnDataChannelOpenMessage(label, config);
4642 } else {
4643 // Otherwise just forward the signal.
4644 SignalSctpDataReceived(params, payload);
4645 }
4646}
4647
4648void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4649 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4650 RTC_DCHECK(network_thread()->IsCurrent());
4651 sctp_invoker_->AsyncInvoke<void>(
4652 RTC_FROM_HERE, signaling_thread(),
4653 rtc::Bind(&sigslot::signal1<int>::operator(),
4654 &SignalSctpStreamClosedRemotely, sid));
4655}
4656
4657// Returns false if bundle is enabled and rtcp_mux is disabled.
4658bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4659 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4660 if (!bundle_enabled)
4661 return true;
4662
4663 const cricket::ContentGroup* bundle_group =
4664 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4665 RTC_DCHECK(bundle_group != NULL);
4666
4667 const cricket::ContentInfos& contents = desc->contents();
4668 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4669 citer != contents.end(); ++citer) {
4670 const cricket::ContentInfo* content = (&*citer);
4671 RTC_DCHECK(content != NULL);
4672 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4673 content->type == cricket::NS_JINGLE_RTP) {
4674 if (!HasRtcpMuxEnabled(content))
4675 return false;
4676 }
4677 }
4678 // RTCP-MUX is enabled in all the contents.
4679 return true;
4680}
4681
4682bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4683 const cricket::MediaContentDescription* description =
4684 static_cast<cricket::MediaContentDescription*>(content->description);
4685 return description->rtcp_mux();
4686}
4687
4688bool PeerConnection::ValidateSessionDescription(
4689 const SessionDescriptionInterface* sdesc,
4690 cricket::ContentSource source,
4691 std::string* err_desc) {
4692 std::string type;
4693 if (error() != ERROR_NONE) {
4694 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4695 }
4696
4697 if (!sdesc || !sdesc->description()) {
4698 return BadSdp(source, type, kInvalidSdp, err_desc);
4699 }
4700
4701 type = sdesc->type();
4702 Action action = GetAction(sdesc->type());
4703 if (source == cricket::CS_LOCAL) {
4704 if (!ExpectSetLocalDescription(action))
4705 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4706 } else {
4707 if (!ExpectSetRemoteDescription(action))
4708 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4709 }
4710
4711 // Verify crypto settings.
4712 std::string crypto_error;
4713 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4714 dtls_enabled_) &&
4715 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4716 return BadSdp(source, type, crypto_error, err_desc);
4717 }
4718
4719 // Verify ice-ufrag and ice-pwd.
4720 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4721 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4722 }
4723
4724 if (!ValidateBundleSettings(sdesc->description())) {
4725 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4726 }
4727
4728 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4729 // m-lines that do not rtcp-mux enabled.
4730
4731 // Verify m-lines in Answer when compared against Offer.
4732 if (action == kAnswer || action == kPrAnswer) {
4733 const cricket::SessionDescription* offer_desc =
4734 (source == cricket::CS_LOCAL) ? remote_description()->description()
4735 : local_description()->description();
4736 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4737 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4738 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4739 }
4740 } else {
4741 const cricket::SessionDescription* current_desc = nullptr;
4742 if (source == cricket::CS_LOCAL && local_description()) {
4743 current_desc = local_description()->description();
4744 } else if (source == cricket::CS_REMOTE && remote_description()) {
4745 current_desc = remote_description()->description();
4746 }
4747 // The re-offers should respect the order of m= sections in current
4748 // description. See RFC3264 Section 8 paragraph 4 for more details.
4749 if (current_desc &&
4750 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4751 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4752 }
4753 }
4754
4755 return true;
4756}
4757
4758bool PeerConnection::ExpectSetLocalDescription(Action action) {
4759 PeerConnectionInterface::SignalingState state = signaling_state();
4760 if (action == kOffer) {
4761 return (state == PeerConnectionInterface::kStable) ||
4762 (state == PeerConnectionInterface::kHaveLocalOffer);
4763 } else { // Answer or PrAnswer
4764 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4765 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4766 }
4767}
4768
4769bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4770 PeerConnectionInterface::SignalingState state = signaling_state();
4771 if (action == kOffer) {
4772 return (state == PeerConnectionInterface::kStable) ||
4773 (state == PeerConnectionInterface::kHaveRemoteOffer);
4774 } else { // Answer or PrAnswer.
4775 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4776 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4777 }
4778}
4779
4780std::string PeerConnection::GetSessionErrorMsg() {
4781 std::ostringstream desc;
4782 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4783 desc << kSessionErrorDesc << error_desc() << ".";
4784 return desc.str();
4785}
4786
4787// We need to check the local/remote description for the Transport instead of
4788// the session, because a new Transport added during renegotiation may have
4789// them unset while the session has them set from the previous negotiation.
4790// Not doing so may trigger the auto generation of transport description and
4791// mess up DTLS identity information, ICE credential, etc.
4792bool PeerConnection::ReadyToUseRemoteCandidate(
4793 const IceCandidateInterface* candidate,
4794 const SessionDescriptionInterface* remote_desc,
4795 bool* valid) {
4796 *valid = true;
4797
4798 const SessionDescriptionInterface* current_remote_desc =
4799 remote_desc ? remote_desc : remote_description();
4800
4801 if (!current_remote_desc) {
4802 return false;
4803 }
4804
4805 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4806 size_t remote_content_size =
4807 current_remote_desc->description()->contents().size();
4808 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004809 RTC_LOG(LS_ERROR)
4810 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4811 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004812
4813 *valid = false;
4814 return false;
4815 }
4816
4817 cricket::ContentInfo content =
4818 current_remote_desc->description()->contents()[mediacontent_index];
4819
4820 const std::string transport_name = GetTransportName(content.name);
4821 if (transport_name.empty()) {
4822 return false;
4823 }
4824 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4825}
4826
4827bool PeerConnection::SrtpRequired() const {
4828 return dtls_enabled_ ||
4829 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4830}
4831
4832void PeerConnection::OnTransportControllerGatheringState(
4833 cricket::IceGatheringState state) {
4834 RTC_DCHECK(signaling_thread()->IsCurrent());
4835 if (state == cricket::kIceGatheringGathering) {
4836 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4837 } else if (state == cricket::kIceGatheringComplete) {
4838 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4839 }
4840}
4841
4842void PeerConnection::ReportTransportStats() {
4843 // Use a set so we don't report the same stats twice if two channels share
4844 // a transport.
4845 std::set<std::string> transport_names;
4846 if (voice_channel()) {
4847 transport_names.insert(voice_channel()->transport_name());
4848 }
4849 if (video_channel()) {
4850 transport_names.insert(video_channel()->transport_name());
4851 }
4852 if (rtp_data_channel()) {
4853 transport_names.insert(rtp_data_channel()->transport_name());
4854 }
4855 if (sctp_transport_name_) {
4856 transport_names.insert(*sctp_transport_name_);
4857 }
4858 for (const auto& name : transport_names) {
4859 cricket::TransportStats stats;
4860 if (transport_controller_->GetStats(name, &stats)) {
4861 ReportBestConnectionState(stats);
4862 ReportNegotiatedCiphers(stats);
4863 }
4864 }
4865}
4866// Walk through the ConnectionInfos to gather best connection usage
4867// for IPv4 and IPv6.
4868void PeerConnection::ReportBestConnectionState(
4869 const cricket::TransportStats& stats) {
4870 RTC_DCHECK(metrics_observer());
4871 for (cricket::TransportChannelStatsList::const_iterator it =
4872 stats.channel_stats.begin();
4873 it != stats.channel_stats.end(); ++it) {
4874 for (cricket::ConnectionInfos::const_iterator it_info =
4875 it->connection_infos.begin();
4876 it_info != it->connection_infos.end(); ++it_info) {
4877 if (!it_info->best_connection) {
4878 continue;
4879 }
4880
4881 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4882 const cricket::Candidate& local = it_info->local_candidate;
4883 const cricket::Candidate& remote = it_info->remote_candidate;
4884
4885 // Increment the counter for IceCandidatePairType.
4886 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4887 (local.type() == RELAY_PORT_TYPE &&
4888 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4889 type = kEnumCounterIceCandidatePairTypeTcp;
4890 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4891 type = kEnumCounterIceCandidatePairTypeUdp;
4892 } else {
4893 RTC_CHECK(0);
4894 }
4895 metrics_observer()->IncrementEnumCounter(
4896 type, GetIceCandidatePairCounter(local, remote),
4897 kIceCandidatePairMax);
4898
4899 // Increment the counter for IP type.
4900 if (local.address().family() == AF_INET) {
4901 metrics_observer()->IncrementEnumCounter(
4902 kEnumCounterAddressFamily, kBestConnections_IPv4,
4903 kPeerConnectionAddressFamilyCounter_Max);
4904
4905 } else if (local.address().family() == AF_INET6) {
4906 metrics_observer()->IncrementEnumCounter(
4907 kEnumCounterAddressFamily, kBestConnections_IPv6,
4908 kPeerConnectionAddressFamilyCounter_Max);
4909 } else {
4910 RTC_CHECK(0);
4911 }
4912
4913 return;
4914 }
4915 }
4916}
4917
4918void PeerConnection::ReportNegotiatedCiphers(
4919 const cricket::TransportStats& stats) {
4920 RTC_DCHECK(metrics_observer());
4921 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4922 return;
4923 }
4924
4925 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4926 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4927 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4928 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4929 return;
4930 }
4931
4932 PeerConnectionEnumCounterType srtp_counter_type;
4933 PeerConnectionEnumCounterType ssl_counter_type;
4934 if (stats.transport_name == cricket::CN_AUDIO) {
4935 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4936 ssl_counter_type = kEnumCounterAudioSslCipher;
4937 } else if (stats.transport_name == cricket::CN_VIDEO) {
4938 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4939 ssl_counter_type = kEnumCounterVideoSslCipher;
4940 } else if (stats.transport_name == cricket::CN_DATA) {
4941 srtp_counter_type = kEnumCounterDataSrtpCipher;
4942 ssl_counter_type = kEnumCounterDataSslCipher;
4943 } else {
4944 RTC_NOTREACHED();
4945 return;
4946 }
4947
4948 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4949 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4950 srtp_crypto_suite);
4951 }
4952 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4953 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4954 ssl_cipher_suite);
4955 }
4956}
4957
4958void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4959 RTC_DCHECK(worker_thread()->IsCurrent());
4960 RTC_DCHECK(call_);
4961 call_->OnSentPacket(sent_packet);
4962}
4963
4964const std::string PeerConnection::GetTransportName(
4965 const std::string& content_name) {
4966 cricket::BaseChannel* channel = GetChannel(content_name);
4967 if (!channel) {
4968 if (sctp_transport_) {
4969 RTC_DCHECK(sctp_content_name_);
4970 RTC_DCHECK(sctp_transport_name_);
4971 if (content_name == *sctp_content_name_) {
4972 return *sctp_transport_name_;
4973 }
4974 }
4975 // Return an empty string if failed to retrieve the transport name.
4976 return "";
4977 }
4978 return channel->transport_name();
4979}
4980
4981void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4982 RTC_DCHECK(network_thread()->IsCurrent());
4983 transport_controller_->DestroyDtlsTransport_n(
4984 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4985}
4986
Steve Anton4171afb2017-11-20 10:20:22 -08004987// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004988void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004989 RTC_DCHECK(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004990 RTC_DCHECK(video_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004991 RTC_DCHECK_EQ(GetVideoTransceiver()->internal()->channel(), video_channel);
4992 GetVideoTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004993 const std::string transport_name =
4994 video_channel->rtp_dtls_transport()->transport_name();
4995 const bool need_to_delete_rtcp =
4996 (video_channel->rtcp_dtls_transport() != nullptr);
4997 // The above need to be cached before destroying the video channel so that we
4998 // do not access uninitialized memory.
4999 channel_manager()->DestroyVideoChannel(video_channel);
5000 transport_controller_->DestroyDtlsTransport(
5001 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5002 if (need_to_delete_rtcp) {
5003 transport_controller_->DestroyDtlsTransport(
5004 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5005 }
5006}
5007
Steve Anton4171afb2017-11-20 10:20:22 -08005008// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08005009void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08005010 RTC_DCHECK(voice_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005011 RTC_DCHECK(voice_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08005012 RTC_DCHECK_EQ(GetAudioTransceiver()->internal()->channel(), voice_channel);
5013 GetAudioTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08005014 const std::string transport_name =
5015 voice_channel->rtp_dtls_transport()->transport_name();
5016 const bool need_to_delete_rtcp =
5017 (voice_channel->rtcp_dtls_transport() != nullptr);
5018 // The above need to be cached before destroying the video channel so that we
5019 // do not access uninitialized memory.
5020 channel_manager()->DestroyVoiceChannel(voice_channel);
5021 transport_controller_->DestroyDtlsTransport(
5022 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5023 if (need_to_delete_rtcp) {
5024 transport_controller_->DestroyDtlsTransport(
5025 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5026 }
5027}
5028
5029void PeerConnection::DestroyDataChannel() {
5030 OnDataChannelDestroyed();
5031 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
5032 std::string transport_name;
5033 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
5034 bool need_to_delete_rtcp =
5035 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
5036 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
5037 rtp_data_channel_ = nullptr;
5038 transport_controller_->DestroyDtlsTransport(
5039 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5040 if (need_to_delete_rtcp) {
5041 transport_controller_->DestroyDtlsTransport(
5042 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5043 }
5044}
5045
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005046} // namespace webrtc