blob: 7bb74e7166291ae62ba78dae2a28a3744c1b3bc5 [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_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800848 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
849 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800850 }
Steve Anton75737c02017-11-06 10:37:17 -0800851 }
Steve Anton4171afb2017-11-20 10:20:22 -0800852 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800853 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
854 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800855 }
Steve Anton75737c02017-11-06 10:37:17 -0800856 }
Steve Anton6fec8802017-12-04 10:37:29 -0800857 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -0800858
Mirko Bonadei675513b2017-11-09 11:09:25 +0100859 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800860
861 webrtc_session_desc_factory_.reset();
862 sctp_invoker_.reset();
863 sctp_factory_.reset();
864 transport_controller_.reset();
865
deadbeef91dd5672016-05-18 16:55:30 -0700866 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700867 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700868 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700869 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700870 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700871 call_.reset();
872 event_log_.reset();
873 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874}
875
876bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000877 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700878 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200879 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800880 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100881 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700882
883 RTCError config_error = ValidateConfiguration(configuration);
884 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100885 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700886 return false;
887 }
888
deadbeef293e9262017-01-11 12:28:30 -0800889 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100890 RTC_LOG(LS_ERROR)
891 << "PeerConnection initialized without a PortAllocator? "
892 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800893 return false;
894 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200895
deadbeef653b8e02015-11-11 12:55:10 -0800896 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800897 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
899 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800900 return false;
901 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000902 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800903 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800904
deadbeef91dd5672016-05-18 16:55:30 -0700905 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700906 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700907 if (!network_thread()->Invoke<bool>(
908 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
909 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910 return false;
911 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000912
Steve Anton75737c02017-11-06 10:37:17 -0800913 // RFC 3264: The numeric value of the session id and version in the
914 // o line MUST be representable with a "64 bit signed integer".
915 // Due to this constraint session id |session_id_| is max limited to
916 // LLONG_MAX.
917 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
918 transport_controller_.reset(factory_->CreateTransportController(
919 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
920 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
921 transport_controller_->SignalConnectionState.connect(
922 this, &PeerConnection::OnTransportControllerConnectionState);
923 transport_controller_->SignalGatheringState.connect(
924 this, &PeerConnection::OnTransportControllerGatheringState);
925 transport_controller_->SignalCandidatesGathered.connect(
926 this, &PeerConnection::OnTransportControllerCandidatesGathered);
927 transport_controller_->SignalCandidatesRemoved.connect(
928 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
929 transport_controller_->SignalDtlsHandshakeError.connect(
930 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
931
932 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700933
deadbeefab9b2d12015-10-14 11:33:11 -0700934 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700935 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936
Steve Antonba818672017-11-06 10:21:57 -0800937 configuration_ = configuration;
938
Steve Anton75737c02017-11-06 10:37:17 -0800939 const PeerConnectionFactoryInterface::Options& options = factory_->options();
940
941 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
942
943 // Obtain a certificate from RTCConfiguration if any were provided (optional).
944 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
945 if (!configuration.certificates.empty()) {
946 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
947 // just picking the first one. The decision should be made based on the DTLS
948 // handshake. The DTLS negotiations need to know about all certificates.
949 certificate = configuration.certificates[0];
950 }
951
Steve Antond25da372017-11-06 14:50:29 -0800952 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800953
954 if (options.disable_encryption) {
955 dtls_enabled_ = false;
956 } else {
957 // Enable DTLS by default if we have an identity store or a certificate.
958 dtls_enabled_ = (cert_generator || certificate);
959 // |configuration| can override the default |dtls_enabled_| value.
960 if (configuration.enable_dtls_srtp) {
961 dtls_enabled_ = *(configuration.enable_dtls_srtp);
962 }
963 }
964
965 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
966 // It takes precendence over the disable_sctp_data_channels
967 // PeerConnectionFactoryInterface::Options.
968 if (configuration.enable_rtp_data_channel) {
969 data_channel_type_ = cricket::DCT_RTP;
970 } else {
971 // DTLS has to be enabled to use SCTP.
972 if (!options.disable_sctp_data_channels && dtls_enabled_) {
973 data_channel_type_ = cricket::DCT_SCTP;
974 }
975 }
976
977 video_options_.screencast_min_bitrate_kbps =
978 configuration.screencast_min_bitrate;
979 audio_options_.combined_audio_video_bwe =
980 configuration.combined_audio_video_bwe;
981
982 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100983 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800984
985 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100986 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800987
988 // Whether the certificate generator/certificate is null or not determines
989 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
990 // the right instructions by clearing the variables if needed.
991 if (!dtls_enabled_) {
992 cert_generator.reset();
993 certificate = nullptr;
994 } else if (certificate) {
995 // Favor generated certificate over the certificate generator.
996 cert_generator.reset();
997 }
998
999 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1000 signaling_thread(), channel_manager(), this, session_id(),
1001 std::move(cert_generator), certificate));
1002 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1003 this, &PeerConnection::OnCertificateReady);
1004
1005 if (options.disable_encryption) {
1006 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1007 }
1008
1009 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1010 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011
Steve Anton4171afb2017-11-20 10:20:22 -08001012 // Add default audio/video transceivers for Plan B SDP.
1013 if (!IsUnifiedPlan()) {
1014 transceivers_.push_back(
1015 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1016 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1017 transceivers_.push_back(
1018 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1019 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1020 }
1021
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 return true;
1023}
1024
Steve Anton038834f2017-07-14 15:59:59 -07001025RTCError PeerConnection::ValidateConfiguration(
1026 const RTCConfiguration& config) const {
1027 if (config.ice_regather_interval_range &&
1028 config.continual_gathering_policy == GATHER_ONCE) {
1029 return RTCError(RTCErrorType::INVALID_PARAMETER,
1030 "ice_regather_interval_range specified but continual "
1031 "gathering policy is GATHER_ONCE");
1032 }
1033 return RTCError::OK();
1034}
1035
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001036rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001038 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001041rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001043 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044}
1045
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001046bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001047 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001048 if (IsClosed()) {
1049 return false;
1050 }
deadbeefab9b2d12015-10-14 11:33:11 -07001051 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 return false;
1053 }
deadbeefab9b2d12015-10-14 11:33:11 -07001054
1055 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001056 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1057 observer->SignalAudioTrackAdded.connect(this,
1058 &PeerConnection::OnAudioTrackAdded);
1059 observer->SignalAudioTrackRemoved.connect(
1060 this, &PeerConnection::OnAudioTrackRemoved);
1061 observer->SignalVideoTrackAdded.connect(this,
1062 &PeerConnection::OnVideoTrackAdded);
1063 observer->SignalVideoTrackRemoved.connect(
1064 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001065 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001066
deadbeefab9b2d12015-10-14 11:33:11 -07001067 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001068 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001069 }
1070 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001071 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001072 }
1073
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001074 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 observer_->OnRenegotiationNeeded();
1076 return true;
1077}
1078
1079void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001081 if (!IsClosed()) {
1082 for (const auto& track : local_stream->GetAudioTracks()) {
1083 RemoveAudioTrack(track.get(), local_stream);
1084 }
1085 for (const auto& track : local_stream->GetVideoTracks()) {
1086 RemoveVideoTrack(track.get(), local_stream);
1087 }
deadbeefab9b2d12015-10-14 11:33:11 -07001088 }
deadbeefab9b2d12015-10-14 11:33:11 -07001089 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001090 stream_observers_.erase(
1091 std::remove_if(
1092 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001093 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001094 return observer->stream()->label().compare(local_stream->label()) ==
1095 0;
1096 }),
1097 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001098
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 if (IsClosed()) {
1100 return;
1101 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 observer_->OnRenegotiationNeeded();
1103}
1104
deadbeefe1f9d832016-01-14 15:35:42 -08001105rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1106 MediaStreamTrackInterface* track,
1107 std::vector<MediaStreamInterface*> streams) {
1108 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1109 if (IsClosed()) {
1110 return nullptr;
1111 }
1112 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001113 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001114 << "Adding a track with two streams is not currently supported.";
1115 return nullptr;
1116 }
Steve Anton4171afb2017-11-20 10:20:22 -08001117 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001118 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1119 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001120 return nullptr;
1121 }
1122
1123 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001124 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001125 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001126 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001127 signaling_thread(),
1128 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001129 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001130 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001131 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001132 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001133 }
Steve Anton4171afb2017-11-20 10:20:22 -08001134 const RtpSenderInfo* sender_info =
1135 FindSenderInfo(local_audio_sender_infos_,
1136 new_sender->internal()->stream_id(), track->id());
1137 if (sender_info) {
1138 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001139 }
1140 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001141 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001142 signaling_thread(),
1143 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001144 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001145 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001146 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001147 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001148 }
Steve Anton4171afb2017-11-20 10:20:22 -08001149 const RtpSenderInfo* sender_info =
1150 FindSenderInfo(local_video_sender_infos_,
1151 new_sender->internal()->stream_id(), track->id());
1152 if (sender_info) {
1153 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
1155 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001156 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1157 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001158 return rtc::scoped_refptr<RtpSenderInterface>();
1159 }
1160
deadbeefe1f9d832016-01-14 15:35:42 -08001161 observer_->OnRenegotiationNeeded();
1162 return new_sender;
1163}
1164
1165bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1166 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1167 if (IsClosed()) {
1168 return false;
1169 }
1170
Steve Anton4171afb2017-11-20 10:20:22 -08001171 bool removed;
1172 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1173 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1174 } else {
1175 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1176 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1177 }
1178 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001179 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1180 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001181 return false;
1182 }
deadbeefe1f9d832016-01-14 15:35:42 -08001183
1184 observer_->OnRenegotiationNeeded();
1185 return true;
1186}
1187
Steve Anton9158ef62017-11-27 13:01:52 -08001188RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1189PeerConnection::AddTransceiver(
1190 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1191 return AddTransceiver(track, RtpTransceiverInit());
1192}
1193
1194RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1195PeerConnection::AddTransceiver(
1196 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1197 const RtpTransceiverInit& init) {
1198 if (!IsUnifiedPlan()) {
1199 LOG_AND_RETURN_ERROR(
1200 RTCErrorType::INTERNAL_ERROR,
1201 "AddTransceiver only supported when Unified Plan is enabled.");
1202 }
1203 if (!track) {
1204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1205 }
1206 cricket::MediaType media_type;
1207 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1208 media_type = cricket::MEDIA_TYPE_AUDIO;
1209 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1210 media_type = cricket::MEDIA_TYPE_VIDEO;
1211 } else {
1212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1213 "Track kind is not audio or video");
1214 }
1215 return AddTransceiver(media_type, track, init);
1216}
1217
1218RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1219PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1220 return AddTransceiver(media_type, RtpTransceiverInit());
1221}
1222
1223RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1224PeerConnection::AddTransceiver(cricket::MediaType media_type,
1225 const RtpTransceiverInit& init) {
1226 if (!IsUnifiedPlan()) {
1227 LOG_AND_RETURN_ERROR(
1228 RTCErrorType::INTERNAL_ERROR,
1229 "AddTransceiver only supported when Unified Plan is enabled.");
1230 }
1231 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1232 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1234 "media type is not audio or video");
1235 }
1236 return AddTransceiver(media_type, nullptr, init);
1237}
1238
1239RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1240PeerConnection::AddTransceiver(
1241 cricket::MediaType media_type,
1242 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1243 const RtpTransceiverInit& init) {
1244 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1245 media_type == cricket::MEDIA_TYPE_VIDEO));
1246 if (track) {
1247 RTC_DCHECK_EQ(media_type,
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO));
1251 }
1252
1253 // TODO(bugs.webrtc.org/7600): Verify init.
1254
1255 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1256 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1257 receiver;
1258 std::string receiver_id = rtc::CreateRandomUuid();
1259 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1260 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1261 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1262 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1263 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1264 } else {
1265 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1266 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1267 signaling_thread(), new VideoRtpSender(nullptr));
1268 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1269 signaling_thread(),
1270 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1271 }
1272 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1273 // channel prevents users from calling SetParameters on them, which is needed
1274 // to be in compliance with the spec.
1275
1276 if (track) {
1277 sender->SetTrack(track);
1278 }
1279
1280 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1281 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1282 signaling_thread(), new RtpTransceiver(sender, receiver));
1283 transceiver->SetDirection(init.direction);
1284
1285 transceivers_.push_back(transceiver);
1286
1287 observer_->OnRenegotiationNeeded();
1288
1289 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1290}
1291
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001292rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001295 if (IsClosed()) {
1296 return nullptr;
1297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001299 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001300 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301 }
Steve Anton4171afb2017-11-20 10:20:22 -08001302 auto track_sender = FindSenderForTrack(track);
1303 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001304 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001305 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 }
1307
Steve Anton4171afb2017-11-20 10:20:22 -08001308 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309}
1310
deadbeeffac06552015-11-25 11:26:01 -08001311rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001312 const std::string& kind,
1313 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001314 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001315 if (IsClosed()) {
1316 return nullptr;
1317 }
Steve Anton4171afb2017-11-20 10:20:22 -08001318
1319 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001320 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001321 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001322 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001323 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001324 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001325 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001326 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001327 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001328 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001329 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001330 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001331 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001332 }
Steve Anton4171afb2017-11-20 10:20:22 -08001333
deadbeefbd7d8f72015-12-18 16:58:44 -08001334 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001335 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001336 }
Steve Anton4171afb2017-11-20 10:20:22 -08001337
deadbeefe1f9d832016-01-14 15:35:42 -08001338 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001339}
1340
deadbeef70ab1a12015-09-28 16:53:55 -07001341std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1342 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001343 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001344 for (auto sender : GetSendersInternal()) {
1345 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001346 }
1347 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001348}
1349
Steve Anton4171afb2017-11-20 10:20:22 -08001350std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1351PeerConnection::GetSendersInternal() const {
1352 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1353 all_senders;
1354 for (auto transceiver : transceivers_) {
1355 auto senders = transceiver->internal()->senders();
1356 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1357 }
1358 return all_senders;
1359}
1360
deadbeef70ab1a12015-09-28 16:53:55 -07001361std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1362PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001363 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001364 for (const auto& receiver : GetReceiversInternal()) {
1365 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001366 }
1367 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001368}
1369
Steve Anton4171afb2017-11-20 10:20:22 -08001370std::vector<
1371 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1372PeerConnection::GetReceiversInternal() const {
1373 std::vector<
1374 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1375 all_receivers;
1376 for (auto transceiver : transceivers_) {
1377 auto receivers = transceiver->internal()->receivers();
1378 all_receivers.insert(all_receivers.end(), receivers.begin(),
1379 receivers.end());
1380 }
1381 return all_receivers;
1382}
1383
Steve Anton9158ef62017-11-27 13:01:52 -08001384std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1385PeerConnection::GetTransceivers() const {
1386 RTC_DCHECK(IsUnifiedPlan());
1387 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1388 for (auto transceiver : transceivers_) {
1389 all_transceivers.push_back(transceiver);
1390 }
1391 return all_transceivers;
1392}
1393
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001395 MediaStreamTrackInterface* track,
1396 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001397 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001398 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001399 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001400 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 return false;
1402 }
1403
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001404 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001405 // The StatsCollector is used to tell if a track is valid because it may
1406 // remember tracks that the PeerConnection previously removed.
1407 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001408 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1409 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001410 return false;
1411 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001412 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001413 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 return true;
1415}
1416
hbos74e1a4f2016-09-15 23:33:01 -07001417void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1418 RTC_DCHECK(stats_collector_);
1419 stats_collector_->GetStatsReport(callback);
1420}
1421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1423 return signaling_state_;
1424}
1425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426PeerConnectionInterface::IceConnectionState
1427PeerConnection::ice_connection_state() {
1428 return ice_connection_state_;
1429}
1430
1431PeerConnectionInterface::IceGatheringState
1432PeerConnection::ice_gathering_state() {
1433 return ice_gathering_state_;
1434}
1435
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001436rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437PeerConnection::CreateDataChannel(
1438 const std::string& label,
1439 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001440 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001441
deadbeefab9b2d12015-10-14 11:33:11 -07001442 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001443
kwibergd1fe2812016-04-27 06:47:29 -07001444 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001445 if (config) {
1446 internal_config.reset(new InternalDataChannelInit(*config));
1447 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001448 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001449 InternalCreateDataChannel(label, internal_config.get()));
1450 if (!channel.get()) {
1451 return nullptr;
1452 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001454 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1455 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001456 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001457 observer_->OnRenegotiationNeeded();
1458 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 return DataChannelProxy::Create(signaling_thread(), channel.get());
1461}
1462
1463void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1464 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001465 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001466
zhihuang1c378ed2017-08-17 14:10:50 -07001467 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1468 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1469 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1470 // compares the mandatory fields parsed with the mandatory fields added in the
1471 // |constraints| and some downstream applications might create offers with
1472 // mandatory fields which would not be parsed in the helper method. For
1473 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1474 // |constraints| as a mandatory field but it is not parsed.
1475 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001476
zhihuang1c378ed2017-08-17 14:10:50 -07001477 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001478}
1479
1480void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1481 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001482 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001483
nisse7ce109a2017-01-31 00:57:56 -08001484 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001485 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001486 return;
1487 }
deadbeefab9b2d12015-10-14 11:33:11 -07001488
Steve Anton8d3444d2017-10-20 15:30:51 -07001489 if (IsClosed()) {
1490 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001491 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001492 PostCreateSessionDescriptionFailure(observer, error);
1493 return;
1494 }
1495
zhihuang1c378ed2017-08-17 14:10:50 -07001496 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001497 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001498 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001499 PostCreateSessionDescriptionFailure(observer, error);
1500 return;
1501 }
1502
zhihuang1c378ed2017-08-17 14:10:50 -07001503 cricket::MediaSessionOptions session_options;
1504 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001505 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506}
1507
1508void PeerConnection::CreateAnswer(
1509 CreateSessionDescriptionObserver* observer,
1510 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001511 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001512
nisse7ce109a2017-01-31 00:57:56 -08001513 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001514 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 return;
1516 }
deadbeefab9b2d12015-10-14 11:33:11 -07001517
zhihuang1c378ed2017-08-17 14:10:50 -07001518 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1519 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1520 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001521 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001522 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001523 PostCreateSessionDescriptionFailure(observer, error);
1524 return;
1525 }
1526
Steve Anton8d3444d2017-10-20 15:30:51 -07001527 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001528}
1529
1530void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1531 const RTCOfferAnswerOptions& options) {
1532 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001533 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001534 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001535 return;
1536 }
1537
Steve Anton8d3444d2017-10-20 15:30:51 -07001538 if (IsClosed()) {
1539 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001541 PostCreateSessionDescriptionFailure(observer, error);
1542 return;
1543 }
1544
Steve Anton75737c02017-11-06 10:37:17 -08001545 if (remote_description() &&
1546 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001547 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001548 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001549 PostCreateSessionDescriptionFailure(observer, error);
1550 return;
1551 }
1552
htaa2a49d92016-03-04 02:51:39 -08001553 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001554 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001555
Steve Antond25da372017-11-06 14:50:29 -08001556 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557}
1558
1559void PeerConnection::SetLocalDescription(
1560 SetSessionDescriptionObserver* observer,
1561 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001562 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001563 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001564 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 return;
1566 }
1567 if (!desc) {
1568 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1569 return;
1570 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001571
1572 // Takes the ownership of |desc| regardless of the result.
1573 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1574
1575 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001576 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001577 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001578 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001579 PostSetSessionDescriptionFailure(observer, error);
1580 return;
1581 }
1582
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 // Update stats here so that we have the most recent stats for tracks and
1584 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001585 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001587 // Takes the ownership of |desc_temp|. On success, local_description() is
1588 // updated to reflect the description that was passed in.
Henrik Boström31638672017-11-23 17:48:32 +01001589 if (!SetCurrentOrPendingLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001590 PostSetSessionDescriptionFailure(observer, error);
1591 return;
1592 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001593 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001594
1595 // If setting the description decided our SSL role, allocate any necessary
1596 // SCTP sids.
1597 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001598 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001599 AllocateSctpSids(role);
1600 }
1601
1602 // Update state and SSRC of local MediaStreams and DataChannels based on the
1603 // local session description.
1604 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001605 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001606 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001607 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001608 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001609 } else {
1610 const cricket::AudioContentDescription* audio_desc =
1611 static_cast<const cricket::AudioContentDescription*>(
1612 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001613 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001614 }
deadbeefab9b2d12015-10-14 11:33:11 -07001615 }
1616
1617 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001618 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001619 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001620 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001621 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001622 } else {
1623 const cricket::VideoContentDescription* video_desc =
1624 static_cast<const cricket::VideoContentDescription*>(
1625 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001626 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001627 }
deadbeefab9b2d12015-10-14 11:33:11 -07001628 }
1629
1630 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001631 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001632 if (data_content) {
1633 const cricket::DataContentDescription* data_desc =
1634 static_cast<const cricket::DataContentDescription*>(
1635 data_content->description);
1636 if (rtc::starts_with(data_desc->protocol().data(),
1637 cricket::kMediaProtocolRtpPrefix)) {
1638 UpdateLocalRtpDataChannels(data_desc->streams());
1639 }
1640 }
1641
Henrik Boström31638672017-11-23 17:48:32 +01001642 PostSetSessionDescriptionSuccess(observer);
deadbeefab9b2d12015-10-14 11:33:11 -07001643
deadbeef42a42632017-03-10 15:18:00 -08001644 // According to JSEP, after setLocalDescription, changing the candidate pool
1645 // size is not allowed, and changing the set of ICE servers will not result
1646 // in new candidates being gathered.
1647 port_allocator_->FreezeCandidatePool();
1648
deadbeefcbecd352015-09-23 11:50:27 -07001649 // MaybeStartGathering needs to be called after posting
1650 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1651 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001652 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001653
Henrik Boströmfdb92012017-11-09 19:55:44 +01001654 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001655 // TODO(deadbeef): We already had to hop to the network thread for
1656 // MaybeStartGathering...
1657 network_thread()->Invoke<void>(
1658 RTC_FROM_HERE,
1659 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1660 port_allocator_.get()));
1661 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662}
1663
1664void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001665 SetSessionDescriptionObserver* observer,
1666 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001667 SetRemoteDescription(
1668 std::unique_ptr<SessionDescriptionInterface>(desc),
1669 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1670 new SetRemoteDescriptionObserverAdapter(this, observer)));
1671}
1672
1673void PeerConnection::SetRemoteDescription(
1674 std::unique_ptr<SessionDescriptionInterface> desc,
1675 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001676 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001677 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001678 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001679 return;
1680 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001682 observer->OnSetRemoteDescriptionComplete(RTCError(
1683 RTCErrorType::UNSUPPORTED_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684 return;
1685 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001686
Steve Anton8d3444d2017-10-20 15:30:51 -07001687 if (IsClosed()) {
Henrik Boström31638672017-11-23 17:48:32 +01001688 std::string error = "Failed to set remote " + desc->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001689 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001690 RTC_LOG(LS_ERROR) << error;
Henrik Boström31638672017-11-23 17:48:32 +01001691 observer->OnSetRemoteDescriptionComplete(
1692 RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001693 return;
1694 }
1695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696 // Update stats here so that we have the most recent stats for tracks and
1697 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001698 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 std::string error;
Henrik Boström31638672017-11-23 17:48:32 +01001700 // Takes the ownership of |desc|. On success, remote_description() is updated
1701 // to reflect the description that was passed in.
1702 if (!SetCurrentOrPendingRemoteDescription(std::move(desc), &error)) {
1703 observer->OnSetRemoteDescriptionComplete(
1704 RTCError(RTCErrorType::UNSUPPORTED_PARAMETER, std::move(error)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705 return;
1706 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001707 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708
deadbeefab9b2d12015-10-14 11:33:11 -07001709 // If setting the description decided our SSL role, allocate any necessary
1710 // SCTP sids.
1711 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001712 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001713 AllocateSctpSids(role);
1714 }
1715
Henrik Boströmfdb92012017-11-09 19:55:44 +01001716 const cricket::ContentInfo* audio_content =
1717 GetFirstAudioContent(remote_description()->description());
1718 const cricket::ContentInfo* video_content =
1719 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001720 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001721 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001722 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001723 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001724 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001725 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001726
1727 // Check if the descriptions include streams, just in case the peer supports
1728 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001729 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001730 (audio_desc && !audio_desc->streams().empty()) ||
1731 (video_desc && !video_desc->streams().empty())) {
1732 remote_peer_supports_msid_ = true;
1733 }
deadbeefab9b2d12015-10-14 11:33:11 -07001734
1735 // We wait to signal new streams until we finish processing the description,
1736 // since only at that point will new streams have all their tracks.
1737 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1738
Steve Anton8d3444d2017-10-20 15:30:51 -07001739 // TODO(steveanton): When removing RTP senders/receivers in response to a
1740 // rejected media section, there is some cleanup logic that expects the voice/
1741 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001742 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001743 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001744 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001745
deadbeefab9b2d12015-10-14 11:33:11 -07001746 // Find all audio rtp streams and create corresponding remote AudioTracks
1747 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001748 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001749 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001750 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001751 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001752 bool default_audio_track_needed =
1753 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001754 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001755 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001756 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001757 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001758 }
deadbeefab9b2d12015-10-14 11:33:11 -07001759 }
1760
1761 // Find all video rtp streams and create corresponding remote VideoTracks
1762 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001763 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001764 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001765 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001766 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001767 bool default_video_track_needed =
1768 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001769 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001770 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001771 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001772 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001773 }
deadbeefab9b2d12015-10-14 11:33:11 -07001774 }
1775
1776 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001777 if (data_desc) {
1778 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001779 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001780 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001781 }
1782 }
1783
1784 // Iterate new_streams and notify the observer about new MediaStreams.
1785 for (size_t i = 0; i < new_streams->count(); ++i) {
1786 MediaStreamInterface* new_stream = new_streams->at(i);
1787 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001788 observer_->OnAddStream(
1789 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001790 }
1791
deadbeefbda7e0b2015-12-08 17:13:40 -08001792 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001793
Henrik Boström31638672017-11-23 17:48:32 +01001794 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
deadbeef42a42632017-03-10 15:18:00 -08001795
Henrik Boströmfdb92012017-11-09 19:55:44 +01001796 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001797 // TODO(deadbeef): We already had to hop to the network thread for
1798 // MaybeStartGathering...
1799 network_thread()->Invoke<void>(
1800 RTC_FROM_HERE,
1801 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1802 port_allocator_.get()));
1803 }
deadbeeffc648b62015-10-13 16:42:33 -07001804}
1805
deadbeef46c73892016-11-16 19:42:04 -08001806PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1807 return configuration_;
1808}
1809
deadbeef293e9262017-01-11 12:28:30 -08001810bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1811 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001812 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001813
Steve Anton75737c02017-11-06 10:37:17 -08001814 if (local_description() && configuration.ice_candidate_pool_size !=
1815 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001816 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1817 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001818 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001819 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001820
deadbeef293e9262017-01-11 12:28:30 -08001821 // The simplest (and most future-compatible) way to tell if the config was
1822 // modified in an invalid way is to copy each property we do support
1823 // modifying, then use operator==. There are far more properties we don't
1824 // support modifying than those we do, and more could be added.
1825 RTCConfiguration modified_config = configuration_;
1826 modified_config.servers = configuration.servers;
1827 modified_config.type = configuration.type;
1828 modified_config.ice_candidate_pool_size =
1829 configuration.ice_candidate_pool_size;
1830 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001831 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001832 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001833 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001834 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001835 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1836 }
1837
Steve Anton038834f2017-07-14 15:59:59 -07001838 // Validate the modified configuration.
1839 RTCError validate_error = ValidateConfiguration(modified_config);
1840 if (!validate_error.ok()) {
1841 return SafeSetError(std::move(validate_error), error);
1842 }
1843
deadbeef293e9262017-01-11 12:28:30 -08001844 // Note that this isn't possible through chromium, since it's an unsigned
1845 // short in WebIDL.
1846 if (configuration.ice_candidate_pool_size < 0 ||
1847 configuration.ice_candidate_pool_size > UINT16_MAX) {
1848 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1849 }
1850
1851 // Parse ICE servers before hopping to network thread.
1852 cricket::ServerAddresses stun_servers;
1853 std::vector<cricket::RelayServerConfig> turn_servers;
1854 RTCErrorType parse_error =
1855 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1856 if (parse_error != RTCErrorType::NONE) {
1857 return SafeSetError(parse_error, error);
1858 }
1859
1860 // In theory this shouldn't fail.
1861 if (!network_thread()->Invoke<bool>(
1862 RTC_FROM_HERE,
1863 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1864 stun_servers, turn_servers, modified_config.type,
1865 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001866 modified_config.prune_turn_ports,
1867 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001868 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001869 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1870 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001871
deadbeefd1a38b52016-12-10 13:15:33 -08001872 // As described in JSEP, calling setConfiguration with new ICE servers or
1873 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1874 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001875 if (modified_config.servers != configuration_.servers ||
1876 modified_config.type != configuration_.type ||
1877 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001878 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001879 }
skvladd1f5fda2017-02-03 16:54:05 -08001880
1881 if (modified_config.ice_check_min_interval !=
1882 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001883 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001884 }
1885
deadbeef293e9262017-01-11 12:28:30 -08001886 configuration_ = modified_config;
1887 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001888}
1889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890bool PeerConnection::AddIceCandidate(
1891 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001892 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001893 if (IsClosed()) {
1894 return false;
1895 }
Steve Antond25da372017-11-06 14:50:29 -08001896
1897 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001898 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1899 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001900 return false;
1901 }
1902
1903 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001904 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001905 return false;
1906 }
1907
1908 bool valid = false;
1909 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1910 if (!valid) {
1911 return false;
1912 }
1913
1914 // Add this candidate to the remote session description.
1915 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001916 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001917 return false;
1918 }
1919
1920 if (ready) {
1921 return UseCandidate(ice_candidate);
1922 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001923 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001924 return true;
1925 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926}
1927
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001928bool PeerConnection::RemoveIceCandidates(
1929 const std::vector<cricket::Candidate>& candidates) {
1930 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001931 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001932 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1933 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001934 return false;
1935 }
1936
1937 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001938 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001939 return false;
1940 }
1941
1942 size_t number_removed =
1943 mutable_remote_description()->RemoveCandidates(candidates);
1944 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR)
1946 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1947 << "Requested " << candidates.size() << " but only " << number_removed
1948 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001949 }
1950
1951 // Remove the candidates from the transport controller.
1952 std::string error;
1953 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1954 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001955 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001956 }
1957 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001958}
1959
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001960void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001961 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001962 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001963
Steve Anton75737c02017-11-06 10:37:17 -08001964 if (transport_controller()) {
1965 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001966 }
1967
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001968 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001969 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001970 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001971 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001972 uma_observer_->IncrementEnumCounter(
1973 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1974 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001975 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001976 uma_observer_->IncrementEnumCounter(
1977 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1978 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001979 }
1980 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001981}
1982
zstein4b979802017-06-02 14:37:37 -07001983RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001984 if (!worker_thread()->IsCurrent()) {
1985 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001986 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1987 }
1988
1989 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1990 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1991 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1992 if (has_min && *bitrate.min_bitrate_bps < 0) {
1993 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1994 "min_bitrate_bps <= 0");
1995 }
1996 if (has_current) {
1997 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1998 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1999 "current_bitrate_bps < min_bitrate_bps");
2000 } else if (*bitrate.current_bitrate_bps < 0) {
2001 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2002 "curent_bitrate_bps < 0");
2003 }
2004 }
2005 if (has_max) {
2006 if (has_current &&
2007 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2008 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2009 "max_bitrate_bps < current_bitrate_bps");
2010 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2011 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2012 "max_bitrate_bps < min_bitrate_bps");
2013 } else if (*bitrate.max_bitrate_bps < 0) {
2014 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2015 "max_bitrate_bps < 0");
2016 }
2017 }
2018
2019 Call::Config::BitrateConfigMask mask;
2020 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2021 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2022 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2023
2024 RTC_DCHECK(call_.get());
2025 call_->SetBitrateConfigMask(mask);
2026
2027 return RTCError::OK();
2028}
2029
Alex Narest78609d52017-10-20 10:37:47 +02002030void PeerConnection::SetBitrateAllocationStrategy(
2031 std::unique_ptr<rtc::BitrateAllocationStrategy>
2032 bitrate_allocation_strategy) {
2033 rtc::Thread* worker_thread = factory_->worker_thread();
2034 if (!worker_thread->IsCurrent()) {
2035 rtc::BitrateAllocationStrategy* strategy_raw =
2036 bitrate_allocation_strategy.release();
2037 auto functor = [this, strategy_raw]() {
2038 call_->SetBitrateAllocationStrategy(
2039 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2040 };
2041 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2042 return;
2043 }
2044 RTC_DCHECK(call_.get());
2045 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2046}
2047
henrika5f6bf242017-11-01 11:06:56 +01002048void PeerConnection::SetAudioPlayout(bool playout) {
2049 if (!worker_thread()->IsCurrent()) {
2050 worker_thread()->Invoke<void>(
2051 RTC_FROM_HERE,
2052 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2053 return;
2054 }
2055 auto audio_state =
2056 factory_->channel_manager()->media_engine()->GetAudioState();
2057 audio_state->SetPlayout(playout);
2058}
2059
2060void PeerConnection::SetAudioRecording(bool recording) {
2061 if (!worker_thread()->IsCurrent()) {
2062 worker_thread()->Invoke<void>(
2063 RTC_FROM_HERE,
2064 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2065 return;
2066 }
2067 auto audio_state =
2068 factory_->channel_manager()->media_engine()->GetAudioState();
2069 audio_state->SetRecording(recording);
2070}
2071
Steve Anton8c0f7a72017-10-03 10:03:10 -07002072std::unique_ptr<rtc::SSLCertificate>
2073PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002074 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002075 return nullptr;
2076 }
Steve Anton75737c02017-11-06 10:37:17 -08002077 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002078}
2079
ivoc14d5dbe2016-07-04 07:06:55 -07002080bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2081 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002082 // TODO(eladalon): It would be better to not allow negative values into PC.
2083 const size_t max_size = (max_size_bytes < 0)
2084 ? RtcEventLog::kUnlimitedOutput
2085 : rtc::saturated_cast<size_t>(max_size_bytes);
2086 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002087 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2088 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002089}
2090
Bjorn Tereliusde939432017-11-20 17:38:14 +01002091bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2092 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002093 // TODO(eladalon): In C++14, this can be done with a lambda.
2094 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002095 bool operator()() {
2096 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2097 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002098 PeerConnection* const pc;
2099 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002100 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002101 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002102 return worker_thread()->Invoke<bool>(
2103 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002104}
2105
2106void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002107 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002108 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2109}
2110
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002111const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002112 return pending_local_description_ ? pending_local_description_.get()
2113 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114}
2115
2116const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002117 return pending_remote_description_ ? pending_remote_description_.get()
2118 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119}
2120
deadbeeffe4a8a42016-12-20 17:56:17 -08002121const SessionDescriptionInterface* PeerConnection::current_local_description()
2122 const {
Steve Anton75737c02017-11-06 10:37:17 -08002123 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002124}
2125
2126const SessionDescriptionInterface* PeerConnection::current_remote_description()
2127 const {
Steve Anton75737c02017-11-06 10:37:17 -08002128 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002129}
2130
2131const SessionDescriptionInterface* PeerConnection::pending_local_description()
2132 const {
Steve Anton75737c02017-11-06 10:37:17 -08002133 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002134}
2135
2136const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2137 const {
Steve Anton75737c02017-11-06 10:37:17 -08002138 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002139}
2140
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002142 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002143 // Update stats here so that we have the most recent stats for tracks and
2144 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002145 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146
Steve Anton75737c02017-11-06 10:37:17 -08002147 ChangeSignalingState(PeerConnectionInterface::kClosed);
2148 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002149 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2150 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002151 RTC_DCHECK(!rtp_data_channel_);
2152 RTC_DCHECK(!sctp_transport_);
2153
deadbeef42a42632017-03-10 15:18:00 -08002154 network_thread()->Invoke<void>(
2155 RTC_FROM_HERE,
2156 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2157 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002158
Steve Anton978b8762017-09-29 12:15:02 -07002159 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002160 call_.reset();
2161 // The event log must outlive call (and any other object that uses it).
2162 event_log_.reset();
2163 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164}
2165
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002166void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2169 SetSessionDescriptionMsg* param =
2170 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2171 param->observer->OnSuccess();
2172 delete param;
2173 break;
2174 }
2175 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2176 SetSessionDescriptionMsg* param =
2177 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2178 param->observer->OnFailure(param->error);
2179 delete param;
2180 break;
2181 }
deadbeefab9b2d12015-10-14 11:33:11 -07002182 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2183 CreateSessionDescriptionMsg* param =
2184 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2185 param->observer->OnFailure(param->error);
2186 delete param;
2187 break;
2188 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 case MSG_GETSTATS: {
2190 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002191 StatsReports reports;
2192 stats_->GetStats(param->track, &reports);
2193 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 delete param;
2195 break;
2196 }
deadbeefbd292462015-12-14 18:15:29 -08002197 case MSG_FREE_DATACHANNELS: {
2198 sctp_data_channels_to_free_.clear();
2199 break;
2200 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002202 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 break;
2204 }
2205}
2206
Steve Anton4171afb2017-11-20 10:20:22 -08002207void PeerConnection::CreateAudioReceiver(
2208 MediaStreamInterface* stream,
2209 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002210 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2211 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002212 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2213 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002214 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002215 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002216 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002217 stream->AddTrack(
2218 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002219 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002220 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221}
2222
Steve Anton4171afb2017-11-20 10:20:22 -08002223void PeerConnection::CreateVideoReceiver(
2224 MediaStreamInterface* stream,
2225 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002226 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2227 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002228 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2229 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002230 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002231 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2232 worker_thread(), remote_sender_info.first_ssrc,
2233 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002234 stream->AddTrack(
2235 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002236 GetVideoTransceiver()->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
deadbeef70ab1a12015-09-28 16:53:55 -07002240// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2241// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002242rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002243 const RtpSenderInfo& remote_sender_info) {
2244 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2245 if (!receiver) {
2246 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2247 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002248 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002249 }
Steve Anton4171afb2017-11-20 10:20:22 -08002250 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2251 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2252 } else {
2253 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2254 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002255 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256}
2257
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002258void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2259 MediaStreamInterface* stream) {
2260 RTC_DCHECK(!IsClosed());
2261 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002262 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002263 // We already have a sender for this track, so just change the stream_id
2264 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002265 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002266 return;
2267 }
2268
2269 // Normal case; we've never seen this track before.
2270 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2271 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2272 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002273 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2274 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002275 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002276 // If the sender has already been configured in SDP, we call SetSsrc,
2277 // which will connect the sender to the underlying transport. This can
2278 // occur if a local session description that contains the ID of the sender
2279 // is set before AddStream is called. It can also occur if the local
2280 // session description is not changed and RemoveStream is called, and
2281 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002282 const RtpSenderInfo* sender_info =
2283 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2284 if (sender_info) {
2285 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002286 }
2287}
2288
2289// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2290// indefinitely, when we have unified plan SDP.
2291void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2292 MediaStreamInterface* stream) {
2293 RTC_DCHECK(!IsClosed());
2294 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002295 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002296 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2297 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002298 return;
2299 }
Steve Anton4171afb2017-11-20 10:20:22 -08002300 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002301}
2302
2303void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2304 MediaStreamInterface* stream) {
2305 RTC_DCHECK(!IsClosed());
2306 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002307 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002308 // We already have a sender for this track, so just change the stream_id
2309 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002310 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002311 return;
2312 }
2313
2314 // Normal case; we've never seen this track before.
2315 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2316 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002317 signaling_thread(),
2318 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002319 GetVideoTransceiver()->internal()->AddSender(new_sender);
2320 const RtpSenderInfo* sender_info =
2321 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2322 if (sender_info) {
2323 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002324 }
2325}
2326
2327void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2328 MediaStreamInterface* stream) {
2329 RTC_DCHECK(!IsClosed());
2330 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002331 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002332 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2333 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002334 return;
2335 }
Steve Anton4171afb2017-11-20 10:20:22 -08002336 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002337}
2338
Steve Antonba818672017-11-06 10:21:57 -08002339void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002340 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002341 if (ice_connection_state_ == new_state) {
2342 return;
2343 }
2344
deadbeefcbecd352015-09-23 11:50:27 -07002345 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002346 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002347 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002348 return;
2349 }
Steve Antonba818672017-11-06 10:21:57 -08002350
Mirko Bonadei675513b2017-11-09 11:09:25 +01002351 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2352 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002353 RTC_DCHECK(ice_connection_state_ !=
2354 PeerConnectionInterface::kIceConnectionClosed);
2355
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002357 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358}
2359
2360void PeerConnection::OnIceGatheringChange(
2361 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002362 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002363 if (IsClosed()) {
2364 return;
2365 }
2366 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002367 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368}
2369
jbauch81bf7b02017-03-25 08:31:12 -07002370void PeerConnection::OnIceCandidate(
2371 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002372 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002373 if (IsClosed()) {
2374 return;
2375 }
jbauch81bf7b02017-03-25 08:31:12 -07002376 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377}
2378
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002379void PeerConnection::OnIceCandidatesRemoved(
2380 const std::vector<cricket::Candidate>& candidates) {
2381 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002382 if (IsClosed()) {
2383 return;
2384 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002385 observer_->OnIceCandidatesRemoved(candidates);
2386}
2387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388void PeerConnection::ChangeSignalingState(
2389 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002390 RTC_DCHECK(signaling_thread()->IsCurrent());
2391 if (signaling_state_ == signaling_state) {
2392 return;
2393 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002394 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2395 << GetSignalingStateString(signaling_state_)
2396 << " New state: "
2397 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 signaling_state_ = signaling_state;
2399 if (signaling_state == kClosed) {
2400 ice_connection_state_ = kIceConnectionClosed;
2401 observer_->OnIceConnectionChange(ice_connection_state_);
2402 if (ice_gathering_state_ != kIceGatheringComplete) {
2403 ice_gathering_state_ = kIceGatheringComplete;
2404 observer_->OnIceGatheringChange(ice_gathering_state_);
2405 }
2406 }
2407 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408}
2409
deadbeefeb459812015-12-15 19:24:43 -08002410void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2411 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002412 if (IsClosed()) {
2413 return;
2414 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002415 AddAudioTrack(track, stream);
2416 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002417}
2418
deadbeefeb459812015-12-15 19:24:43 -08002419void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2420 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002421 if (IsClosed()) {
2422 return;
2423 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002424 RemoveAudioTrack(track, stream);
2425 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002426}
2427
2428void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2429 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002430 if (IsClosed()) {
2431 return;
2432 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002433 AddVideoTrack(track, stream);
2434 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002435}
2436
2437void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2438 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002439 if (IsClosed()) {
2440 return;
2441 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002442 RemoveVideoTrack(track, stream);
2443 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002444}
2445
Henrik Boström31638672017-11-23 17:48:32 +01002446void PeerConnection::PostSetSessionDescriptionSuccess(
2447 SetSessionDescriptionObserver* observer) {
2448 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2449 signaling_thread()->Post(RTC_FROM_HERE, this,
2450 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2451}
2452
deadbeefab9b2d12015-10-14 11:33:11 -07002453void PeerConnection::PostSetSessionDescriptionFailure(
2454 SetSessionDescriptionObserver* observer,
2455 const std::string& error) {
2456 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2457 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002458 signaling_thread()->Post(RTC_FROM_HERE, this,
2459 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002460}
2461
2462void PeerConnection::PostCreateSessionDescriptionFailure(
2463 CreateSessionDescriptionObserver* observer,
2464 const std::string& error) {
2465 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2466 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002467 signaling_thread()->Post(RTC_FROM_HERE, this,
2468 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002469}
2470
zhihuang1c378ed2017-08-17 14:10:50 -07002471void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002472 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2473 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002474 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2475
2476 // Figure out transceiver directional preferences.
2477 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2478 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2479
2480 // By default, generate sendrecv/recvonly m= sections.
2481 bool recv_audio = true;
2482 bool recv_video = true;
2483
2484 // By default, only offer a new m= section if we have media to send with it.
2485 bool offer_new_audio_description = send_audio;
2486 bool offer_new_video_description = send_video;
2487 bool offer_new_data_description = HasDataChannels();
2488
2489 // The "offer_to_receive_X" options allow those defaults to be overridden.
2490 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2491 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2492 offer_new_audio_description =
2493 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2494 }
2495 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2496 recv_video = (rtc_options.offer_to_receive_video > 0);
2497 offer_new_video_description =
2498 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2499 }
2500
2501 rtc::Optional<size_t> audio_index;
2502 rtc::Optional<size_t> video_index;
2503 rtc::Optional<size_t> data_index;
2504 // If a current description exists, generate m= sections in the same order,
2505 // using the first audio/video/data section that appears and rejecting
2506 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002507 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002508 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002509 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002510 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2511 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2512 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002513 }
2514
zhihuang1c378ed2017-08-17 14:10:50 -07002515 // Add audio/video/data m= sections to the end if needed.
2516 if (!audio_index && offer_new_audio_description) {
2517 session_options->media_description_options.push_back(
2518 cricket::MediaDescriptionOptions(
2519 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002520 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2521 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002522 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002523 }
zhihuang1c378ed2017-08-17 14:10:50 -07002524 if (!video_index && offer_new_video_description) {
2525 session_options->media_description_options.push_back(
2526 cricket::MediaDescriptionOptions(
2527 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002528 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2529 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002530 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002531 }
zhihuang1c378ed2017-08-17 14:10:50 -07002532 if (!data_index && offer_new_data_description) {
2533 session_options->media_description_options.push_back(
2534 cricket::MediaDescriptionOptions(
2535 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002536 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002537 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002538 }
2539
2540 cricket::MediaDescriptionOptions* audio_media_description_options =
2541 !audio_index ? nullptr
2542 : &session_options->media_description_options[*audio_index];
2543 cricket::MediaDescriptionOptions* video_media_description_options =
2544 !video_index ? nullptr
2545 : &session_options->media_description_options[*video_index];
2546 cricket::MediaDescriptionOptions* data_media_description_options =
2547 !data_index ? nullptr
2548 : &session_options->media_description_options[*data_index];
2549
2550 // Apply ICE restart flag and renomination flag.
2551 for (auto& options : session_options->media_description_options) {
2552 options.transport_options.ice_restart = rtc_options.ice_restart;
2553 options.transport_options.enable_ice_renomination =
2554 configuration_.enable_ice_renomination;
2555 }
2556
Steve Anton4171afb2017-11-20 10:20:22 -08002557 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002558 video_media_description_options);
2559 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002560
zhihuang9763d562016-08-05 11:14:50 -07002561 // Intentionally unset the data channel type for RTP data channel with the
2562 // second condition. Otherwise the RTP data channels would be successfully
2563 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2564 // when building with chromium. We want to leave RTP data channels broken, so
2565 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002566 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2567 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002568 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002569
2570 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002571 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002572}
2573
zhihuang1c378ed2017-08-17 14:10:50 -07002574void PeerConnection::GetOptionsForAnswer(
2575 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002576 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002577 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002578
zhihuang1c378ed2017-08-17 14:10:50 -07002579 // Figure out transceiver directional preferences.
2580 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2581 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2582
2583 // By default, generate sendrecv/recvonly m= sections. The direction is also
2584 // restricted by the direction in the offer.
2585 bool recv_audio = true;
2586 bool recv_video = true;
2587
2588 // The "offer_to_receive_X" options allow those defaults to be overridden.
2589 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2590 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002591 }
zhihuang1c378ed2017-08-17 14:10:50 -07002592 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2593 recv_video = (rtc_options.offer_to_receive_video > 0);
2594 }
2595
2596 rtc::Optional<size_t> audio_index;
2597 rtc::Optional<size_t> video_index;
2598 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002599 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002600 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002601 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002602 SessionDescriptionInterface::kOffer);
2603 // Generate m= sections that match those in the offer.
2604 // Note that mediasession.cc will handle intersection our preferred
2605 // direction with the offered direction.
2606 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002607 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002608 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2609 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2610 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002611 }
zhihuang1c378ed2017-08-17 14:10:50 -07002612
2613 cricket::MediaDescriptionOptions* audio_media_description_options =
2614 !audio_index ? nullptr
2615 : &session_options->media_description_options[*audio_index];
2616 cricket::MediaDescriptionOptions* video_media_description_options =
2617 !video_index ? nullptr
2618 : &session_options->media_description_options[*video_index];
2619 cricket::MediaDescriptionOptions* data_media_description_options =
2620 !data_index ? nullptr
2621 : &session_options->media_description_options[*data_index];
2622
2623 // Apply ICE renomination flag.
2624 for (auto& options : session_options->media_description_options) {
2625 options.transport_options.enable_ice_renomination =
2626 configuration_.enable_ice_renomination;
2627 }
2628
Steve Anton4171afb2017-11-20 10:20:22 -08002629 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002630 video_media_description_options);
2631 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2632
zhihuang9763d562016-08-05 11:14:50 -07002633 // Intentionally unset the data channel type for RTP data channel. Otherwise
2634 // the RTP data channels would be successfully negotiated by default and the
2635 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2636 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002637 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2638 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002639 }
zhihuangaf388472016-11-02 16:49:48 -07002640
zhihuang1c378ed2017-08-17 14:10:50 -07002641 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002642 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002643}
2644
zhihuang1c378ed2017-08-17 14:10:50 -07002645void PeerConnection::GenerateMediaDescriptionOptions(
2646 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002647 RtpTransceiverDirection audio_direction,
2648 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002649 rtc::Optional<size_t>* audio_index,
2650 rtc::Optional<size_t>* video_index,
2651 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002652 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002653 for (const cricket::ContentInfo& content :
2654 session_desc->description()->contents()) {
2655 if (IsAudioContent(&content)) {
2656 // If we already have an audio m= section, reject this extra one.
2657 if (*audio_index) {
2658 session_options->media_description_options.push_back(
2659 cricket::MediaDescriptionOptions(
2660 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002661 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002662 } else {
2663 session_options->media_description_options.push_back(
2664 cricket::MediaDescriptionOptions(
2665 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002666 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002667 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002668 }
2669 } else if (IsVideoContent(&content)) {
2670 // If we already have an video m= section, reject this extra one.
2671 if (*video_index) {
2672 session_options->media_description_options.push_back(
2673 cricket::MediaDescriptionOptions(
2674 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002675 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002676 } else {
2677 session_options->media_description_options.push_back(
2678 cricket::MediaDescriptionOptions(
2679 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002680 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002681 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002682 }
2683 } else {
2684 RTC_DCHECK(IsDataContent(&content));
2685 // If we already have an data m= section, reject this extra one.
2686 if (*data_index) {
2687 session_options->media_description_options.push_back(
2688 cricket::MediaDescriptionOptions(
2689 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002690 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002691 } else {
2692 session_options->media_description_options.push_back(
2693 cricket::MediaDescriptionOptions(
2694 cricket::MEDIA_TYPE_DATA, content.name,
2695 // Direction for data sections is meaningless, but legacy
2696 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002697 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002698 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002699 }
2700 }
htaa2a49d92016-03-04 02:51:39 -08002701 }
deadbeefab9b2d12015-10-14 11:33:11 -07002702}
2703
Steve Anton4171afb2017-11-20 10:20:22 -08002704void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2705 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2706 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002707 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002708}
2709
Steve Anton4171afb2017-11-20 10:20:22 -08002710void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002711 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002712 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002713 cricket::MediaType media_type,
2714 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002715 std::vector<RtpSenderInfo>* current_senders =
2716 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002717
Steve Anton4171afb2017-11-20 10:20:22 -08002718 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002719 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002720 for (auto sender_it = current_senders->begin();
2721 sender_it != current_senders->end();
2722 /* incremented manually */) {
2723 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002724 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002725 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2726 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002727 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002728 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2729 sender_exists) {
2730 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002731 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002732 OnRemoteSenderRemoved(info, media_type);
2733 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002734 }
2735 }
2736
Steve Anton4171afb2017-11-20 10:20:22 -08002737 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002738 for (const cricket::StreamParams& params : streams) {
2739 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002740 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002741 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002742 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002743 uint32_t ssrc = params.first_ssrc();
2744
2745 rtc::scoped_refptr<MediaStreamInterface> stream =
2746 remote_streams_->find(stream_label);
2747 if (!stream) {
2748 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002749 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2750 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002751 remote_streams_->AddStream(stream);
2752 new_streams->AddStream(stream);
2753 }
2754
Steve Anton4171afb2017-11-20 10:20:22 -08002755 const RtpSenderInfo* sender_info =
2756 FindSenderInfo(*current_senders, stream_label, sender_id);
2757 if (!sender_info) {
2758 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2759 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002760 }
2761 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002762
Steve Anton4171afb2017-11-20 10:20:22 -08002763 // Add default sender if necessary.
2764 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002765 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2766 remote_streams_->find(kDefaultStreamLabel);
2767 if (!default_stream) {
2768 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002769 default_stream = MediaStreamProxy::Create(
2770 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002771 remote_streams_->AddStream(default_stream);
2772 new_streams->AddStream(default_stream);
2773 }
Steve Anton4171afb2017-11-20 10:20:22 -08002774 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2775 ? kDefaultAudioSenderId
2776 : kDefaultVideoSenderId;
2777 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2778 *current_senders, kDefaultStreamLabel, default_sender_id);
2779 if (!default_sender_info) {
2780 current_senders->push_back(
2781 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2782 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002783 }
2784 }
deadbeefab9b2d12015-10-14 11:33:11 -07002785}
2786
Steve Anton4171afb2017-11-20 10:20:22 -08002787void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2788 cricket::MediaType media_type) {
2789 MediaStreamInterface* stream =
2790 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002791
2792 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002793 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002794 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002795 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002796 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002797 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002798 }
2799}
2800
Steve Anton4171afb2017-11-20 10:20:22 -08002801void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2802 cricket::MediaType media_type) {
2803 MediaStreamInterface* stream =
2804 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002805
Henrik Boström933d8b02017-10-10 10:05:16 -07002806 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002807 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002808 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2809 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002810 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002811 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002812 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002813 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002814 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002815 }
2816 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002817 // Stopping or destroying a VideoRtpReceiver will end the
2818 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002819 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002820 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002821 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002822 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002823 // There's no guarantee the track is still available, e.g. the track may
2824 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002825 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002826 }
2827 } else {
nisseede5da42017-01-12 05:15:36 -08002828 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002829 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002830 if (receiver) {
2831 observer_->OnRemoveTrack(receiver);
2832 }
deadbeefab9b2d12015-10-14 11:33:11 -07002833}
2834
2835void PeerConnection::UpdateEndedRemoteMediaStreams() {
2836 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2837 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2838 MediaStreamInterface* stream = remote_streams_->at(i);
2839 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2840 streams_to_remove.push_back(stream);
2841 }
2842 }
2843
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002844 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002845 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002846 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002847 }
2848}
2849
Steve Anton4171afb2017-11-20 10:20:22 -08002850void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002851 const std::vector<cricket::StreamParams>& streams,
2852 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002853 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002854
2855 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2856 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002857 for (auto sender_it = current_senders->begin();
2858 sender_it != current_senders->end();
2859 /* incremented manually */) {
2860 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002861 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002862 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2863 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002864 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002865 OnLocalSenderRemoved(info, media_type);
2866 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002867 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002868 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002869 }
2870 }
2871
Steve Anton4171afb2017-11-20 10:20:22 -08002872 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002873 for (const cricket::StreamParams& params : streams) {
2874 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002875 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002876 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002877 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002878 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002879 const RtpSenderInfo* sender_info =
2880 FindSenderInfo(*current_senders, stream_label, sender_id);
2881 if (!sender_info) {
2882 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2883 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002884 }
2885 }
2886}
2887
Steve Anton4171afb2017-11-20 10:20:22 -08002888void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2889 cricket::MediaType media_type) {
2890 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002891 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002892 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2893 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002894 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002895 return;
2896 }
2897
deadbeeffac06552015-11-25 11:26:01 -08002898 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002899 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2900 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002901 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002902 }
deadbeeffac06552015-11-25 11:26:01 -08002903
Steve Anton4171afb2017-11-20 10:20:22 -08002904 sender->internal()->set_stream_id(sender_info.stream_label);
2905 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002906}
2907
Steve Anton4171afb2017-11-20 10:20:22 -08002908void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2909 cricket::MediaType media_type) {
2910 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002911 if (!sender) {
2912 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002913 // SessionDescriptions has been renegotiated.
2914 return;
2915 }
deadbeeffac06552015-11-25 11:26:01 -08002916
2917 // A sender has been removed from the SessionDescription but it's still
2918 // associated with the PeerConnection. This only occurs if the SDP doesn't
2919 // match with the calls to CreateSender, AddStream and RemoveStream.
2920 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002921 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2922 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002923 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002924 }
deadbeeffac06552015-11-25 11:26:01 -08002925
Steve Anton4171afb2017-11-20 10:20:22 -08002926 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002927}
2928
2929void PeerConnection::UpdateLocalRtpDataChannels(
2930 const cricket::StreamParamsVec& streams) {
2931 std::vector<std::string> existing_channels;
2932
2933 // Find new and active data channels.
2934 for (const cricket::StreamParams& params : streams) {
2935 // |it->sync_label| is actually the data channel label. The reason is that
2936 // we use the same naming of data channels as we do for
2937 // MediaStreams and Tracks.
2938 // For MediaStreams, the sync_label is the MediaStream label and the
2939 // track label is the same as |streamid|.
2940 const std::string& channel_label = params.sync_label;
2941 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002942 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002943 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002944 continue;
2945 }
2946 // Set the SSRC the data channel should use for sending.
2947 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2948 existing_channels.push_back(data_channel_it->first);
2949 }
2950
2951 UpdateClosingRtpDataChannels(existing_channels, true);
2952}
2953
2954void PeerConnection::UpdateRemoteRtpDataChannels(
2955 const cricket::StreamParamsVec& streams) {
2956 std::vector<std::string> existing_channels;
2957
2958 // Find new and active data channels.
2959 for (const cricket::StreamParams& params : streams) {
2960 // The data channel label is either the mslabel or the SSRC if the mslabel
2961 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2962 std::string label = params.sync_label.empty()
2963 ? rtc::ToString(params.first_ssrc())
2964 : params.sync_label;
2965 auto data_channel_it = rtp_data_channels_.find(label);
2966 if (data_channel_it == rtp_data_channels_.end()) {
2967 // This is a new data channel.
2968 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2969 } else {
2970 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2971 }
2972 existing_channels.push_back(label);
2973 }
2974
2975 UpdateClosingRtpDataChannels(existing_channels, false);
2976}
2977
2978void PeerConnection::UpdateClosingRtpDataChannels(
2979 const std::vector<std::string>& active_channels,
2980 bool is_local_update) {
2981 auto it = rtp_data_channels_.begin();
2982 while (it != rtp_data_channels_.end()) {
2983 DataChannel* data_channel = it->second;
2984 if (std::find(active_channels.begin(), active_channels.end(),
2985 data_channel->label()) != active_channels.end()) {
2986 ++it;
2987 continue;
2988 }
2989
2990 if (is_local_update) {
2991 data_channel->SetSendSsrc(0);
2992 } else {
2993 data_channel->RemotePeerRequestClose();
2994 }
2995
2996 if (data_channel->state() == DataChannel::kClosed) {
2997 rtp_data_channels_.erase(it);
2998 it = rtp_data_channels_.begin();
2999 } else {
3000 ++it;
3001 }
3002 }
3003}
3004
3005void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3006 uint32_t remote_ssrc) {
3007 rtc::scoped_refptr<DataChannel> channel(
3008 InternalCreateDataChannel(label, nullptr));
3009 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003010 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3011 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003012 return;
3013 }
3014 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003015 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3016 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003017 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003018}
3019
3020rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3021 const std::string& label,
3022 const InternalDataChannelInit* config) {
3023 if (IsClosed()) {
3024 return nullptr;
3025 }
Steve Anton75737c02017-11-06 10:37:17 -08003026 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003027 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003028 << "InternalCreateDataChannel: Data is not supported in this call.";
3029 return nullptr;
3030 }
3031 InternalDataChannelInit new_config =
3032 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003033 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003034 if (new_config.id < 0) {
3035 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003036 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003037 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003038 RTC_LOG(LS_ERROR)
3039 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003040 return nullptr;
3041 }
3042 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003043 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3044 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003045 return nullptr;
3046 }
3047 }
3048
Steve Anton75737c02017-11-06 10:37:17 -08003049 rtc::scoped_refptr<DataChannel> channel(
3050 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003051 if (!channel) {
3052 sid_allocator_.ReleaseSid(new_config.id);
3053 return nullptr;
3054 }
3055
3056 if (channel->data_channel_type() == cricket::DCT_RTP) {
3057 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003058 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3059 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003060 return nullptr;
3061 }
3062 rtp_data_channels_[channel->label()] = channel;
3063 } else {
3064 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3065 sctp_data_channels_.push_back(channel);
3066 channel->SignalClosed.connect(this,
3067 &PeerConnection::OnSctpDataChannelClosed);
3068 }
3069
hbos82ebe022016-11-14 01:41:09 -08003070 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003071 return channel;
3072}
3073
3074bool PeerConnection::HasDataChannels() const {
3075 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3076}
3077
3078void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3079 for (const auto& channel : sctp_data_channels_) {
3080 if (channel->id() < 0) {
3081 int sid;
3082 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003083 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003084 continue;
3085 }
3086 channel->SetSctpSid(sid);
3087 }
3088 }
3089}
3090
3091void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003092 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003093 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3094 ++it) {
3095 if (it->get() == channel) {
3096 if (channel->id() >= 0) {
3097 sid_allocator_.ReleaseSid(channel->id());
3098 }
deadbeefbd292462015-12-14 18:15:29 -08003099 // Since this method is triggered by a signal from the DataChannel,
3100 // we can't free it directly here; we need to free it asynchronously.
3101 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003102 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003103 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3104 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003105 return;
3106 }
3107 }
3108}
3109
deadbeefab9b2d12015-10-14 11:33:11 -07003110void PeerConnection::OnDataChannelDestroyed() {
3111 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3112 // DataChannel may callback to us and try to modify the list.
3113 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3114 temp_rtp_dcs.swap(rtp_data_channels_);
3115 for (const auto& kv : temp_rtp_dcs) {
3116 kv.second->OnTransportChannelDestroyed();
3117 }
3118
3119 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3120 temp_sctp_dcs.swap(sctp_data_channels_);
3121 for (const auto& channel : temp_sctp_dcs) {
3122 channel->OnTransportChannelDestroyed();
3123 }
3124}
3125
3126void PeerConnection::OnDataChannelOpenMessage(
3127 const std::string& label,
3128 const InternalDataChannelInit& config) {
3129 rtc::scoped_refptr<DataChannel> channel(
3130 InternalCreateDataChannel(label, &config));
3131 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003132 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003133 return;
3134 }
3135
deadbeefa601f5c2016-06-06 14:27:39 -07003136 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3137 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003138 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003139}
3140
Steve Anton4171afb2017-11-20 10:20:22 -08003141rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3142PeerConnection::GetAudioTransceiver() const {
3143 // This method only works with Plan B SDP, where there is a single
3144 // audio/video transceiver.
3145 RTC_DCHECK(!IsUnifiedPlan());
3146 for (auto transceiver : transceivers_) {
3147 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3148 return transceiver;
3149 }
3150 }
3151 RTC_NOTREACHED();
3152 return nullptr;
3153}
3154
3155rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3156PeerConnection::GetVideoTransceiver() const {
3157 // This method only works with Plan B SDP, where there is a single
3158 // audio/video transceiver.
3159 RTC_DCHECK(!IsUnifiedPlan());
3160 for (auto transceiver : transceivers_) {
3161 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3162 return transceiver;
3163 }
3164 }
3165 RTC_NOTREACHED();
3166 return nullptr;
3167}
3168
3169// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3170// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003171bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003172 switch (type) {
3173 case cricket::MEDIA_TYPE_AUDIO:
3174 return !GetAudioTransceiver()->internal()->senders().empty();
3175 case cricket::MEDIA_TYPE_VIDEO:
3176 return !GetVideoTransceiver()->internal()->senders().empty();
3177 case cricket::MEDIA_TYPE_DATA:
3178 return false;
3179 }
3180 RTC_NOTREACHED();
3181 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003182}
3183
Steve Anton4171afb2017-11-20 10:20:22 -08003184rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3185PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3186 for (auto transceiver : transceivers_) {
3187 for (auto sender : transceiver->internal()->senders()) {
3188 if (sender->track() == track) {
3189 return sender;
3190 }
3191 }
3192 }
3193 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003194}
3195
Steve Anton4171afb2017-11-20 10:20:22 -08003196rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3197PeerConnection::FindSenderById(const std::string& sender_id) const {
3198 for (auto transceiver : transceivers_) {
3199 for (auto sender : transceiver->internal()->senders()) {
3200 if (sender->id() == sender_id) {
3201 return sender;
3202 }
3203 }
3204 }
3205 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003206}
3207
Steve Anton4171afb2017-11-20 10:20:22 -08003208rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3209PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3210 for (auto transceiver : transceivers_) {
3211 for (auto receiver : transceiver->internal()->receivers()) {
3212 if (receiver->id() == receiver_id) {
3213 return receiver;
3214 }
3215 }
3216 }
3217 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003218}
3219
Steve Anton4171afb2017-11-20 10:20:22 -08003220std::vector<PeerConnection::RtpSenderInfo>*
3221PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3222 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3223 media_type == cricket::MEDIA_TYPE_VIDEO);
3224 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3225 ? &remote_audio_sender_infos_
3226 : &remote_video_sender_infos_;
3227}
3228
3229std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003230 cricket::MediaType media_type) {
3231 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3232 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003233 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3234 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003235}
3236
Steve Anton4171afb2017-11-20 10:20:22 -08003237const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3238 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003239 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003240 const std::string sender_id) const {
3241 for (const RtpSenderInfo& sender_info : infos) {
3242 if (sender_info.stream_label == stream_label &&
3243 sender_info.sender_id == sender_id) {
3244 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003245 }
3246 }
3247 return nullptr;
3248}
3249
3250DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3251 for (const auto& channel : sctp_data_channels_) {
3252 if (channel->id() == sid) {
3253 return channel;
3254 }
3255 }
3256 return nullptr;
3257}
3258
deadbeef91dd5672016-05-18 16:55:30 -07003259bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003260 const RTCConfiguration& configuration) {
3261 cricket::ServerAddresses stun_servers;
3262 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003263 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3264 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003265 return false;
3266 }
3267
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003268 port_allocator_->Initialize();
3269
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003270 // To handle both internal and externally created port allocator, we will
3271 // enable BUNDLE here.
3272 int portallocator_flags = port_allocator_->flags();
3273 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003274 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3275 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003276 // If the disable-IPv6 flag was specified, we'll not override it
3277 // by experiment.
3278 if (configuration.disable_ipv6) {
3279 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003280 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3281 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003282 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3283 }
3284
zhihuangb09b3f92017-03-07 14:40:51 -08003285 if (configuration.disable_ipv6_on_wifi) {
3286 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003287 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003288 }
3289
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003290 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3291 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003292 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003293 }
3294
honghaiz60347052016-05-31 18:29:12 -07003295 if (configuration.candidate_network_policy ==
3296 kCandidateNetworkPolicyLowCost) {
3297 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003298 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003299 }
3300
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003301 port_allocator_->set_flags(portallocator_flags);
3302 // No step delay is used while allocating ports.
3303 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3304 port_allocator_->set_candidate_filter(
3305 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003306 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003307
3308 // Call this last since it may create pooled allocator sessions using the
3309 // properties set above.
3310 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003311 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003312 configuration.prune_turn_ports,
3313 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003314 return true;
3315}
3316
deadbeef91dd5672016-05-18 16:55:30 -07003317bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003318 const cricket::ServerAddresses& stun_servers,
3319 const std::vector<cricket::RelayServerConfig>& turn_servers,
3320 IceTransportsType type,
3321 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003322 bool prune_turn_ports,
3323 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003324 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003325 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003326 // Call this last since it may create pooled allocator sessions using the
3327 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003328 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003329 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3330 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003331}
3332
Steve Antonba818672017-11-06 10:21:57 -08003333cricket::ChannelManager* PeerConnection::channel_manager() const {
3334 return factory_->channel_manager();
3335}
3336
3337MetricsObserverInterface* PeerConnection::metrics_observer() const {
3338 return uma_observer_;
3339}
3340
Elad Alon99c3fe52017-10-13 16:29:40 +02003341bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003342 std::unique_ptr<RtcEventLogOutput> output,
3343 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003344 if (!event_log_) {
3345 return false;
3346 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003347 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003348}
3349
3350void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003351 if (event_log_) {
3352 event_log_->StopLogging();
3353 }
ivoc14d5dbe2016-07-04 07:06:55 -07003354}
nisseeaabdf62017-05-05 02:23:02 -07003355
Steve Anton75737c02017-11-06 10:37:17 -08003356cricket::BaseChannel* PeerConnection::GetChannel(
3357 const std::string& content_name) {
3358 if (voice_channel() && voice_channel()->content_name() == content_name) {
3359 return voice_channel();
3360 }
3361 if (video_channel() && video_channel()->content_name() == content_name) {
3362 return video_channel();
3363 }
3364 if (rtp_data_channel() &&
3365 rtp_data_channel()->content_name() == content_name) {
3366 return rtp_data_channel();
3367 }
3368 return nullptr;
3369}
3370
3371bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3372 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003373 RTC_LOG(LS_INFO)
3374 << "Local and Remote descriptions must be applied to get the "
3375 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003376 return false;
3377 }
3378 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003379 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3380 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003381 return false;
3382 }
3383
3384 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3385}
3386
3387bool PeerConnection::GetSslRole(const std::string& content_name,
3388 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 session.";
Steve Anton75737c02017-11-06 10:37:17 -08003393 return false;
3394 }
3395
3396 return transport_controller_->GetSslRole(GetTransportName(content_name),
3397 role);
3398}
3399
Henrik Boström31638672017-11-23 17:48:32 +01003400bool PeerConnection::SetCurrentOrPendingLocalDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003401 std::unique_ptr<SessionDescriptionInterface> desc,
3402 std::string* err_desc) {
3403 RTC_DCHECK(signaling_thread()->IsCurrent());
3404
3405 // Validate SDP.
3406 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3407 return false;
3408 }
3409
3410 // Update the initial_offerer flag if this session is the initial_offerer.
3411 Action action = GetAction(desc->type());
3412 if (!initial_offerer_.has_value()) {
3413 initial_offerer_.emplace(action == kOffer);
3414 if (*initial_offerer_) {
3415 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3416 } else {
3417 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3418 }
3419 }
3420
3421 if (action == kAnswer) {
3422 current_local_description_ = std::move(desc);
3423 pending_local_description_ = nullptr;
3424 current_remote_description_ = std::move(pending_remote_description_);
3425 } else {
3426 pending_local_description_ = std::move(desc);
3427 }
3428
3429 // Transport and Media channels will be created only when offer is set.
3430 if (action == kOffer && !CreateChannels(local_description()->description())) {
3431 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3432 // is applied. Restore back to old description.
3433 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3434 err_desc);
3435 }
3436
3437 // Remove unused channels if MediaContentDescription is rejected.
3438 RemoveUnusedChannels(local_description()->description());
3439
3440 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3441 return false;
3442 }
3443 if (remote_description()) {
3444 // Now that we have a local description, we can push down remote candidates.
3445 UseCandidatesInSessionDescription(remote_description());
3446 }
3447
3448 pending_ice_restarts_.clear();
3449 if (error() != ERROR_NONE) {
3450 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3451 err_desc);
3452 }
3453 return true;
3454}
3455
Henrik Boström31638672017-11-23 17:48:32 +01003456bool PeerConnection::SetCurrentOrPendingRemoteDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003457 std::unique_ptr<SessionDescriptionInterface> desc,
3458 std::string* err_desc) {
3459 RTC_DCHECK(signaling_thread()->IsCurrent());
3460
3461 // Validate SDP.
3462 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3463 return false;
3464 }
3465
3466 // Hold this pointer so candidates can be copied to it later in the method.
3467 SessionDescriptionInterface* desc_ptr = desc.get();
3468
3469 const SessionDescriptionInterface* old_remote_description =
3470 remote_description();
3471 // Grab ownership of the description being replaced for the remainder of this
3472 // method, since it's used below as |old_remote_description|.
3473 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3474 Action action = GetAction(desc->type());
3475 if (action == kAnswer) {
3476 replaced_remote_description = pending_remote_description_
3477 ? std::move(pending_remote_description_)
3478 : std::move(current_remote_description_);
3479 current_remote_description_ = std::move(desc);
3480 pending_remote_description_ = nullptr;
3481 current_local_description_ = std::move(pending_local_description_);
3482 } else {
3483 replaced_remote_description = std::move(pending_remote_description_);
3484 pending_remote_description_ = std::move(desc);
3485 }
3486
3487 // Transport and Media channels will be created only when offer is set.
3488 if (action == kOffer &&
3489 !CreateChannels(remote_description()->description())) {
3490 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3491 // is applied. Restore back to old description.
3492 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3493 err_desc);
3494 }
3495
3496 // Remove unused channels if MediaContentDescription is rejected.
3497 RemoveUnusedChannels(remote_description()->description());
3498
3499 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3500 // is called.
3501 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3502 return false;
3503 }
3504
3505 if (local_description() &&
3506 !UseCandidatesInSessionDescription(remote_description())) {
3507 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3508 err_desc);
3509 }
3510
3511 if (old_remote_description) {
3512 for (const cricket::ContentInfo& content :
3513 old_remote_description->description()->contents()) {
3514 // Check if this new SessionDescription contains new ICE ufrag and
3515 // password that indicates the remote peer requests an ICE restart.
3516 // TODO(deadbeef): When we start storing both the current and pending
3517 // remote description, this should reset pending_ice_restarts and compare
3518 // against the current description.
3519 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3520 content.name)) {
3521 if (action == kOffer) {
3522 pending_ice_restarts_.insert(content.name);
3523 }
3524 } else {
3525 // We retain all received candidates only if ICE is not restarted.
3526 // When ICE is restarted, all previous candidates belong to an old
3527 // generation and should not be kept.
3528 // TODO(deadbeef): This goes against the W3C spec which says the remote
3529 // description should only contain candidates from the last set remote
3530 // description plus any candidates added since then. We should remove
3531 // this once we're sure it won't break anything.
3532 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3533 old_remote_description, content.name, desc_ptr);
3534 }
3535 }
3536 }
3537
3538 if (error() != ERROR_NONE) {
3539 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3540 err_desc);
3541 }
3542
3543 // Set the the ICE connection state to connecting since the connection may
3544 // become writable with peer reflexive candidates before any remote candidate
3545 // is signaled.
3546 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3547 // is to have a new signal the indicates a change in checking state from the
3548 // transport and expose a new checking() member from transport that can be
3549 // read to determine the current checking state. The existing SignalConnecting
3550 // actually means "gathering candidates", so cannot be be used here.
3551 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3552 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3553 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3554 }
3555 return true;
3556}
3557
3558// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3559// vector of BaseChannel pointers instead of separate voice and video channel
3560// vectors. At that point, this will become a simple getter.
3561std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3562 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003563 if (voice_channel()) {
3564 channels.push_back(voice_channel());
3565 }
3566 if (video_channel()) {
3567 channels.push_back(video_channel());
3568 }
Steve Anton75737c02017-11-06 10:37:17 -08003569 if (rtp_data_channel_) {
3570 channels.push_back(rtp_data_channel_);
3571 }
3572 return channels;
3573}
3574
3575void PeerConnection::SetError(Error error, const std::string& error_desc) {
3576 RTC_DCHECK(signaling_thread()->IsCurrent());
3577 if (error != error_) {
3578 error_ = error;
3579 error_desc_ = error_desc;
3580 }
3581}
3582
3583bool PeerConnection::UpdateSessionState(Action action,
3584 cricket::ContentSource source,
3585 std::string* err_desc) {
3586 RTC_DCHECK(signaling_thread()->IsCurrent());
3587
3588 // If there's already a pending error then no state transition should happen.
3589 // But all call-sites should be verifying this before calling us!
3590 RTC_DCHECK(error() == ERROR_NONE);
3591 std::string td_err;
3592 if (action == kOffer) {
3593 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3594 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3595 }
3596 ChangeSignalingState(source == cricket::CS_LOCAL
3597 ? PeerConnectionInterface::kHaveLocalOffer
3598 : PeerConnectionInterface::kHaveRemoteOffer);
3599 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3600 SetError(ERROR_CONTENT, *err_desc);
3601 }
3602 if (error() != ERROR_NONE) {
3603 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3604 }
3605 } else if (action == kPrAnswer) {
3606 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3607 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3608 }
3609 EnableChannels();
3610 ChangeSignalingState(source == cricket::CS_LOCAL
3611 ? PeerConnectionInterface::kHaveLocalPrAnswer
3612 : PeerConnectionInterface::kHaveRemotePrAnswer);
3613 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3614 SetError(ERROR_CONTENT, *err_desc);
3615 }
3616 if (error() != ERROR_NONE) {
3617 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3618 }
3619 } else if (action == kAnswer) {
3620 const cricket::ContentGroup* local_bundle =
3621 local_description()->description()->GetGroupByName(
3622 cricket::GROUP_TYPE_BUNDLE);
3623 const cricket::ContentGroup* remote_bundle =
3624 remote_description()->description()->GetGroupByName(
3625 cricket::GROUP_TYPE_BUNDLE);
3626 if (local_bundle && remote_bundle) {
3627 // The answerer decides the transport to bundle on.
3628 const cricket::ContentGroup* answer_bundle =
3629 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3630 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003631 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003632 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3633 }
3634 }
3635 // Only push down the transport description after enabling BUNDLE; we don't
3636 // want to push down a description on a transport about to be destroyed.
3637 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3638 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3639 }
3640 EnableChannels();
3641 ChangeSignalingState(PeerConnectionInterface::kStable);
3642 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3643 SetError(ERROR_CONTENT, *err_desc);
3644 }
3645 if (error() != ERROR_NONE) {
3646 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3647 }
3648 }
3649 return true;
3650}
3651
3652PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3653 if (type == SessionDescriptionInterface::kOffer) {
3654 return PeerConnection::kOffer;
3655 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3656 return PeerConnection::kPrAnswer;
3657 } else if (type == SessionDescriptionInterface::kAnswer) {
3658 return PeerConnection::kAnswer;
3659 }
3660 RTC_NOTREACHED() << "unknown action type";
3661 return PeerConnection::kOffer;
3662}
3663
3664bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3665 cricket::ContentSource source,
3666 std::string* err) {
3667 const SessionDescription* sdesc =
3668 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3669 ->description();
3670 RTC_DCHECK(sdesc);
3671 bool all_success = true;
3672 for (auto* channel : Channels()) {
3673 // TODO(steveanton): Add support for multiple channels of the same type.
3674 const ContentInfo* content_info =
3675 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3676 if (!content_info) {
3677 continue;
3678 }
3679 const MediaContentDescription* content_desc =
3680 static_cast<const MediaContentDescription*>(content_info->description);
3681 if (content_desc && !content_info->rejected) {
3682 bool success = (source == cricket::CS_LOCAL)
3683 ? channel->SetLocalContent(content_desc, action, err)
3684 : channel->SetRemoteContent(content_desc, action, err);
3685 if (!success) {
3686 all_success = false;
3687 break;
3688 }
3689 }
3690 }
3691 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3692 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3693 if (sctp_transport_ && local_description() && remote_description() &&
3694 cricket::GetFirstDataContent(local_description()->description()) &&
3695 cricket::GetFirstDataContent(remote_description()->description())) {
3696 all_success &= network_thread()->Invoke<bool>(
3697 RTC_FROM_HERE,
3698 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3699 }
3700 return all_success;
3701}
3702
3703bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3704 RTC_DCHECK(network_thread()->IsCurrent());
3705 RTC_DCHECK(local_description());
3706 RTC_DCHECK(remote_description());
3707 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3708 // When we support "max-message-size", that would also be pushed down here.
3709 return sctp_transport_->Start(
3710 GetSctpPort(local_description()->description()),
3711 GetSctpPort(remote_description()->description()));
3712}
3713
3714bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3715 cricket::ContentAction action,
3716 std::string* error_desc) {
3717 RTC_DCHECK(signaling_thread()->IsCurrent());
3718
3719 if (source == cricket::CS_LOCAL) {
3720 return PushdownLocalTransportDescription(local_description()->description(),
3721 action, error_desc);
3722 }
3723 return PushdownRemoteTransportDescription(remote_description()->description(),
3724 action, error_desc);
3725}
3726
3727bool PeerConnection::PushdownLocalTransportDescription(
3728 const SessionDescription* sdesc,
3729 cricket::ContentAction action,
3730 std::string* err) {
3731 RTC_DCHECK(signaling_thread()->IsCurrent());
3732
3733 if (!sdesc) {
3734 return false;
3735 }
3736
3737 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3738 if (!transport_controller_->SetLocalTransportDescription(
3739 tinfo.content_name, tinfo.description, action, err)) {
3740 return false;
3741 }
3742 }
3743
3744 return true;
3745}
3746
3747bool PeerConnection::PushdownRemoteTransportDescription(
3748 const SessionDescription* sdesc,
3749 cricket::ContentAction action,
3750 std::string* err) {
3751 RTC_DCHECK(signaling_thread()->IsCurrent());
3752
3753 if (!sdesc) {
3754 return false;
3755 }
3756
3757 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3758 if (!transport_controller_->SetRemoteTransportDescription(
3759 tinfo.content_name, tinfo.description, action, err)) {
3760 return false;
3761 }
3762 }
3763
3764 return true;
3765}
3766
3767bool PeerConnection::GetTransportDescription(
3768 const SessionDescription* description,
3769 const std::string& content_name,
3770 cricket::TransportDescription* tdesc) {
3771 if (!description || !tdesc) {
3772 return false;
3773 }
3774 const TransportInfo* transport_info =
3775 description->GetTransportInfoByName(content_name);
3776 if (!transport_info) {
3777 return false;
3778 }
3779 *tdesc = transport_info->description;
3780 return true;
3781}
3782
3783bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3784 const std::string* first_content_name = bundle.FirstContentName();
3785 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003786 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003787 return false;
3788 }
3789 const std::string& transport_name = *first_content_name;
3790
3791 auto maybe_set_transport = [this, bundle,
3792 transport_name](cricket::BaseChannel* ch) {
3793 if (!ch || !bundle.HasContentName(ch->content_name())) {
3794 return true;
3795 }
3796
3797 std::string old_transport_name = ch->transport_name();
3798 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003799 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3800 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003801 return true;
3802 }
3803
3804 cricket::DtlsTransportInternal* rtp_dtls_transport =
3805 transport_controller_->CreateDtlsTransport(
3806 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3807 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3808 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3809 if (need_rtcp) {
3810 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3811 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3812 }
3813
3814 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003815 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3816 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003817 transport_controller_->DestroyDtlsTransport(
3818 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3819 // If the channel needs rtcp, it means that the channel used to have a
3820 // rtcp transport which needs to be deleted now.
3821 if (need_rtcp) {
3822 transport_controller_->DestroyDtlsTransport(
3823 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3824 }
3825 return true;
3826 };
3827
3828 if (!maybe_set_transport(voice_channel()) ||
3829 !maybe_set_transport(video_channel()) ||
3830 !maybe_set_transport(rtp_data_channel())) {
3831 return false;
3832 }
3833 // For SCTP, transport creation/deletion happens here instead of in the
3834 // object itself.
3835 if (sctp_transport_) {
3836 RTC_DCHECK(sctp_transport_name_);
3837 RTC_DCHECK(sctp_content_name_);
3838 if (transport_name != *sctp_transport_name_ &&
3839 bundle.HasContentName(*sctp_content_name_)) {
3840 network_thread()->Invoke<void>(
3841 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3842 transport_name));
3843 }
3844 }
3845
3846 return true;
3847}
3848
Steve Anton75737c02017-11-06 10:37:17 -08003849cricket::IceConfig PeerConnection::ParseIceConfig(
3850 const PeerConnectionInterface::RTCConfiguration& config) const {
3851 cricket::ContinualGatheringPolicy gathering_policy;
3852 // TODO(honghaiz): Add the third continual gathering policy in
3853 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3854 switch (config.continual_gathering_policy) {
3855 case PeerConnectionInterface::GATHER_ONCE:
3856 gathering_policy = cricket::GATHER_ONCE;
3857 break;
3858 case PeerConnectionInterface::GATHER_CONTINUALLY:
3859 gathering_policy = cricket::GATHER_CONTINUALLY;
3860 break;
3861 default:
3862 RTC_NOTREACHED();
3863 gathering_policy = cricket::GATHER_ONCE;
3864 }
3865 cricket::IceConfig ice_config;
3866 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3867 ice_config.prioritize_most_likely_candidate_pairs =
3868 config.prioritize_most_likely_ice_candidate_pairs;
3869 ice_config.backup_connection_ping_interval =
3870 config.ice_backup_candidate_pair_ping_interval;
3871 ice_config.continual_gathering_policy = gathering_policy;
3872 ice_config.presume_writable_when_fully_relayed =
3873 config.presume_writable_when_fully_relayed;
3874 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3875 ice_config.regather_all_networks_interval_range =
3876 config.ice_regather_interval_range;
3877 return ice_config;
3878}
3879
Steve Anton75737c02017-11-06 10:37:17 -08003880bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3881 std::string* track_id) {
3882 if (!local_description()) {
3883 return false;
3884 }
3885 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3886 track_id);
3887}
3888
3889bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3890 std::string* track_id) {
3891 if (!remote_description()) {
3892 return false;
3893 }
3894 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3895 track_id);
3896}
3897
3898bool PeerConnection::SendData(const cricket::SendDataParams& params,
3899 const rtc::CopyOnWriteBuffer& payload,
3900 cricket::SendDataResult* result) {
3901 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003902 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3903 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003904 return false;
3905 }
3906 return rtp_data_channel_
3907 ? rtp_data_channel_->SendData(params, payload, result)
3908 : network_thread()->Invoke<bool>(
3909 RTC_FROM_HERE,
3910 Bind(&cricket::SctpTransportInternal::SendData,
3911 sctp_transport_.get(), params, payload, result));
3912}
3913
3914bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3915 if (!rtp_data_channel_ && !sctp_transport_) {
3916 // Don't log an error here, because DataChannels are expected to call
3917 // ConnectDataChannel in this state. It's the only way to initially tell
3918 // whether or not the underlying transport is ready.
3919 return false;
3920 }
3921 if (rtp_data_channel_) {
3922 rtp_data_channel_->SignalReadyToSendData.connect(
3923 webrtc_data_channel, &DataChannel::OnChannelReady);
3924 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3925 &DataChannel::OnDataReceived);
3926 } else {
3927 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3928 &DataChannel::OnChannelReady);
3929 SignalSctpDataReceived.connect(webrtc_data_channel,
3930 &DataChannel::OnDataReceived);
3931 SignalSctpStreamClosedRemotely.connect(
3932 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3933 }
3934 return true;
3935}
3936
3937void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3938 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003939 RTC_LOG(LS_ERROR)
3940 << "DisconnectDataChannel called when rtp_data_channel_ and "
3941 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003942 return;
3943 }
3944 if (rtp_data_channel_) {
3945 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3946 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3947 } else {
3948 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3949 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3950 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3951 }
3952}
3953
3954void PeerConnection::AddSctpDataStream(int sid) {
3955 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003956 RTC_LOG(LS_ERROR)
3957 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003958 return;
3959 }
3960 network_thread()->Invoke<void>(
3961 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3962 sctp_transport_.get(), sid));
3963}
3964
3965void PeerConnection::RemoveSctpDataStream(int sid) {
3966 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003967 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3968 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003969 return;
3970 }
3971 network_thread()->Invoke<void>(
3972 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3973 sctp_transport_.get(), sid));
3974}
3975
3976bool PeerConnection::ReadyToSendData() const {
3977 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3978 sctp_ready_to_send_data_;
3979}
3980
3981std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3982 RTC_DCHECK(signaling_thread()->IsCurrent());
3983 ChannelNamePairs channel_name_pairs;
3984 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003985 channel_name_pairs.voice = ChannelNamePair(
3986 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003987 }
3988 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003989 channel_name_pairs.video = ChannelNamePair(
3990 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003991 }
3992 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003993 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003994 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003995 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003996 }
3997 if (sctp_transport_) {
3998 RTC_DCHECK(sctp_content_name_);
3999 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004000 channel_name_pairs.data =
4001 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004002 }
4003 return GetSessionStats(channel_name_pairs);
4004}
4005
4006std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4007 const ChannelNamePairs& channel_name_pairs) {
4008 if (network_thread()->IsCurrent()) {
4009 return GetSessionStats_n(channel_name_pairs);
4010 }
4011 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4012 RTC_FROM_HERE,
4013 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4014}
4015
4016bool PeerConnection::GetLocalCertificate(
4017 const std::string& transport_name,
4018 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4019 return transport_controller_->GetLocalCertificate(transport_name,
4020 certificate);
4021}
4022
4023std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4024 const std::string& transport_name) {
4025 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4026}
4027
4028cricket::DataChannelType PeerConnection::data_channel_type() const {
4029 return data_channel_type_;
4030}
4031
4032bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4033 return pending_ice_restarts_.find(content_name) !=
4034 pending_ice_restarts_.end();
4035}
4036
Steve Anton75737c02017-11-06 10:37:17 -08004037bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4038 return transport_controller_->NeedsIceRestart(content_name);
4039}
4040
4041void PeerConnection::OnCertificateReady(
4042 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4043 transport_controller_->SetLocalCertificate(certificate);
4044}
4045
4046void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
4047 SetError(ERROR_TRANSPORT,
4048 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
4049}
4050
4051void PeerConnection::OnTransportControllerConnectionState(
4052 cricket::IceConnectionState state) {
4053 switch (state) {
4054 case cricket::kIceConnectionConnecting:
4055 // If the current state is Connected or Completed, then there were
4056 // writable channels but now there are not, so the next state must
4057 // be Disconnected.
4058 // kIceConnectionConnecting is currently used as the default,
4059 // un-connected state by the TransportController, so its only use is
4060 // detecting disconnections.
4061 if (ice_connection_state_ ==
4062 PeerConnectionInterface::kIceConnectionConnected ||
4063 ice_connection_state_ ==
4064 PeerConnectionInterface::kIceConnectionCompleted) {
4065 SetIceConnectionState(
4066 PeerConnectionInterface::kIceConnectionDisconnected);
4067 }
4068 break;
4069 case cricket::kIceConnectionFailed:
4070 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4071 break;
4072 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004073 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4074 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004075 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4076 break;
4077 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004078 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4079 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004080 if (ice_connection_state_ !=
4081 PeerConnectionInterface::kIceConnectionConnected) {
4082 // If jumping directly from "checking" to "connected",
4083 // signal "connected" first.
4084 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4085 }
4086 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4087 if (metrics_observer()) {
4088 ReportTransportStats();
4089 }
4090 break;
4091 default:
4092 RTC_NOTREACHED();
4093 }
4094}
4095
4096void PeerConnection::OnTransportControllerCandidatesGathered(
4097 const std::string& transport_name,
4098 const cricket::Candidates& candidates) {
4099 RTC_DCHECK(signaling_thread()->IsCurrent());
4100 int sdp_mline_index;
4101 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004102 RTC_LOG(LS_ERROR)
4103 << "OnTransportControllerCandidatesGathered: content name "
4104 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004105 return;
4106 }
4107
4108 for (cricket::Candidates::const_iterator citer = candidates.begin();
4109 citer != candidates.end(); ++citer) {
4110 // Use transport_name as the candidate media id.
4111 std::unique_ptr<JsepIceCandidate> candidate(
4112 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4113 if (local_description()) {
4114 mutable_local_description()->AddCandidate(candidate.get());
4115 }
4116 OnIceCandidate(std::move(candidate));
4117 }
4118}
4119
4120void PeerConnection::OnTransportControllerCandidatesRemoved(
4121 const std::vector<cricket::Candidate>& candidates) {
4122 RTC_DCHECK(signaling_thread()->IsCurrent());
4123 // Sanity check.
4124 for (const cricket::Candidate& candidate : candidates) {
4125 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004126 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4127 << "empty content name in candidate "
4128 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004129 return;
4130 }
4131 }
4132
4133 if (local_description()) {
4134 mutable_local_description()->RemoveCandidates(candidates);
4135 }
4136 OnIceCandidatesRemoved(candidates);
4137}
4138
4139void PeerConnection::OnTransportControllerDtlsHandshakeError(
4140 rtc::SSLHandshakeError error) {
4141 if (metrics_observer()) {
4142 metrics_observer()->IncrementEnumCounter(
4143 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4144 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4145 }
4146}
4147
4148// Enabling voice and video (and RTP data) channels.
4149void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004150 if (voice_channel() && !voice_channel()->enabled()) {
4151 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004152 }
4153
Steve Anton4171afb2017-11-20 10:20:22 -08004154 if (video_channel() && !video_channel()->enabled()) {
4155 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004156 }
4157
Steve Anton4171afb2017-11-20 10:20:22 -08004158 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004159 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004160 }
Steve Anton75737c02017-11-06 10:37:17 -08004161}
4162
4163// Returns the media index for a local ice candidate given the content name.
4164bool PeerConnection::GetLocalCandidateMediaIndex(
4165 const std::string& content_name,
4166 int* sdp_mline_index) {
4167 if (!local_description() || !sdp_mline_index) {
4168 return false;
4169 }
4170
4171 bool content_found = false;
4172 const ContentInfos& contents = local_description()->description()->contents();
4173 for (size_t index = 0; index < contents.size(); ++index) {
4174 if (contents[index].name == content_name) {
4175 *sdp_mline_index = static_cast<int>(index);
4176 content_found = true;
4177 break;
4178 }
4179 }
4180 return content_found;
4181}
4182
4183bool PeerConnection::UseCandidatesInSessionDescription(
4184 const SessionDescriptionInterface* remote_desc) {
4185 if (!remote_desc) {
4186 return true;
4187 }
4188 bool ret = true;
4189
4190 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4191 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4192 for (size_t n = 0; n < candidates->count(); ++n) {
4193 const IceCandidateInterface* candidate = candidates->at(n);
4194 bool valid = false;
4195 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4196 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_INFO)
4198 << "UseCandidatesInSessionDescription: Not ready to use "
4199 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004200 }
4201 continue;
4202 }
4203 ret = UseCandidate(candidate);
4204 if (!ret) {
4205 break;
4206 }
4207 }
4208 }
4209 return ret;
4210}
4211
4212bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4213 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4214 size_t remote_content_size =
4215 remote_description()->description()->contents().size();
4216 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004217 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004218 return false;
4219 }
4220
4221 cricket::ContentInfo content =
4222 remote_description()->description()->contents()[mediacontent_index];
4223 std::vector<cricket::Candidate> candidates;
4224 candidates.push_back(candidate->candidate());
4225 // Invoking BaseSession method to handle remote candidates.
4226 std::string error;
4227 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4228 &error)) {
4229 // Candidates successfully submitted for checking.
4230 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4231 ice_connection_state_ ==
4232 PeerConnectionInterface::kIceConnectionDisconnected) {
4233 // If state is New, then the session has just gotten its first remote ICE
4234 // candidates, so go to Checking.
4235 // If state is Disconnected, the session is re-using old candidates or
4236 // receiving additional ones, so go to Checking.
4237 // If state is Connected, stay Connected.
4238 // TODO(bemasc): If state is Connected, and the new candidates are for a
4239 // newly added transport, then the state actually _should_ move to
4240 // checking. Add a way to distinguish that case.
4241 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4242 }
4243 // TODO(bemasc): If state is Completed, go back to Connected.
4244 } else {
4245 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004246 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004247 }
4248 }
4249 return true;
4250}
4251
4252void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004253 // Destroy video channel first since it may have a pointer to the
4254 // voice channel.
4255 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004256 if (!video_info || video_info->rejected) {
4257 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004258 }
4259
Steve Anton6fec8802017-12-04 10:37:29 -08004260 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4261 if (!audio_info || audio_info->rejected) {
4262 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004263 }
4264
4265 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4266 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004267 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004268 }
4269}
4270
Steve Antoneda6ccd2017-12-04 10:21:55 -08004271std::string PeerConnection::GetTransportNameForMediaSection(
4272 const std::string& mid,
4273 const cricket::ContentGroup* bundle_group) const {
4274 if (!bundle_group) {
4275 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004276 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004277 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004278 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004279 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004280 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004281 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004282 if (!bundle_group->HasContentName(mid)) {
4283 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4284 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004285 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004286 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4287 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004288}
4289
4290bool PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004291 RTC_DCHECK(desc);
4292
Steve Anton75737c02017-11-06 10:37:17 -08004293 const cricket::ContentGroup* bundle_group = nullptr;
4294 if (configuration_.bundle_policy ==
4295 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4296 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4297 if (!bundle_group) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004298 RTC_LOG(LS_WARNING) << "max-bundle configured but session description "
4299 "has no BUNDLE group";
Steve Anton75737c02017-11-06 10:37:17 -08004300 return false;
4301 }
4302 }
4303
Steve Antoneda6ccd2017-12-04 10:21:55 -08004304 // Creating the media channels and transport proxies.
4305 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4306 if (voice && !voice->rejected &&
4307 !GetAudioTransceiver()->internal()->channel()) {
4308 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4309 voice->name,
4310 GetTransportNameForMediaSection(voice->name, bundle_group));
4311 if (!voice_channel) {
4312 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
4313 return false;
4314 }
4315 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4316 }
4317
Steve Anton75737c02017-11-06 10:37:17 -08004318 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004319 if (video && !video->rejected &&
4320 !GetVideoTransceiver()->internal()->channel()) {
4321 cricket::VideoChannel* video_channel = CreateVideoChannel(
4322 video->name,
4323 GetTransportNameForMediaSection(video->name, bundle_group));
4324 if (!video_channel) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004325 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004326 return false;
4327 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004328 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004329 }
4330
4331 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4332 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4333 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004334 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4335 data->name, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004336 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004337 return false;
4338 }
4339 }
4340
4341 return true;
4342}
4343
Steve Anton4171afb2017-11-20 10:20:22 -08004344// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004345cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4346 const std::string& mid,
4347 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004348 cricket::DtlsTransportInternal* rtp_dtls_transport =
4349 transport_controller_->CreateDtlsTransport(
4350 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4351 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4352 if (configuration_.rtcp_mux_policy !=
4353 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4354 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4355 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4356 }
4357
4358 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4359 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004360 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4361 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004362 if (!voice_channel) {
4363 transport_controller_->DestroyDtlsTransport(
4364 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4365 if (rtcp_dtls_transport) {
4366 transport_controller_->DestroyDtlsTransport(
4367 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4368 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004369 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004370 }
Steve Anton75737c02017-11-06 10:37:17 -08004371 voice_channel->SignalRtcpMuxFullyActive.connect(
4372 this, &PeerConnection::DestroyRtcpTransport_n);
4373 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4374 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004375 voice_channel->SignalSentPacket.connect(this,
4376 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004377
Steve Antoneda6ccd2017-12-04 10:21:55 -08004378 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004379}
4380
Steve Anton4171afb2017-11-20 10:20:22 -08004381// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004382cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4383 const std::string& mid,
4384 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004385 cricket::DtlsTransportInternal* rtp_dtls_transport =
4386 transport_controller_->CreateDtlsTransport(
4387 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4388 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4389 if (configuration_.rtcp_mux_policy !=
4390 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4391 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4392 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4393 }
4394
4395 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4396 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004397 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4398 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004399
4400 if (!video_channel) {
4401 transport_controller_->DestroyDtlsTransport(
4402 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4403 if (rtcp_dtls_transport) {
4404 transport_controller_->DestroyDtlsTransport(
4405 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4406 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004407 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004408 }
Steve Anton75737c02017-11-06 10:37:17 -08004409 video_channel->SignalRtcpMuxFullyActive.connect(
4410 this, &PeerConnection::DestroyRtcpTransport_n);
4411 video_channel->SignalDtlsSrtpSetupFailure.connect(
4412 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004413 video_channel->SignalSentPacket.connect(this,
4414 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004415
Steve Antoneda6ccd2017-12-04 10:21:55 -08004416 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004417}
4418
Steve Antoneda6ccd2017-12-04 10:21:55 -08004419bool PeerConnection::CreateDataChannel(const std::string& mid,
4420 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004421 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4422 if (sctp) {
4423 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004424 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004425 << "Trying to create SCTP transport, but didn't compile with "
4426 "SCTP support (HAVE_SCTP)";
4427 return false;
4428 }
4429 if (!network_thread()->Invoke<bool>(
4430 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004431 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004432 return false;
4433 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004434 for (const auto& channel : sctp_data_channels_) {
4435 channel->OnTransportChannelCreated();
4436 }
Steve Anton75737c02017-11-06 10:37:17 -08004437 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004438 cricket::DtlsTransportInternal* rtp_dtls_transport =
4439 transport_controller_->CreateDtlsTransport(
4440 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4441 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4442 if (configuration_.rtcp_mux_policy !=
4443 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4444 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4445 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4446 }
4447
4448 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4449 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004450 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004451
4452 if (!rtp_data_channel_) {
4453 transport_controller_->DestroyDtlsTransport(
4454 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4455 if (rtcp_dtls_transport) {
4456 transport_controller_->DestroyDtlsTransport(
4457 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4458 }
4459 return false;
4460 }
4461
4462 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4463 this, &PeerConnection::DestroyRtcpTransport_n);
4464 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4465 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4466 rtp_data_channel_->SignalSentPacket.connect(
4467 this, &PeerConnection::OnSentPacket_w);
4468 }
4469
Steve Anton75737c02017-11-06 10:37:17 -08004470 return true;
4471}
4472
4473Call::Stats PeerConnection::GetCallStats() {
4474 if (!worker_thread()->IsCurrent()) {
4475 return worker_thread()->Invoke<Call::Stats>(
4476 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4477 }
4478 if (call_) {
4479 return call_->GetStats();
4480 } else {
4481 return Call::Stats();
4482 }
4483}
4484
4485std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4486 const ChannelNamePairs& channel_name_pairs) {
4487 RTC_DCHECK(network_thread()->IsCurrent());
4488 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4489 for (const auto channel_name_pair :
4490 {&channel_name_pairs.voice, &channel_name_pairs.video,
4491 &channel_name_pairs.data}) {
4492 if (*channel_name_pair) {
4493 cricket::TransportStats transport_stats;
4494 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4495 &transport_stats)) {
4496 return nullptr;
4497 }
4498 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4499 (*channel_name_pair)->transport_name;
4500 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4501 std::move(transport_stats);
4502 }
4503 }
4504 return session_stats;
4505}
4506
4507bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4508 const std::string& transport_name) {
4509 RTC_DCHECK(network_thread()->IsCurrent());
4510 RTC_DCHECK(sctp_factory_);
4511 cricket::DtlsTransportInternal* tc =
4512 transport_controller_->CreateDtlsTransport_n(
4513 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4514 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4515 RTC_DCHECK(sctp_transport_);
4516 sctp_invoker_.reset(new rtc::AsyncInvoker());
4517 sctp_transport_->SignalReadyToSendData.connect(
4518 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4519 sctp_transport_->SignalDataReceived.connect(
4520 this, &PeerConnection::OnSctpTransportDataReceived_n);
4521 sctp_transport_->SignalStreamClosedRemotely.connect(
4522 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004523 sctp_transport_name_ = transport_name;
4524 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004525 return true;
4526}
4527
4528void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4529 RTC_DCHECK(network_thread()->IsCurrent());
4530 RTC_DCHECK(sctp_transport_);
4531 RTC_DCHECK(sctp_transport_name_);
4532 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004533 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004534 cricket::DtlsTransportInternal* tc =
4535 transport_controller_->CreateDtlsTransport_n(
4536 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4537 sctp_transport_->SetTransportChannel(tc);
4538 transport_controller_->DestroyDtlsTransport_n(
4539 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4540}
4541
4542void PeerConnection::DestroySctpTransport_n() {
4543 RTC_DCHECK(network_thread()->IsCurrent());
4544 sctp_transport_.reset(nullptr);
4545 sctp_content_name_.reset();
4546 sctp_transport_name_.reset();
4547 sctp_invoker_.reset(nullptr);
4548 sctp_ready_to_send_data_ = false;
4549}
4550
4551void PeerConnection::OnSctpTransportReadyToSendData_n() {
4552 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4553 RTC_DCHECK(network_thread()->IsCurrent());
4554 // Note: Cannot use rtc::Bind here because it will grab a reference to
4555 // PeerConnection and potentially cause PeerConnection to live longer than
4556 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4557 // be destroyed before PeerConnection is destroyed, and at that point all
4558 // pending tasks will be cleared.
4559 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4560 OnSctpTransportReadyToSendData_s(true);
4561 });
4562}
4563
4564void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4565 RTC_DCHECK(signaling_thread()->IsCurrent());
4566 sctp_ready_to_send_data_ = ready;
4567 SignalSctpReadyToSendData(ready);
4568}
4569
4570void PeerConnection::OnSctpTransportDataReceived_n(
4571 const cricket::ReceiveDataParams& params,
4572 const rtc::CopyOnWriteBuffer& payload) {
4573 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4574 RTC_DCHECK(network_thread()->IsCurrent());
4575 // Note: Cannot use rtc::Bind here because it will grab a reference to
4576 // PeerConnection and potentially cause PeerConnection to live longer than
4577 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4578 // be destroyed before PeerConnection is destroyed, and at that point all
4579 // pending tasks will be cleared.
4580 sctp_invoker_->AsyncInvoke<void>(
4581 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4582 OnSctpTransportDataReceived_s(params, payload);
4583 });
4584}
4585
4586void PeerConnection::OnSctpTransportDataReceived_s(
4587 const cricket::ReceiveDataParams& params,
4588 const rtc::CopyOnWriteBuffer& payload) {
4589 RTC_DCHECK(signaling_thread()->IsCurrent());
4590 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4591 // Received OPEN message; parse and signal that a new data channel should
4592 // be created.
4593 std::string label;
4594 InternalDataChannelInit config;
4595 config.id = params.ssrc;
4596 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004597 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4598 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004599 return;
4600 }
4601 config.open_handshake_role = InternalDataChannelInit::kAcker;
4602 OnDataChannelOpenMessage(label, config);
4603 } else {
4604 // Otherwise just forward the signal.
4605 SignalSctpDataReceived(params, payload);
4606 }
4607}
4608
4609void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4610 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4611 RTC_DCHECK(network_thread()->IsCurrent());
4612 sctp_invoker_->AsyncInvoke<void>(
4613 RTC_FROM_HERE, signaling_thread(),
4614 rtc::Bind(&sigslot::signal1<int>::operator(),
4615 &SignalSctpStreamClosedRemotely, sid));
4616}
4617
4618// Returns false if bundle is enabled and rtcp_mux is disabled.
4619bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4620 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4621 if (!bundle_enabled)
4622 return true;
4623
4624 const cricket::ContentGroup* bundle_group =
4625 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4626 RTC_DCHECK(bundle_group != NULL);
4627
4628 const cricket::ContentInfos& contents = desc->contents();
4629 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4630 citer != contents.end(); ++citer) {
4631 const cricket::ContentInfo* content = (&*citer);
4632 RTC_DCHECK(content != NULL);
4633 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4634 content->type == cricket::NS_JINGLE_RTP) {
4635 if (!HasRtcpMuxEnabled(content))
4636 return false;
4637 }
4638 }
4639 // RTCP-MUX is enabled in all the contents.
4640 return true;
4641}
4642
4643bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4644 const cricket::MediaContentDescription* description =
4645 static_cast<cricket::MediaContentDescription*>(content->description);
4646 return description->rtcp_mux();
4647}
4648
4649bool PeerConnection::ValidateSessionDescription(
4650 const SessionDescriptionInterface* sdesc,
4651 cricket::ContentSource source,
4652 std::string* err_desc) {
4653 std::string type;
4654 if (error() != ERROR_NONE) {
4655 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4656 }
4657
4658 if (!sdesc || !sdesc->description()) {
4659 return BadSdp(source, type, kInvalidSdp, err_desc);
4660 }
4661
4662 type = sdesc->type();
4663 Action action = GetAction(sdesc->type());
4664 if (source == cricket::CS_LOCAL) {
4665 if (!ExpectSetLocalDescription(action))
4666 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4667 } else {
4668 if (!ExpectSetRemoteDescription(action))
4669 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4670 }
4671
4672 // Verify crypto settings.
4673 std::string crypto_error;
4674 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4675 dtls_enabled_) &&
4676 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4677 return BadSdp(source, type, crypto_error, err_desc);
4678 }
4679
4680 // Verify ice-ufrag and ice-pwd.
4681 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4682 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4683 }
4684
4685 if (!ValidateBundleSettings(sdesc->description())) {
4686 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4687 }
4688
4689 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4690 // m-lines that do not rtcp-mux enabled.
4691
4692 // Verify m-lines in Answer when compared against Offer.
4693 if (action == kAnswer || action == kPrAnswer) {
4694 const cricket::SessionDescription* offer_desc =
4695 (source == cricket::CS_LOCAL) ? remote_description()->description()
4696 : local_description()->description();
4697 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4698 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4699 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4700 }
4701 } else {
4702 const cricket::SessionDescription* current_desc = nullptr;
4703 if (source == cricket::CS_LOCAL && local_description()) {
4704 current_desc = local_description()->description();
4705 } else if (source == cricket::CS_REMOTE && remote_description()) {
4706 current_desc = remote_description()->description();
4707 }
4708 // The re-offers should respect the order of m= sections in current
4709 // description. See RFC3264 Section 8 paragraph 4 for more details.
4710 if (current_desc &&
4711 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4712 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4713 }
4714 }
4715
4716 return true;
4717}
4718
4719bool PeerConnection::ExpectSetLocalDescription(Action action) {
4720 PeerConnectionInterface::SignalingState state = signaling_state();
4721 if (action == kOffer) {
4722 return (state == PeerConnectionInterface::kStable) ||
4723 (state == PeerConnectionInterface::kHaveLocalOffer);
4724 } else { // Answer or PrAnswer
4725 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4726 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4727 }
4728}
4729
4730bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4731 PeerConnectionInterface::SignalingState state = signaling_state();
4732 if (action == kOffer) {
4733 return (state == PeerConnectionInterface::kStable) ||
4734 (state == PeerConnectionInterface::kHaveRemoteOffer);
4735 } else { // Answer or PrAnswer.
4736 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4737 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4738 }
4739}
4740
4741std::string PeerConnection::GetSessionErrorMsg() {
4742 std::ostringstream desc;
4743 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4744 desc << kSessionErrorDesc << error_desc() << ".";
4745 return desc.str();
4746}
4747
4748// We need to check the local/remote description for the Transport instead of
4749// the session, because a new Transport added during renegotiation may have
4750// them unset while the session has them set from the previous negotiation.
4751// Not doing so may trigger the auto generation of transport description and
4752// mess up DTLS identity information, ICE credential, etc.
4753bool PeerConnection::ReadyToUseRemoteCandidate(
4754 const IceCandidateInterface* candidate,
4755 const SessionDescriptionInterface* remote_desc,
4756 bool* valid) {
4757 *valid = true;
4758
4759 const SessionDescriptionInterface* current_remote_desc =
4760 remote_desc ? remote_desc : remote_description();
4761
4762 if (!current_remote_desc) {
4763 return false;
4764 }
4765
4766 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4767 size_t remote_content_size =
4768 current_remote_desc->description()->contents().size();
4769 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004770 RTC_LOG(LS_ERROR)
4771 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4772 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004773
4774 *valid = false;
4775 return false;
4776 }
4777
4778 cricket::ContentInfo content =
4779 current_remote_desc->description()->contents()[mediacontent_index];
4780
4781 const std::string transport_name = GetTransportName(content.name);
4782 if (transport_name.empty()) {
4783 return false;
4784 }
4785 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4786}
4787
4788bool PeerConnection::SrtpRequired() const {
4789 return dtls_enabled_ ||
4790 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4791}
4792
4793void PeerConnection::OnTransportControllerGatheringState(
4794 cricket::IceGatheringState state) {
4795 RTC_DCHECK(signaling_thread()->IsCurrent());
4796 if (state == cricket::kIceGatheringGathering) {
4797 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4798 } else if (state == cricket::kIceGatheringComplete) {
4799 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4800 }
4801}
4802
4803void PeerConnection::ReportTransportStats() {
4804 // Use a set so we don't report the same stats twice if two channels share
4805 // a transport.
4806 std::set<std::string> transport_names;
4807 if (voice_channel()) {
4808 transport_names.insert(voice_channel()->transport_name());
4809 }
4810 if (video_channel()) {
4811 transport_names.insert(video_channel()->transport_name());
4812 }
4813 if (rtp_data_channel()) {
4814 transport_names.insert(rtp_data_channel()->transport_name());
4815 }
4816 if (sctp_transport_name_) {
4817 transport_names.insert(*sctp_transport_name_);
4818 }
4819 for (const auto& name : transport_names) {
4820 cricket::TransportStats stats;
4821 if (transport_controller_->GetStats(name, &stats)) {
4822 ReportBestConnectionState(stats);
4823 ReportNegotiatedCiphers(stats);
4824 }
4825 }
4826}
4827// Walk through the ConnectionInfos to gather best connection usage
4828// for IPv4 and IPv6.
4829void PeerConnection::ReportBestConnectionState(
4830 const cricket::TransportStats& stats) {
4831 RTC_DCHECK(metrics_observer());
4832 for (cricket::TransportChannelStatsList::const_iterator it =
4833 stats.channel_stats.begin();
4834 it != stats.channel_stats.end(); ++it) {
4835 for (cricket::ConnectionInfos::const_iterator it_info =
4836 it->connection_infos.begin();
4837 it_info != it->connection_infos.end(); ++it_info) {
4838 if (!it_info->best_connection) {
4839 continue;
4840 }
4841
4842 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4843 const cricket::Candidate& local = it_info->local_candidate;
4844 const cricket::Candidate& remote = it_info->remote_candidate;
4845
4846 // Increment the counter for IceCandidatePairType.
4847 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4848 (local.type() == RELAY_PORT_TYPE &&
4849 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4850 type = kEnumCounterIceCandidatePairTypeTcp;
4851 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4852 type = kEnumCounterIceCandidatePairTypeUdp;
4853 } else {
4854 RTC_CHECK(0);
4855 }
4856 metrics_observer()->IncrementEnumCounter(
4857 type, GetIceCandidatePairCounter(local, remote),
4858 kIceCandidatePairMax);
4859
4860 // Increment the counter for IP type.
4861 if (local.address().family() == AF_INET) {
4862 metrics_observer()->IncrementEnumCounter(
4863 kEnumCounterAddressFamily, kBestConnections_IPv4,
4864 kPeerConnectionAddressFamilyCounter_Max);
4865
4866 } else if (local.address().family() == AF_INET6) {
4867 metrics_observer()->IncrementEnumCounter(
4868 kEnumCounterAddressFamily, kBestConnections_IPv6,
4869 kPeerConnectionAddressFamilyCounter_Max);
4870 } else {
4871 RTC_CHECK(0);
4872 }
4873
4874 return;
4875 }
4876 }
4877}
4878
4879void PeerConnection::ReportNegotiatedCiphers(
4880 const cricket::TransportStats& stats) {
4881 RTC_DCHECK(metrics_observer());
4882 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4883 return;
4884 }
4885
4886 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4887 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4888 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4889 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4890 return;
4891 }
4892
4893 PeerConnectionEnumCounterType srtp_counter_type;
4894 PeerConnectionEnumCounterType ssl_counter_type;
4895 if (stats.transport_name == cricket::CN_AUDIO) {
4896 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4897 ssl_counter_type = kEnumCounterAudioSslCipher;
4898 } else if (stats.transport_name == cricket::CN_VIDEO) {
4899 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4900 ssl_counter_type = kEnumCounterVideoSslCipher;
4901 } else if (stats.transport_name == cricket::CN_DATA) {
4902 srtp_counter_type = kEnumCounterDataSrtpCipher;
4903 ssl_counter_type = kEnumCounterDataSslCipher;
4904 } else {
4905 RTC_NOTREACHED();
4906 return;
4907 }
4908
4909 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4910 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4911 srtp_crypto_suite);
4912 }
4913 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4914 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4915 ssl_cipher_suite);
4916 }
4917}
4918
4919void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4920 RTC_DCHECK(worker_thread()->IsCurrent());
4921 RTC_DCHECK(call_);
4922 call_->OnSentPacket(sent_packet);
4923}
4924
4925const std::string PeerConnection::GetTransportName(
4926 const std::string& content_name) {
4927 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004928 if (channel) {
4929 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004930 }
Steve Anton6fec8802017-12-04 10:37:29 -08004931 if (sctp_transport_) {
4932 RTC_DCHECK(sctp_content_name_);
4933 RTC_DCHECK(sctp_transport_name_);
4934 if (content_name == *sctp_content_name_) {
4935 return *sctp_transport_name_;
4936 }
4937 }
4938 // Return an empty string if failed to retrieve the transport name.
4939 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004940}
4941
4942void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4943 RTC_DCHECK(network_thread()->IsCurrent());
4944 transport_controller_->DestroyDtlsTransport_n(
4945 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4946}
4947
Steve Anton6fec8802017-12-04 10:37:29 -08004948void PeerConnection::DestroyTransceiverChannel(
4949 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4950 transceiver) {
4951 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004952
Steve Anton6fec8802017-12-04 10:37:29 -08004953 cricket::BaseChannel* channel = transceiver->internal()->channel();
4954 if (channel) {
4955 transceiver->internal()->SetChannel(nullptr);
4956 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004957 }
4958}
4959
4960void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004961 if (rtp_data_channel_) {
4962 OnDataChannelDestroyed();
4963 DestroyBaseChannel(rtp_data_channel_);
4964 rtp_data_channel_ = nullptr;
4965 }
4966
4967 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4968 // grab a reference to this PeerConnection. If this is called from the
4969 // PeerConnection destructor, the RefCountedObject vtable will have already
4970 // been destroyed (since it is a subclass of PeerConnection) and using
4971 // rtc::Bind will cause "Pure virtual function called" error to appear.
4972
4973 if (sctp_transport_) {
4974 OnDataChannelDestroyed();
4975 network_thread()->Invoke<void>(RTC_FROM_HERE,
4976 [this] { DestroySctpTransport_n(); });
4977 }
4978}
4979
4980void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4981 RTC_DCHECK(channel);
4982 RTC_DCHECK(channel->rtp_dtls_transport());
4983
4984 // Need to cache these before destroying the base channel so that we do not
4985 // access uninitialized memory.
4986 const std::string transport_name =
4987 channel->rtp_dtls_transport()->transport_name();
4988 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4989
4990 switch (channel->media_type()) {
4991 case cricket::MEDIA_TYPE_AUDIO:
4992 channel_manager()->DestroyVoiceChannel(
4993 static_cast<cricket::VoiceChannel*>(channel));
4994 break;
4995 case cricket::MEDIA_TYPE_VIDEO:
4996 channel_manager()->DestroyVideoChannel(
4997 static_cast<cricket::VideoChannel*>(channel));
4998 break;
4999 case cricket::MEDIA_TYPE_DATA:
5000 channel_manager()->DestroyRtpDataChannel(
5001 static_cast<cricket::RtpDataChannel*>(channel));
5002 break;
5003 default:
5004 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5005 break;
5006 }
5007
5008 // |channel| can no longer be used.
5009
Steve Anton75737c02017-11-06 10:37:17 -08005010 transport_controller_->DestroyDtlsTransport(
5011 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5012 if (need_to_delete_rtcp) {
5013 transport_controller_->DestroyDtlsTransport(
5014 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5015 }
5016}
5017
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005018} // namespace webrtc