blob: 8efdf04d29206f538ca397ca125ba95d2b0c0844 [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
Steve Anton75737c02017-11-06 10:37:17 -0800579std::string MakeErrorString(const std::string& error, const std::string& desc) {
580 std::ostringstream ret;
581 ret << error << " " << desc;
582 return ret.str();
583}
584
585std::string MakeTdErrorString(const std::string& desc) {
586 return MakeErrorString(kPushDownTDFailed, desc);
587}
588
589// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
590bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
591 const SessionDescriptionInterface* new_desc,
592 const std::string& content_name) {
593 if (!old_desc) {
594 return false;
595 }
596 const SessionDescription* new_sd = new_desc->description();
597 const SessionDescription* old_sd = old_desc->description();
598 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
599 if (!cinfo || cinfo->rejected) {
600 return false;
601 }
602 // If the content isn't rejected, check if ufrag and password has changed.
603 const cricket::TransportDescription* new_transport_desc =
604 new_sd->GetTransportDescriptionByName(content_name);
605 const cricket::TransportDescription* old_transport_desc =
606 old_sd->GetTransportDescriptionByName(content_name);
607 if (!new_transport_desc || !old_transport_desc) {
608 // No transport description exists. This is not an ICE restart.
609 return false;
610 }
611 if (cricket::IceCredentialsChanged(
612 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
613 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100614 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
615 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800616 return true;
617 }
618 return false;
619}
620
621} // namespace
622
Henrik Boström31638672017-11-23 17:48:32 +0100623// Upon completion, posts a task to execute the callback of the
624// SetSessionDescriptionObserver asynchronously on the same thread. At this
625// point, the state of the peer connection might no longer reflect the effects
626// of the SetRemoteDescription operation, as the peer connection could have been
627// modified during the post.
628// TODO(hbos): Remove this class once we remove the version of
629// PeerConnectionInterface::SetRemoteDescription() that takes a
630// SetSessionDescriptionObserver as an argument.
631class PeerConnection::SetRemoteDescriptionObserverAdapter
632 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
633 public:
634 SetRemoteDescriptionObserverAdapter(
635 rtc::scoped_refptr<PeerConnection> pc,
636 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
637 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
638
639 // SetRemoteDescriptionObserverInterface implementation.
640 void OnSetRemoteDescriptionComplete(RTCError error) override {
641 if (error.ok())
642 pc_->PostSetSessionDescriptionSuccess(wrapper_);
643 else
644 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
645 }
646
647 private:
648 rtc::scoped_refptr<PeerConnection> pc_;
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
650};
651
deadbeef293e9262017-01-11 12:28:30 -0800652bool PeerConnectionInterface::RTCConfiguration::operator==(
653 const PeerConnectionInterface::RTCConfiguration& o) const {
654 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700655 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800656 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000657 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800659 BundlePolicy bundle_policy;
660 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
662 int ice_candidate_pool_size;
663 bool disable_ipv6;
664 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700665 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700666 bool enable_rtp_data_channel;
667 rtc::Optional<int> screencast_min_bitrate;
668 rtc::Optional<bool> combined_audio_video_bwe;
669 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800670 TcpCandidatePolicy tcp_candidate_policy;
671 CandidateNetworkPolicy candidate_network_policy;
672 int audio_jitter_buffer_max_packets;
673 bool audio_jitter_buffer_fast_accelerate;
674 int ice_connection_receiving_timeout;
675 int ice_backup_candidate_pair_ping_interval;
676 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800677 bool prioritize_most_likely_ice_candidate_pairs;
678 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800679 bool prune_turn_ports;
680 bool presume_writable_when_fully_relayed;
681 bool enable_ice_renomination;
682 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800683 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700684 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200685 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800686 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800687 };
688 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
689 "Did you add something to RTCConfiguration and forget to "
690 "update operator==?");
691 return type == o.type && servers == o.servers &&
692 bundle_policy == o.bundle_policy &&
693 rtcp_mux_policy == o.rtcp_mux_policy &&
694 tcp_candidate_policy == o.tcp_candidate_policy &&
695 candidate_network_policy == o.candidate_network_policy &&
696 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
697 audio_jitter_buffer_fast_accelerate ==
698 o.audio_jitter_buffer_fast_accelerate &&
699 ice_connection_receiving_timeout ==
700 o.ice_connection_receiving_timeout &&
701 ice_backup_candidate_pair_ping_interval ==
702 o.ice_backup_candidate_pair_ping_interval &&
703 continual_gathering_policy == o.continual_gathering_policy &&
704 certificates == o.certificates &&
705 prioritize_most_likely_ice_candidate_pairs ==
706 o.prioritize_most_likely_ice_candidate_pairs &&
707 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800708 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700709 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800710 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800711 screencast_min_bitrate == o.screencast_min_bitrate &&
712 combined_audio_video_bwe == o.combined_audio_video_bwe &&
713 enable_dtls_srtp == o.enable_dtls_srtp &&
714 ice_candidate_pool_size == o.ice_candidate_pool_size &&
715 prune_turn_ports == o.prune_turn_ports &&
716 presume_writable_when_fully_relayed ==
717 o.presume_writable_when_fully_relayed &&
718 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800719 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700720 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200721 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800722 turn_customizer == o.turn_customizer &&
723 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800724}
725
726bool PeerConnectionInterface::RTCConfiguration::operator!=(
727 const PeerConnectionInterface::RTCConfiguration& o) const {
728 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800729}
730
zhihuang8f65cdf2016-05-06 18:40:30 -0700731// Generate a RTCP CNAME when a PeerConnection is created.
732std::string GenerateRtcpCname() {
733 std::string cname;
734 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100735 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800736 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700737 }
738 return cname;
739}
740
zhihuang1c378ed2017-08-17 14:10:50 -0700741bool ValidateOfferAnswerOptions(
742 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
743 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
744 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700745}
746
zhihuang1c378ed2017-08-17 14:10:50 -0700747// From |rtc_options|, fill parts of |session_options| shared by all generated
748// m= sections (in other words, nothing that involves a map/array).
749void ExtractSharedMediaSessionOptions(
750 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
751 cricket::MediaSessionOptions* session_options) {
752 session_options->vad_enabled = rtc_options.voice_activity_detection;
753 session_options->bundle_enabled = rtc_options.use_rtp_mux;
754}
zhihuanga77e6bb2017-08-14 18:17:48 -0700755
zhihuang1c378ed2017-08-17 14:10:50 -0700756bool ConvertConstraintsToOfferAnswerOptions(
757 const MediaConstraintsInterface* constraints,
758 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700759 if (!constraints) {
760 return true;
761 }
zhihuang1c378ed2017-08-17 14:10:50 -0700762
763 bool value = false;
764 size_t mandatory_constraints_satisfied = 0;
765
766 if (FindConstraint(constraints,
767 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
768 &mandatory_constraints_satisfied)) {
769 offer_answer_options->offer_to_receive_audio =
770 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
771 kOfferToReceiveMediaTrue
772 : 0;
773 }
774
775 if (FindConstraint(constraints,
776 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
777 &mandatory_constraints_satisfied)) {
778 offer_answer_options->offer_to_receive_video =
779 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
780 kOfferToReceiveMediaTrue
781 : 0;
782 }
783 if (FindConstraint(constraints,
784 MediaConstraintsInterface::kVoiceActivityDetection, &value,
785 &mandatory_constraints_satisfied)) {
786 offer_answer_options->voice_activity_detection = value;
787 }
788 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
789 &mandatory_constraints_satisfied)) {
790 offer_answer_options->use_rtp_mux = value;
791 }
792 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
793 &value, &mandatory_constraints_satisfied)) {
794 offer_answer_options->ice_restart = value;
795 }
796
deadbeefab9b2d12015-10-14 11:33:11 -0700797 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
798}
799
zhihuang38ede132017-06-15 12:52:32 -0700800PeerConnection::PeerConnection(PeerConnectionFactory* factory,
801 std::unique_ptr<RtcEventLog> event_log,
802 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000803 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700804 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700805 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700806 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700807 remote_streams_(StreamCollection::Create()),
808 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809
810PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100811 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800812 RTC_DCHECK_RUN_ON(signaling_thread());
813
814 // Need to detach RTP transceivers from PeerConnection, since it's about to be
815 // destroyed.
816 for (auto transceiver : transceivers_) {
817 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700818 }
Steve Anton4171afb2017-11-20 10:20:22 -0800819
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700820 // Destroy stats_ because it depends on session_.
821 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800822 if (stats_collector_) {
823 stats_collector_->WaitForPendingRequest();
824 stats_collector_ = nullptr;
825 }
Steve Anton75737c02017-11-06 10:37:17 -0800826
827 // Destroy video channels first since they may have a pointer to a voice
828 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800829 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800830 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
831 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800832 }
Steve Anton75737c02017-11-06 10:37:17 -0800833 }
Steve Anton4171afb2017-11-20 10:20:22 -0800834 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800835 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
836 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800837 }
Steve Anton75737c02017-11-06 10:37:17 -0800838 }
Steve Anton6fec8802017-12-04 10:37:29 -0800839 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -0800840
Mirko Bonadei675513b2017-11-09 11:09:25 +0100841 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800842
843 webrtc_session_desc_factory_.reset();
844 sctp_invoker_.reset();
845 sctp_factory_.reset();
846 transport_controller_.reset();
847
deadbeef91dd5672016-05-18 16:55:30 -0700848 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700849 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700850 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700851 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700852 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700853 call_.reset();
854 event_log_.reset();
855 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000856}
857
858bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000859 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700860 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200861 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800862 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100863 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700864
865 RTCError config_error = ValidateConfiguration(configuration);
866 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700868 return false;
869 }
870
deadbeef293e9262017-01-11 12:28:30 -0800871 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_ERROR)
873 << "PeerConnection initialized without a PortAllocator? "
874 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800875 return false;
876 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200877
deadbeef653b8e02015-11-11 12:55:10 -0800878 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800879 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
881 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800882 return false;
883 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000884 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800885 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800886
deadbeef91dd5672016-05-18 16:55:30 -0700887 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700888 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700889 if (!network_thread()->Invoke<bool>(
890 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
891 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892 return false;
893 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894
Steve Anton75737c02017-11-06 10:37:17 -0800895 // RFC 3264: The numeric value of the session id and version in the
896 // o line MUST be representable with a "64 bit signed integer".
897 // Due to this constraint session id |session_id_| is max limited to
898 // LLONG_MAX.
899 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
900 transport_controller_.reset(factory_->CreateTransportController(
901 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
902 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
903 transport_controller_->SignalConnectionState.connect(
904 this, &PeerConnection::OnTransportControllerConnectionState);
905 transport_controller_->SignalGatheringState.connect(
906 this, &PeerConnection::OnTransportControllerGatheringState);
907 transport_controller_->SignalCandidatesGathered.connect(
908 this, &PeerConnection::OnTransportControllerCandidatesGathered);
909 transport_controller_->SignalCandidatesRemoved.connect(
910 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
911 transport_controller_->SignalDtlsHandshakeError.connect(
912 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
913
914 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700915
deadbeefab9b2d12015-10-14 11:33:11 -0700916 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700917 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918
Steve Antonba818672017-11-06 10:21:57 -0800919 configuration_ = configuration;
920
Steve Anton75737c02017-11-06 10:37:17 -0800921 const PeerConnectionFactoryInterface::Options& options = factory_->options();
922
923 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
924
925 // Obtain a certificate from RTCConfiguration if any were provided (optional).
926 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
927 if (!configuration.certificates.empty()) {
928 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
929 // just picking the first one. The decision should be made based on the DTLS
930 // handshake. The DTLS negotiations need to know about all certificates.
931 certificate = configuration.certificates[0];
932 }
933
Steve Antond25da372017-11-06 14:50:29 -0800934 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800935
936 if (options.disable_encryption) {
937 dtls_enabled_ = false;
938 } else {
939 // Enable DTLS by default if we have an identity store or a certificate.
940 dtls_enabled_ = (cert_generator || certificate);
941 // |configuration| can override the default |dtls_enabled_| value.
942 if (configuration.enable_dtls_srtp) {
943 dtls_enabled_ = *(configuration.enable_dtls_srtp);
944 }
945 }
946
947 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
948 // It takes precendence over the disable_sctp_data_channels
949 // PeerConnectionFactoryInterface::Options.
950 if (configuration.enable_rtp_data_channel) {
951 data_channel_type_ = cricket::DCT_RTP;
952 } else {
953 // DTLS has to be enabled to use SCTP.
954 if (!options.disable_sctp_data_channels && dtls_enabled_) {
955 data_channel_type_ = cricket::DCT_SCTP;
956 }
957 }
958
959 video_options_.screencast_min_bitrate_kbps =
960 configuration.screencast_min_bitrate;
961 audio_options_.combined_audio_video_bwe =
962 configuration.combined_audio_video_bwe;
963
964 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100965 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800966
967 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100968 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800969
970 // Whether the certificate generator/certificate is null or not determines
971 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
972 // the right instructions by clearing the variables if needed.
973 if (!dtls_enabled_) {
974 cert_generator.reset();
975 certificate = nullptr;
976 } else if (certificate) {
977 // Favor generated certificate over the certificate generator.
978 cert_generator.reset();
979 }
980
981 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
982 signaling_thread(), channel_manager(), this, session_id(),
983 std::move(cert_generator), certificate));
984 webrtc_session_desc_factory_->SignalCertificateReady.connect(
985 this, &PeerConnection::OnCertificateReady);
986
987 if (options.disable_encryption) {
988 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
989 }
990
991 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
992 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993
Steve Anton4171afb2017-11-20 10:20:22 -0800994 // Add default audio/video transceivers for Plan B SDP.
995 if (!IsUnifiedPlan()) {
996 transceivers_.push_back(
997 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
998 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
999 transceivers_.push_back(
1000 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1001 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1002 }
1003
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004 return true;
1005}
1006
Steve Anton038834f2017-07-14 15:59:59 -07001007RTCError PeerConnection::ValidateConfiguration(
1008 const RTCConfiguration& config) const {
1009 if (config.ice_regather_interval_range &&
1010 config.continual_gathering_policy == GATHER_ONCE) {
1011 return RTCError(RTCErrorType::INVALID_PARAMETER,
1012 "ice_regather_interval_range specified but continual "
1013 "gathering policy is GATHER_ONCE");
1014 }
1015 return RTCError::OK();
1016}
1017
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001018rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001020 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021}
1022
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001023rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001025 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026}
1027
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001028bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001029 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 if (IsClosed()) {
1031 return false;
1032 }
deadbeefab9b2d12015-10-14 11:33:11 -07001033 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 return false;
1035 }
deadbeefab9b2d12015-10-14 11:33:11 -07001036
1037 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001038 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1039 observer->SignalAudioTrackAdded.connect(this,
1040 &PeerConnection::OnAudioTrackAdded);
1041 observer->SignalAudioTrackRemoved.connect(
1042 this, &PeerConnection::OnAudioTrackRemoved);
1043 observer->SignalVideoTrackAdded.connect(this,
1044 &PeerConnection::OnVideoTrackAdded);
1045 observer->SignalVideoTrackRemoved.connect(
1046 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001047 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001048
deadbeefab9b2d12015-10-14 11:33:11 -07001049 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001050 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001051 }
1052 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001053 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001054 }
1055
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001056 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057 observer_->OnRenegotiationNeeded();
1058 return true;
1059}
1060
1061void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001062 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001063 if (!IsClosed()) {
1064 for (const auto& track : local_stream->GetAudioTracks()) {
1065 RemoveAudioTrack(track.get(), local_stream);
1066 }
1067 for (const auto& track : local_stream->GetVideoTracks()) {
1068 RemoveVideoTrack(track.get(), local_stream);
1069 }
deadbeefab9b2d12015-10-14 11:33:11 -07001070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001072 stream_observers_.erase(
1073 std::remove_if(
1074 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001075 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001076 return observer->stream()->label().compare(local_stream->label()) ==
1077 0;
1078 }),
1079 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001080
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 if (IsClosed()) {
1082 return;
1083 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001084 observer_->OnRenegotiationNeeded();
1085}
1086
deadbeefe1f9d832016-01-14 15:35:42 -08001087rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1088 MediaStreamTrackInterface* track,
1089 std::vector<MediaStreamInterface*> streams) {
1090 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1091 if (IsClosed()) {
1092 return nullptr;
1093 }
1094 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001095 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001096 << "Adding a track with two streams is not currently supported.";
1097 return nullptr;
1098 }
Steve Anton4171afb2017-11-20 10:20:22 -08001099 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001100 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1101 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001102 return nullptr;
1103 }
1104
1105 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001106 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001107 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001108 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001109 signaling_thread(),
1110 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001111 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001112 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001113 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001114 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001115 }
Steve Anton4171afb2017-11-20 10:20:22 -08001116 const RtpSenderInfo* sender_info =
1117 FindSenderInfo(local_audio_sender_infos_,
1118 new_sender->internal()->stream_id(), track->id());
1119 if (sender_info) {
1120 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001121 }
1122 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001123 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001124 signaling_thread(),
1125 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001126 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001127 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001128 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001129 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001130 }
Steve Anton4171afb2017-11-20 10:20:22 -08001131 const RtpSenderInfo* sender_info =
1132 FindSenderInfo(local_video_sender_infos_,
1133 new_sender->internal()->stream_id(), track->id());
1134 if (sender_info) {
1135 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001136 }
1137 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001138 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1139 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001140 return rtc::scoped_refptr<RtpSenderInterface>();
1141 }
1142
deadbeefe1f9d832016-01-14 15:35:42 -08001143 observer_->OnRenegotiationNeeded();
1144 return new_sender;
1145}
1146
1147bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1148 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1149 if (IsClosed()) {
1150 return false;
1151 }
1152
Steve Anton4171afb2017-11-20 10:20:22 -08001153 bool removed;
1154 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1155 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1156 } else {
1157 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1158 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1159 }
1160 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001161 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1162 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001163 return false;
1164 }
deadbeefe1f9d832016-01-14 15:35:42 -08001165
1166 observer_->OnRenegotiationNeeded();
1167 return true;
1168}
1169
Steve Anton9158ef62017-11-27 13:01:52 -08001170RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1171PeerConnection::AddTransceiver(
1172 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1173 return AddTransceiver(track, RtpTransceiverInit());
1174}
1175
1176RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1177PeerConnection::AddTransceiver(
1178 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1179 const RtpTransceiverInit& init) {
1180 if (!IsUnifiedPlan()) {
1181 LOG_AND_RETURN_ERROR(
1182 RTCErrorType::INTERNAL_ERROR,
1183 "AddTransceiver only supported when Unified Plan is enabled.");
1184 }
1185 if (!track) {
1186 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1187 }
1188 cricket::MediaType media_type;
1189 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1190 media_type = cricket::MEDIA_TYPE_AUDIO;
1191 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1192 media_type = cricket::MEDIA_TYPE_VIDEO;
1193 } else {
1194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1195 "Track kind is not audio or video");
1196 }
1197 return AddTransceiver(media_type, track, init);
1198}
1199
1200RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1201PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1202 return AddTransceiver(media_type, RtpTransceiverInit());
1203}
1204
1205RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1206PeerConnection::AddTransceiver(cricket::MediaType media_type,
1207 const RtpTransceiverInit& init) {
1208 if (!IsUnifiedPlan()) {
1209 LOG_AND_RETURN_ERROR(
1210 RTCErrorType::INTERNAL_ERROR,
1211 "AddTransceiver only supported when Unified Plan is enabled.");
1212 }
1213 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1214 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1216 "media type is not audio or video");
1217 }
1218 return AddTransceiver(media_type, nullptr, init);
1219}
1220
1221RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1222PeerConnection::AddTransceiver(
1223 cricket::MediaType media_type,
1224 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1225 const RtpTransceiverInit& init) {
1226 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1227 media_type == cricket::MEDIA_TYPE_VIDEO));
1228 if (track) {
1229 RTC_DCHECK_EQ(media_type,
1230 (track->kind() == MediaStreamTrackInterface::kAudioKind
1231 ? cricket::MEDIA_TYPE_AUDIO
1232 : cricket::MEDIA_TYPE_VIDEO));
1233 }
1234
1235 // TODO(bugs.webrtc.org/7600): Verify init.
1236
1237 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1238 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1239 receiver;
1240 std::string receiver_id = rtc::CreateRandomUuid();
1241 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1242 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1243 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1244 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1245 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1246 } else {
1247 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1248 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1249 signaling_thread(), new VideoRtpSender(nullptr));
1250 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1251 signaling_thread(),
1252 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1253 }
1254 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1255 // channel prevents users from calling SetParameters on them, which is needed
1256 // to be in compliance with the spec.
1257
1258 if (track) {
1259 sender->SetTrack(track);
1260 }
1261
1262 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1263 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1264 signaling_thread(), new RtpTransceiver(sender, receiver));
1265 transceiver->SetDirection(init.direction);
1266
1267 transceivers_.push_back(transceiver);
1268
1269 observer_->OnRenegotiationNeeded();
1270
1271 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1272}
1273
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001274rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001276 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001277 if (IsClosed()) {
1278 return nullptr;
1279 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001281 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001282 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 }
Steve Anton4171afb2017-11-20 10:20:22 -08001284 auto track_sender = FindSenderForTrack(track);
1285 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001286 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001287 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001288 }
1289
Steve Anton4171afb2017-11-20 10:20:22 -08001290 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291}
1292
deadbeeffac06552015-11-25 11:26:01 -08001293rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001294 const std::string& kind,
1295 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001296 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001297 if (IsClosed()) {
1298 return nullptr;
1299 }
Steve Anton4171afb2017-11-20 10:20:22 -08001300
1301 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001302 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001303 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001304 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001305 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001306 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001307 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001308 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001309 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001310 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001311 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001312 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001313 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001314 }
Steve Anton4171afb2017-11-20 10:20:22 -08001315
deadbeefbd7d8f72015-12-18 16:58:44 -08001316 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001317 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001318 }
Steve Anton4171afb2017-11-20 10:20:22 -08001319
deadbeefe1f9d832016-01-14 15:35:42 -08001320 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001321}
1322
deadbeef70ab1a12015-09-28 16:53:55 -07001323std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1324 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001325 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001326 for (auto sender : GetSendersInternal()) {
1327 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001328 }
1329 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001330}
1331
Steve Anton4171afb2017-11-20 10:20:22 -08001332std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1333PeerConnection::GetSendersInternal() const {
1334 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1335 all_senders;
1336 for (auto transceiver : transceivers_) {
1337 auto senders = transceiver->internal()->senders();
1338 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1339 }
1340 return all_senders;
1341}
1342
deadbeef70ab1a12015-09-28 16:53:55 -07001343std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1344PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001345 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001346 for (const auto& receiver : GetReceiversInternal()) {
1347 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001348 }
1349 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001350}
1351
Steve Anton4171afb2017-11-20 10:20:22 -08001352std::vector<
1353 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1354PeerConnection::GetReceiversInternal() const {
1355 std::vector<
1356 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1357 all_receivers;
1358 for (auto transceiver : transceivers_) {
1359 auto receivers = transceiver->internal()->receivers();
1360 all_receivers.insert(all_receivers.end(), receivers.begin(),
1361 receivers.end());
1362 }
1363 return all_receivers;
1364}
1365
Steve Anton9158ef62017-11-27 13:01:52 -08001366std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1367PeerConnection::GetTransceivers() const {
1368 RTC_DCHECK(IsUnifiedPlan());
1369 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1370 for (auto transceiver : transceivers_) {
1371 all_transceivers.push_back(transceiver);
1372 }
1373 return all_transceivers;
1374}
1375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001377 MediaStreamTrackInterface* track,
1378 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001379 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001380 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001381 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001382 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383 return false;
1384 }
1385
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001386 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001387 // The StatsCollector is used to tell if a track is valid because it may
1388 // remember tracks that the PeerConnection previously removed.
1389 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001390 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1391 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001392 return false;
1393 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001394 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001395 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 return true;
1397}
1398
hbos74e1a4f2016-09-15 23:33:01 -07001399void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1400 RTC_DCHECK(stats_collector_);
1401 stats_collector_->GetStatsReport(callback);
1402}
1403
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1405 return signaling_state_;
1406}
1407
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408PeerConnectionInterface::IceConnectionState
1409PeerConnection::ice_connection_state() {
1410 return ice_connection_state_;
1411}
1412
1413PeerConnectionInterface::IceGatheringState
1414PeerConnection::ice_gathering_state() {
1415 return ice_gathering_state_;
1416}
1417
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001418rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419PeerConnection::CreateDataChannel(
1420 const std::string& label,
1421 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001422 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001423
deadbeefab9b2d12015-10-14 11:33:11 -07001424 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001425
kwibergd1fe2812016-04-27 06:47:29 -07001426 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001427 if (config) {
1428 internal_config.reset(new InternalDataChannelInit(*config));
1429 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001430 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001431 InternalCreateDataChannel(label, internal_config.get()));
1432 if (!channel.get()) {
1433 return nullptr;
1434 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001436 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1437 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001438 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001439 observer_->OnRenegotiationNeeded();
1440 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 return DataChannelProxy::Create(signaling_thread(), channel.get());
1443}
1444
1445void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1446 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001447 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001448
zhihuang1c378ed2017-08-17 14:10:50 -07001449 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1450 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1451 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1452 // compares the mandatory fields parsed with the mandatory fields added in the
1453 // |constraints| and some downstream applications might create offers with
1454 // mandatory fields which would not be parsed in the helper method. For
1455 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1456 // |constraints| as a mandatory field but it is not parsed.
1457 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001458
zhihuang1c378ed2017-08-17 14:10:50 -07001459 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001460}
1461
1462void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1463 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001464 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001465
nisse7ce109a2017-01-31 00:57:56 -08001466 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001467 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001468 return;
1469 }
deadbeefab9b2d12015-10-14 11:33:11 -07001470
Steve Anton8d3444d2017-10-20 15:30:51 -07001471 if (IsClosed()) {
1472 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001473 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001474 PostCreateSessionDescriptionFailure(observer, error);
1475 return;
1476 }
1477
zhihuang1c378ed2017-08-17 14:10:50 -07001478 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001479 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001481 PostCreateSessionDescriptionFailure(observer, error);
1482 return;
1483 }
1484
zhihuang1c378ed2017-08-17 14:10:50 -07001485 cricket::MediaSessionOptions session_options;
1486 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001487 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488}
1489
1490void PeerConnection::CreateAnswer(
1491 CreateSessionDescriptionObserver* observer,
1492 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001493 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001494
nisse7ce109a2017-01-31 00:57:56 -08001495 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001496 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497 return;
1498 }
deadbeefab9b2d12015-10-14 11:33:11 -07001499
zhihuang1c378ed2017-08-17 14:10:50 -07001500 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1501 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1502 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001503 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001505 PostCreateSessionDescriptionFailure(observer, error);
1506 return;
1507 }
1508
Steve Anton8d3444d2017-10-20 15:30:51 -07001509 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001510}
1511
1512void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1513 const RTCOfferAnswerOptions& options) {
1514 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001515 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001516 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001517 return;
1518 }
1519
Steve Anton8d3444d2017-10-20 15:30:51 -07001520 if (IsClosed()) {
1521 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001522 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001523 PostCreateSessionDescriptionFailure(observer, error);
1524 return;
1525 }
1526
Steve Anton75737c02017-11-06 10:37:17 -08001527 if (remote_description() &&
1528 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001529 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001530 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001531 PostCreateSessionDescriptionFailure(observer, error);
1532 return;
1533 }
1534
htaa2a49d92016-03-04 02:51:39 -08001535 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001536 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001537
Steve Antond25da372017-11-06 14:50:29 -08001538 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001539}
1540
1541void PeerConnection::SetLocalDescription(
1542 SetSessionDescriptionObserver* observer,
1543 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001544 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001545 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001546 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 return;
1548 }
1549 if (!desc) {
1550 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1551 return;
1552 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001553
1554 // Takes the ownership of |desc| regardless of the result.
1555 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1556
1557 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001558 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001560 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001561 PostSetSessionDescriptionFailure(observer, error);
1562 return;
1563 }
1564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 // Update stats here so that we have the most recent stats for tracks and
1566 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001567 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001569 // Takes the ownership of |desc_temp|. On success, local_description() is
1570 // updated to reflect the description that was passed in.
Henrik Boström31638672017-11-23 17:48:32 +01001571 if (!SetCurrentOrPendingLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572 PostSetSessionDescriptionFailure(observer, error);
1573 return;
1574 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001575 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001576
1577 // If setting the description decided our SSL role, allocate any necessary
1578 // SCTP sids.
1579 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001580 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001581 AllocateSctpSids(role);
1582 }
1583
1584 // Update state and SSRC of local MediaStreams and DataChannels based on the
1585 // local session description.
1586 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001587 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001588 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001589 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001590 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001591 } else {
1592 const cricket::AudioContentDescription* audio_desc =
1593 static_cast<const cricket::AudioContentDescription*>(
1594 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001595 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001596 }
deadbeefab9b2d12015-10-14 11:33:11 -07001597 }
1598
1599 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001600 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001601 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001602 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001603 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001604 } else {
1605 const cricket::VideoContentDescription* video_desc =
1606 static_cast<const cricket::VideoContentDescription*>(
1607 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001608 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001609 }
deadbeefab9b2d12015-10-14 11:33:11 -07001610 }
1611
1612 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001613 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001614 if (data_content) {
1615 const cricket::DataContentDescription* data_desc =
1616 static_cast<const cricket::DataContentDescription*>(
1617 data_content->description);
1618 if (rtc::starts_with(data_desc->protocol().data(),
1619 cricket::kMediaProtocolRtpPrefix)) {
1620 UpdateLocalRtpDataChannels(data_desc->streams());
1621 }
1622 }
1623
Henrik Boström31638672017-11-23 17:48:32 +01001624 PostSetSessionDescriptionSuccess(observer);
deadbeefab9b2d12015-10-14 11:33:11 -07001625
deadbeef42a42632017-03-10 15:18:00 -08001626 // According to JSEP, after setLocalDescription, changing the candidate pool
1627 // size is not allowed, and changing the set of ICE servers will not result
1628 // in new candidates being gathered.
1629 port_allocator_->FreezeCandidatePool();
1630
deadbeefcbecd352015-09-23 11:50:27 -07001631 // MaybeStartGathering needs to be called after posting
1632 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1633 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001634 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001635
Henrik Boströmfdb92012017-11-09 19:55:44 +01001636 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001637 // TODO(deadbeef): We already had to hop to the network thread for
1638 // MaybeStartGathering...
1639 network_thread()->Invoke<void>(
1640 RTC_FROM_HERE,
1641 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1642 port_allocator_.get()));
1643 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001644}
1645
1646void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001647 SetSessionDescriptionObserver* observer,
1648 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001649 SetRemoteDescription(
1650 std::unique_ptr<SessionDescriptionInterface>(desc),
1651 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1652 new SetRemoteDescriptionObserverAdapter(this, observer)));
1653}
1654
1655void PeerConnection::SetRemoteDescription(
1656 std::unique_ptr<SessionDescriptionInterface> desc,
1657 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001658 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001659 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001660 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661 return;
1662 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001663 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001664 observer->OnSetRemoteDescriptionComplete(RTCError(
1665 RTCErrorType::UNSUPPORTED_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666 return;
1667 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001668
Steve Anton8d3444d2017-10-20 15:30:51 -07001669 if (IsClosed()) {
Henrik Boström31638672017-11-23 17:48:32 +01001670 std::string error = "Failed to set remote " + desc->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001671 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001672 RTC_LOG(LS_ERROR) << error;
Henrik Boström31638672017-11-23 17:48:32 +01001673 observer->OnSetRemoteDescriptionComplete(
1674 RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001675 return;
1676 }
1677
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678 // Update stats here so that we have the most recent stats for tracks and
1679 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001680 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681 std::string error;
Henrik Boström31638672017-11-23 17:48:32 +01001682 // Takes the ownership of |desc|. On success, remote_description() is updated
1683 // to reflect the description that was passed in.
1684 if (!SetCurrentOrPendingRemoteDescription(std::move(desc), &error)) {
1685 observer->OnSetRemoteDescriptionComplete(
1686 RTCError(RTCErrorType::UNSUPPORTED_PARAMETER, std::move(error)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687 return;
1688 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001689 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690
deadbeefab9b2d12015-10-14 11:33:11 -07001691 // If setting the description decided our SSL role, allocate any necessary
1692 // SCTP sids.
1693 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001694 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001695 AllocateSctpSids(role);
1696 }
1697
Henrik Boströmfdb92012017-11-09 19:55:44 +01001698 const cricket::ContentInfo* audio_content =
1699 GetFirstAudioContent(remote_description()->description());
1700 const cricket::ContentInfo* video_content =
1701 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001702 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001703 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001704 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001705 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001706 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001707 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001708
1709 // Check if the descriptions include streams, just in case the peer supports
1710 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001711 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001712 (audio_desc && !audio_desc->streams().empty()) ||
1713 (video_desc && !video_desc->streams().empty())) {
1714 remote_peer_supports_msid_ = true;
1715 }
deadbeefab9b2d12015-10-14 11:33:11 -07001716
1717 // We wait to signal new streams until we finish processing the description,
1718 // since only at that point will new streams have all their tracks.
1719 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1720
Steve Anton8d3444d2017-10-20 15:30:51 -07001721 // TODO(steveanton): When removing RTP senders/receivers in response to a
1722 // rejected media section, there is some cleanup logic that expects the voice/
1723 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001724 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001725 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001726 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
deadbeefab9b2d12015-10-14 11:33:11 -07001728 // Find all audio rtp streams and create corresponding remote AudioTracks
1729 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001730 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001731 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001732 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001733 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001734 bool default_audio_track_needed =
1735 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001736 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001737 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001738 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001739 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001740 }
deadbeefab9b2d12015-10-14 11:33:11 -07001741 }
1742
1743 // Find all video rtp streams and create corresponding remote VideoTracks
1744 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001745 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001746 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001747 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001748 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001749 bool default_video_track_needed =
1750 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001751 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001752 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001753 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001754 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001755 }
deadbeefab9b2d12015-10-14 11:33:11 -07001756 }
1757
1758 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001759 if (data_desc) {
1760 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001761 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001762 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001763 }
1764 }
1765
1766 // Iterate new_streams and notify the observer about new MediaStreams.
1767 for (size_t i = 0; i < new_streams->count(); ++i) {
1768 MediaStreamInterface* new_stream = new_streams->at(i);
1769 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001770 observer_->OnAddStream(
1771 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001772 }
1773
deadbeefbda7e0b2015-12-08 17:13:40 -08001774 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001775
Henrik Boström31638672017-11-23 17:48:32 +01001776 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
deadbeef42a42632017-03-10 15:18:00 -08001777
Henrik Boströmfdb92012017-11-09 19:55:44 +01001778 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001779 // TODO(deadbeef): We already had to hop to the network thread for
1780 // MaybeStartGathering...
1781 network_thread()->Invoke<void>(
1782 RTC_FROM_HERE,
1783 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1784 port_allocator_.get()));
1785 }
deadbeeffc648b62015-10-13 16:42:33 -07001786}
1787
deadbeef46c73892016-11-16 19:42:04 -08001788PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1789 return configuration_;
1790}
1791
deadbeef293e9262017-01-11 12:28:30 -08001792bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1793 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001794 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001795
Steve Anton75737c02017-11-06 10:37:17 -08001796 if (local_description() && configuration.ice_candidate_pool_size !=
1797 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001798 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1799 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001800 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001801 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001802
deadbeef293e9262017-01-11 12:28:30 -08001803 // The simplest (and most future-compatible) way to tell if the config was
1804 // modified in an invalid way is to copy each property we do support
1805 // modifying, then use operator==. There are far more properties we don't
1806 // support modifying than those we do, and more could be added.
1807 RTCConfiguration modified_config = configuration_;
1808 modified_config.servers = configuration.servers;
1809 modified_config.type = configuration.type;
1810 modified_config.ice_candidate_pool_size =
1811 configuration.ice_candidate_pool_size;
1812 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001813 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001814 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001815 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001816 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001817 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1818 }
1819
Steve Anton038834f2017-07-14 15:59:59 -07001820 // Validate the modified configuration.
1821 RTCError validate_error = ValidateConfiguration(modified_config);
1822 if (!validate_error.ok()) {
1823 return SafeSetError(std::move(validate_error), error);
1824 }
1825
deadbeef293e9262017-01-11 12:28:30 -08001826 // Note that this isn't possible through chromium, since it's an unsigned
1827 // short in WebIDL.
1828 if (configuration.ice_candidate_pool_size < 0 ||
1829 configuration.ice_candidate_pool_size > UINT16_MAX) {
1830 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1831 }
1832
1833 // Parse ICE servers before hopping to network thread.
1834 cricket::ServerAddresses stun_servers;
1835 std::vector<cricket::RelayServerConfig> turn_servers;
1836 RTCErrorType parse_error =
1837 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1838 if (parse_error != RTCErrorType::NONE) {
1839 return SafeSetError(parse_error, error);
1840 }
1841
1842 // In theory this shouldn't fail.
1843 if (!network_thread()->Invoke<bool>(
1844 RTC_FROM_HERE,
1845 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1846 stun_servers, turn_servers, modified_config.type,
1847 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001848 modified_config.prune_turn_ports,
1849 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001850 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001851 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1852 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001853
deadbeefd1a38b52016-12-10 13:15:33 -08001854 // As described in JSEP, calling setConfiguration with new ICE servers or
1855 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1856 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001857 if (modified_config.servers != configuration_.servers ||
1858 modified_config.type != configuration_.type ||
1859 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001860 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001861 }
skvladd1f5fda2017-02-03 16:54:05 -08001862
1863 if (modified_config.ice_check_min_interval !=
1864 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001865 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001866 }
1867
deadbeef293e9262017-01-11 12:28:30 -08001868 configuration_ = modified_config;
1869 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001870}
1871
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001872bool PeerConnection::AddIceCandidate(
1873 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001874 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001875 if (IsClosed()) {
1876 return false;
1877 }
Steve Antond25da372017-11-06 14:50:29 -08001878
1879 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1881 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001882 return false;
1883 }
1884
1885 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001886 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001887 return false;
1888 }
1889
1890 bool valid = false;
1891 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1892 if (!valid) {
1893 return false;
1894 }
1895
1896 // Add this candidate to the remote session description.
1897 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001898 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001899 return false;
1900 }
1901
1902 if (ready) {
1903 return UseCandidate(ice_candidate);
1904 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001905 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001906 return true;
1907 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908}
1909
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001910bool PeerConnection::RemoveIceCandidates(
1911 const std::vector<cricket::Candidate>& candidates) {
1912 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001913 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001914 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1915 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001916 return false;
1917 }
1918
1919 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001920 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001921 return false;
1922 }
1923
1924 size_t number_removed =
1925 mutable_remote_description()->RemoveCandidates(candidates);
1926 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001927 RTC_LOG(LS_ERROR)
1928 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1929 << "Requested " << candidates.size() << " but only " << number_removed
1930 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001931 }
1932
1933 // Remove the candidates from the transport controller.
1934 std::string error;
1935 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1936 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001938 }
1939 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001940}
1941
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001942void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001943 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001944 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001945
Steve Anton75737c02017-11-06 10:37:17 -08001946 if (transport_controller()) {
1947 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001948 }
1949
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001950 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001951 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001952 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001953 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001954 uma_observer_->IncrementEnumCounter(
1955 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1956 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001957 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001958 uma_observer_->IncrementEnumCounter(
1959 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1960 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001961 }
1962 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001963}
1964
zstein4b979802017-06-02 14:37:37 -07001965RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001966 if (!worker_thread()->IsCurrent()) {
1967 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001968 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1969 }
1970
1971 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1972 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1973 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1974 if (has_min && *bitrate.min_bitrate_bps < 0) {
1975 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1976 "min_bitrate_bps <= 0");
1977 }
1978 if (has_current) {
1979 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1980 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1981 "current_bitrate_bps < min_bitrate_bps");
1982 } else if (*bitrate.current_bitrate_bps < 0) {
1983 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1984 "curent_bitrate_bps < 0");
1985 }
1986 }
1987 if (has_max) {
1988 if (has_current &&
1989 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1990 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1991 "max_bitrate_bps < current_bitrate_bps");
1992 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1993 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1994 "max_bitrate_bps < min_bitrate_bps");
1995 } else if (*bitrate.max_bitrate_bps < 0) {
1996 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1997 "max_bitrate_bps < 0");
1998 }
1999 }
2000
2001 Call::Config::BitrateConfigMask mask;
2002 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2003 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2004 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2005
2006 RTC_DCHECK(call_.get());
2007 call_->SetBitrateConfigMask(mask);
2008
2009 return RTCError::OK();
2010}
2011
Alex Narest78609d52017-10-20 10:37:47 +02002012void PeerConnection::SetBitrateAllocationStrategy(
2013 std::unique_ptr<rtc::BitrateAllocationStrategy>
2014 bitrate_allocation_strategy) {
2015 rtc::Thread* worker_thread = factory_->worker_thread();
2016 if (!worker_thread->IsCurrent()) {
2017 rtc::BitrateAllocationStrategy* strategy_raw =
2018 bitrate_allocation_strategy.release();
2019 auto functor = [this, strategy_raw]() {
2020 call_->SetBitrateAllocationStrategy(
2021 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2022 };
2023 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2024 return;
2025 }
2026 RTC_DCHECK(call_.get());
2027 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2028}
2029
henrika5f6bf242017-11-01 11:06:56 +01002030void PeerConnection::SetAudioPlayout(bool playout) {
2031 if (!worker_thread()->IsCurrent()) {
2032 worker_thread()->Invoke<void>(
2033 RTC_FROM_HERE,
2034 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2035 return;
2036 }
2037 auto audio_state =
2038 factory_->channel_manager()->media_engine()->GetAudioState();
2039 audio_state->SetPlayout(playout);
2040}
2041
2042void PeerConnection::SetAudioRecording(bool recording) {
2043 if (!worker_thread()->IsCurrent()) {
2044 worker_thread()->Invoke<void>(
2045 RTC_FROM_HERE,
2046 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2047 return;
2048 }
2049 auto audio_state =
2050 factory_->channel_manager()->media_engine()->GetAudioState();
2051 audio_state->SetRecording(recording);
2052}
2053
Steve Anton8c0f7a72017-10-03 10:03:10 -07002054std::unique_ptr<rtc::SSLCertificate>
2055PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002056 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002057 return nullptr;
2058 }
Steve Anton75737c02017-11-06 10:37:17 -08002059 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002060}
2061
ivoc14d5dbe2016-07-04 07:06:55 -07002062bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2063 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002064 // TODO(eladalon): It would be better to not allow negative values into PC.
2065 const size_t max_size = (max_size_bytes < 0)
2066 ? RtcEventLog::kUnlimitedOutput
2067 : rtc::saturated_cast<size_t>(max_size_bytes);
2068 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002069 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2070 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002071}
2072
Bjorn Tereliusde939432017-11-20 17:38:14 +01002073bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2074 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002075 // TODO(eladalon): In C++14, this can be done with a lambda.
2076 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002077 bool operator()() {
2078 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2079 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002080 PeerConnection* const pc;
2081 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002082 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002083 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002084 return worker_thread()->Invoke<bool>(
2085 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002086}
2087
2088void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002089 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002090 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2091}
2092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002094 return pending_local_description_ ? pending_local_description_.get()
2095 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002096}
2097
2098const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002099 return pending_remote_description_ ? pending_remote_description_.get()
2100 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101}
2102
deadbeeffe4a8a42016-12-20 17:56:17 -08002103const SessionDescriptionInterface* PeerConnection::current_local_description()
2104 const {
Steve Anton75737c02017-11-06 10:37:17 -08002105 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002106}
2107
2108const SessionDescriptionInterface* PeerConnection::current_remote_description()
2109 const {
Steve Anton75737c02017-11-06 10:37:17 -08002110 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002111}
2112
2113const SessionDescriptionInterface* PeerConnection::pending_local_description()
2114 const {
Steve Anton75737c02017-11-06 10:37:17 -08002115 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002116}
2117
2118const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2119 const {
Steve Anton75737c02017-11-06 10:37:17 -08002120 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002121}
2122
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002124 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 // Update stats here so that we have the most recent stats for tracks and
2126 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002127 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128
Steve Anton75737c02017-11-06 10:37:17 -08002129 ChangeSignalingState(PeerConnectionInterface::kClosed);
2130 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002131 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2132 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002133 RTC_DCHECK(!rtp_data_channel_);
2134 RTC_DCHECK(!sctp_transport_);
2135
deadbeef42a42632017-03-10 15:18:00 -08002136 network_thread()->Invoke<void>(
2137 RTC_FROM_HERE,
2138 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2139 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002140
Steve Anton978b8762017-09-29 12:15:02 -07002141 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002142 call_.reset();
2143 // The event log must outlive call (and any other object that uses it).
2144 event_log_.reset();
2145 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146}
2147
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002148void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2151 SetSessionDescriptionMsg* param =
2152 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2153 param->observer->OnSuccess();
2154 delete param;
2155 break;
2156 }
2157 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2158 SetSessionDescriptionMsg* param =
2159 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2160 param->observer->OnFailure(param->error);
2161 delete param;
2162 break;
2163 }
deadbeefab9b2d12015-10-14 11:33:11 -07002164 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2165 CreateSessionDescriptionMsg* param =
2166 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2167 param->observer->OnFailure(param->error);
2168 delete param;
2169 break;
2170 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171 case MSG_GETSTATS: {
2172 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002173 StatsReports reports;
2174 stats_->GetStats(param->track, &reports);
2175 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 delete param;
2177 break;
2178 }
deadbeefbd292462015-12-14 18:15:29 -08002179 case MSG_FREE_DATACHANNELS: {
2180 sctp_data_channels_to_free_.clear();
2181 break;
2182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002184 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 break;
2186 }
2187}
2188
Steve Anton4171afb2017-11-20 10:20:22 -08002189void PeerConnection::CreateAudioReceiver(
2190 MediaStreamInterface* stream,
2191 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002192 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2193 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002194 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2195 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002196 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002197 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002198 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002199 stream->AddTrack(
2200 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002201 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002202 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203}
2204
Steve Anton4171afb2017-11-20 10:20:22 -08002205void PeerConnection::CreateVideoReceiver(
2206 MediaStreamInterface* stream,
2207 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002208 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2209 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002210 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2211 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002212 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002213 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2214 worker_thread(), remote_sender_info.first_ssrc,
2215 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002216 stream->AddTrack(
2217 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002218 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002219 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220}
2221
deadbeef70ab1a12015-09-28 16:53:55 -07002222// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2223// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002224rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002225 const RtpSenderInfo& remote_sender_info) {
2226 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2227 if (!receiver) {
2228 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2229 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002230 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002231 }
Steve Anton4171afb2017-11-20 10:20:22 -08002232 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2233 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2234 } else {
2235 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2236 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002237 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238}
2239
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002240void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2241 MediaStreamInterface* stream) {
2242 RTC_DCHECK(!IsClosed());
2243 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002244 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002245 // We already have a sender for this track, so just change the stream_id
2246 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002247 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002248 return;
2249 }
2250
2251 // Normal case; we've never seen this track before.
2252 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2253 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2254 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002255 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2256 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002257 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002258 // If the sender has already been configured in SDP, we call SetSsrc,
2259 // which will connect the sender to the underlying transport. This can
2260 // occur if a local session description that contains the ID of the sender
2261 // is set before AddStream is called. It can also occur if the local
2262 // session description is not changed and RemoveStream is called, and
2263 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002264 const RtpSenderInfo* sender_info =
2265 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2266 if (sender_info) {
2267 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002268 }
2269}
2270
2271// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2272// indefinitely, when we have unified plan SDP.
2273void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2274 MediaStreamInterface* stream) {
2275 RTC_DCHECK(!IsClosed());
2276 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002277 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002278 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2279 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002280 return;
2281 }
Steve Anton4171afb2017-11-20 10:20:22 -08002282 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002283}
2284
2285void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2286 MediaStreamInterface* stream) {
2287 RTC_DCHECK(!IsClosed());
2288 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002289 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002290 // We already have a sender for this track, so just change the stream_id
2291 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002292 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002293 return;
2294 }
2295
2296 // Normal case; we've never seen this track before.
2297 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2298 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002299 signaling_thread(),
2300 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002301 GetVideoTransceiver()->internal()->AddSender(new_sender);
2302 const RtpSenderInfo* sender_info =
2303 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2304 if (sender_info) {
2305 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002306 }
2307}
2308
2309void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2310 MediaStreamInterface* stream) {
2311 RTC_DCHECK(!IsClosed());
2312 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002313 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002314 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2315 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002316 return;
2317 }
Steve Anton4171afb2017-11-20 10:20:22 -08002318 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002319}
2320
Steve Antonba818672017-11-06 10:21:57 -08002321void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002322 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002323 if (ice_connection_state_ == new_state) {
2324 return;
2325 }
2326
deadbeefcbecd352015-09-23 11:50:27 -07002327 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002328 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002329 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002330 return;
2331 }
Steve Antonba818672017-11-06 10:21:57 -08002332
Mirko Bonadei675513b2017-11-09 11:09:25 +01002333 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2334 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002335 RTC_DCHECK(ice_connection_state_ !=
2336 PeerConnectionInterface::kIceConnectionClosed);
2337
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002339 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340}
2341
2342void PeerConnection::OnIceGatheringChange(
2343 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002344 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 if (IsClosed()) {
2346 return;
2347 }
2348 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002349 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350}
2351
jbauch81bf7b02017-03-25 08:31:12 -07002352void PeerConnection::OnIceCandidate(
2353 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002354 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002355 if (IsClosed()) {
2356 return;
2357 }
jbauch81bf7b02017-03-25 08:31:12 -07002358 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002359}
2360
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002361void PeerConnection::OnIceCandidatesRemoved(
2362 const std::vector<cricket::Candidate>& candidates) {
2363 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002364 if (IsClosed()) {
2365 return;
2366 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002367 observer_->OnIceCandidatesRemoved(candidates);
2368}
2369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370void PeerConnection::ChangeSignalingState(
2371 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002372 RTC_DCHECK(signaling_thread()->IsCurrent());
2373 if (signaling_state_ == signaling_state) {
2374 return;
2375 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002376 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2377 << GetSignalingStateString(signaling_state_)
2378 << " New state: "
2379 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 signaling_state_ = signaling_state;
2381 if (signaling_state == kClosed) {
2382 ice_connection_state_ = kIceConnectionClosed;
2383 observer_->OnIceConnectionChange(ice_connection_state_);
2384 if (ice_gathering_state_ != kIceGatheringComplete) {
2385 ice_gathering_state_ = kIceGatheringComplete;
2386 observer_->OnIceGatheringChange(ice_gathering_state_);
2387 }
2388 }
2389 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002390}
2391
deadbeefeb459812015-12-15 19:24:43 -08002392void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2393 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002394 if (IsClosed()) {
2395 return;
2396 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002397 AddAudioTrack(track, stream);
2398 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002399}
2400
deadbeefeb459812015-12-15 19:24:43 -08002401void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2402 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002403 if (IsClosed()) {
2404 return;
2405 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002406 RemoveAudioTrack(track, stream);
2407 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002408}
2409
2410void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2411 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002412 if (IsClosed()) {
2413 return;
2414 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002415 AddVideoTrack(track, stream);
2416 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002417}
2418
2419void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2420 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002421 if (IsClosed()) {
2422 return;
2423 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002424 RemoveVideoTrack(track, stream);
2425 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002426}
2427
Henrik Boström31638672017-11-23 17:48:32 +01002428void PeerConnection::PostSetSessionDescriptionSuccess(
2429 SetSessionDescriptionObserver* observer) {
2430 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2431 signaling_thread()->Post(RTC_FROM_HERE, this,
2432 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2433}
2434
deadbeefab9b2d12015-10-14 11:33:11 -07002435void PeerConnection::PostSetSessionDescriptionFailure(
2436 SetSessionDescriptionObserver* observer,
2437 const std::string& error) {
2438 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2439 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002440 signaling_thread()->Post(RTC_FROM_HERE, this,
2441 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002442}
2443
2444void PeerConnection::PostCreateSessionDescriptionFailure(
2445 CreateSessionDescriptionObserver* observer,
2446 const std::string& error) {
2447 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2448 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002449 signaling_thread()->Post(RTC_FROM_HERE, this,
2450 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002451}
2452
zhihuang1c378ed2017-08-17 14:10:50 -07002453void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002454 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2455 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002456 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2457
2458 // Figure out transceiver directional preferences.
2459 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2460 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2461
2462 // By default, generate sendrecv/recvonly m= sections.
2463 bool recv_audio = true;
2464 bool recv_video = true;
2465
2466 // By default, only offer a new m= section if we have media to send with it.
2467 bool offer_new_audio_description = send_audio;
2468 bool offer_new_video_description = send_video;
2469 bool offer_new_data_description = HasDataChannels();
2470
2471 // The "offer_to_receive_X" options allow those defaults to be overridden.
2472 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2473 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2474 offer_new_audio_description =
2475 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2476 }
2477 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2478 recv_video = (rtc_options.offer_to_receive_video > 0);
2479 offer_new_video_description =
2480 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2481 }
2482
2483 rtc::Optional<size_t> audio_index;
2484 rtc::Optional<size_t> video_index;
2485 rtc::Optional<size_t> data_index;
2486 // If a current description exists, generate m= sections in the same order,
2487 // using the first audio/video/data section that appears and rejecting
2488 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002489 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002490 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002491 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002492 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2493 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2494 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002495 }
2496
zhihuang1c378ed2017-08-17 14:10:50 -07002497 // Add audio/video/data m= sections to the end if needed.
2498 if (!audio_index && offer_new_audio_description) {
2499 session_options->media_description_options.push_back(
2500 cricket::MediaDescriptionOptions(
2501 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002502 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2503 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002504 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002505 }
zhihuang1c378ed2017-08-17 14:10:50 -07002506 if (!video_index && offer_new_video_description) {
2507 session_options->media_description_options.push_back(
2508 cricket::MediaDescriptionOptions(
2509 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002510 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2511 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002512 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002513 }
zhihuang1c378ed2017-08-17 14:10:50 -07002514 if (!data_index && offer_new_data_description) {
2515 session_options->media_description_options.push_back(
2516 cricket::MediaDescriptionOptions(
2517 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002518 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002519 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002520 }
2521
2522 cricket::MediaDescriptionOptions* audio_media_description_options =
2523 !audio_index ? nullptr
2524 : &session_options->media_description_options[*audio_index];
2525 cricket::MediaDescriptionOptions* video_media_description_options =
2526 !video_index ? nullptr
2527 : &session_options->media_description_options[*video_index];
2528 cricket::MediaDescriptionOptions* data_media_description_options =
2529 !data_index ? nullptr
2530 : &session_options->media_description_options[*data_index];
2531
2532 // Apply ICE restart flag and renomination flag.
2533 for (auto& options : session_options->media_description_options) {
2534 options.transport_options.ice_restart = rtc_options.ice_restart;
2535 options.transport_options.enable_ice_renomination =
2536 configuration_.enable_ice_renomination;
2537 }
2538
Steve Anton4171afb2017-11-20 10:20:22 -08002539 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002540 video_media_description_options);
2541 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002542
zhihuang9763d562016-08-05 11:14:50 -07002543 // Intentionally unset the data channel type for RTP data channel with the
2544 // second condition. Otherwise the RTP data channels would be successfully
2545 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2546 // when building with chromium. We want to leave RTP data channels broken, so
2547 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002548 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2549 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002550 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002551
2552 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002553 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002554}
2555
zhihuang1c378ed2017-08-17 14:10:50 -07002556void PeerConnection::GetOptionsForAnswer(
2557 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002558 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002559 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002560
zhihuang1c378ed2017-08-17 14:10:50 -07002561 // Figure out transceiver directional preferences.
2562 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2563 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2564
2565 // By default, generate sendrecv/recvonly m= sections. The direction is also
2566 // restricted by the direction in the offer.
2567 bool recv_audio = true;
2568 bool recv_video = true;
2569
2570 // The "offer_to_receive_X" options allow those defaults to be overridden.
2571 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2572 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002573 }
zhihuang1c378ed2017-08-17 14:10:50 -07002574 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2575 recv_video = (rtc_options.offer_to_receive_video > 0);
2576 }
2577
2578 rtc::Optional<size_t> audio_index;
2579 rtc::Optional<size_t> video_index;
2580 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002581 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002582 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002583 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002584 SessionDescriptionInterface::kOffer);
2585 // Generate m= sections that match those in the offer.
2586 // Note that mediasession.cc will handle intersection our preferred
2587 // direction with the offered direction.
2588 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002589 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002590 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2591 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2592 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002593 }
zhihuang1c378ed2017-08-17 14:10:50 -07002594
2595 cricket::MediaDescriptionOptions* audio_media_description_options =
2596 !audio_index ? nullptr
2597 : &session_options->media_description_options[*audio_index];
2598 cricket::MediaDescriptionOptions* video_media_description_options =
2599 !video_index ? nullptr
2600 : &session_options->media_description_options[*video_index];
2601 cricket::MediaDescriptionOptions* data_media_description_options =
2602 !data_index ? nullptr
2603 : &session_options->media_description_options[*data_index];
2604
2605 // Apply ICE renomination flag.
2606 for (auto& options : session_options->media_description_options) {
2607 options.transport_options.enable_ice_renomination =
2608 configuration_.enable_ice_renomination;
2609 }
2610
Steve Anton4171afb2017-11-20 10:20:22 -08002611 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002612 video_media_description_options);
2613 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2614
zhihuang9763d562016-08-05 11:14:50 -07002615 // Intentionally unset the data channel type for RTP data channel. Otherwise
2616 // the RTP data channels would be successfully negotiated by default and the
2617 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2618 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002619 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2620 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002621 }
zhihuangaf388472016-11-02 16:49:48 -07002622
zhihuang1c378ed2017-08-17 14:10:50 -07002623 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002624 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002625}
2626
zhihuang1c378ed2017-08-17 14:10:50 -07002627void PeerConnection::GenerateMediaDescriptionOptions(
2628 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002629 RtpTransceiverDirection audio_direction,
2630 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002631 rtc::Optional<size_t>* audio_index,
2632 rtc::Optional<size_t>* video_index,
2633 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002634 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002635 for (const cricket::ContentInfo& content :
2636 session_desc->description()->contents()) {
2637 if (IsAudioContent(&content)) {
2638 // If we already have an audio m= section, reject this extra one.
2639 if (*audio_index) {
2640 session_options->media_description_options.push_back(
2641 cricket::MediaDescriptionOptions(
2642 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002643 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002644 } else {
2645 session_options->media_description_options.push_back(
2646 cricket::MediaDescriptionOptions(
2647 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002648 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002649 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002650 }
2651 } else if (IsVideoContent(&content)) {
2652 // If we already have an video m= section, reject this extra one.
2653 if (*video_index) {
2654 session_options->media_description_options.push_back(
2655 cricket::MediaDescriptionOptions(
2656 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002657 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002658 } else {
2659 session_options->media_description_options.push_back(
2660 cricket::MediaDescriptionOptions(
2661 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002662 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002663 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002664 }
2665 } else {
2666 RTC_DCHECK(IsDataContent(&content));
2667 // If we already have an data m= section, reject this extra one.
2668 if (*data_index) {
2669 session_options->media_description_options.push_back(
2670 cricket::MediaDescriptionOptions(
2671 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002672 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002673 } else {
2674 session_options->media_description_options.push_back(
2675 cricket::MediaDescriptionOptions(
2676 cricket::MEDIA_TYPE_DATA, content.name,
2677 // Direction for data sections is meaningless, but legacy
2678 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002679 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002680 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002681 }
2682 }
htaa2a49d92016-03-04 02:51:39 -08002683 }
deadbeefab9b2d12015-10-14 11:33:11 -07002684}
2685
Steve Anton4171afb2017-11-20 10:20:22 -08002686void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2687 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2688 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002689 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002690}
2691
Steve Anton4171afb2017-11-20 10:20:22 -08002692void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002693 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002694 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002695 cricket::MediaType media_type,
2696 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002697 std::vector<RtpSenderInfo>* current_senders =
2698 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002699
Steve Anton4171afb2017-11-20 10:20:22 -08002700 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002701 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002702 for (auto sender_it = current_senders->begin();
2703 sender_it != current_senders->end();
2704 /* incremented manually */) {
2705 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002706 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002707 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2708 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002709 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002710 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2711 sender_exists) {
2712 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002713 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002714 OnRemoteSenderRemoved(info, media_type);
2715 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002716 }
2717 }
2718
Steve Anton4171afb2017-11-20 10:20:22 -08002719 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002720 for (const cricket::StreamParams& params : streams) {
2721 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002722 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002723 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002724 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002725 uint32_t ssrc = params.first_ssrc();
2726
2727 rtc::scoped_refptr<MediaStreamInterface> stream =
2728 remote_streams_->find(stream_label);
2729 if (!stream) {
2730 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002731 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2732 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002733 remote_streams_->AddStream(stream);
2734 new_streams->AddStream(stream);
2735 }
2736
Steve Anton4171afb2017-11-20 10:20:22 -08002737 const RtpSenderInfo* sender_info =
2738 FindSenderInfo(*current_senders, stream_label, sender_id);
2739 if (!sender_info) {
2740 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2741 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002742 }
2743 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002744
Steve Anton4171afb2017-11-20 10:20:22 -08002745 // Add default sender if necessary.
2746 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002747 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2748 remote_streams_->find(kDefaultStreamLabel);
2749 if (!default_stream) {
2750 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002751 default_stream = MediaStreamProxy::Create(
2752 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002753 remote_streams_->AddStream(default_stream);
2754 new_streams->AddStream(default_stream);
2755 }
Steve Anton4171afb2017-11-20 10:20:22 -08002756 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2757 ? kDefaultAudioSenderId
2758 : kDefaultVideoSenderId;
2759 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2760 *current_senders, kDefaultStreamLabel, default_sender_id);
2761 if (!default_sender_info) {
2762 current_senders->push_back(
2763 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2764 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002765 }
2766 }
deadbeefab9b2d12015-10-14 11:33:11 -07002767}
2768
Steve Anton4171afb2017-11-20 10:20:22 -08002769void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2770 cricket::MediaType media_type) {
2771 MediaStreamInterface* stream =
2772 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002773
2774 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002775 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002776 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002777 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002778 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002779 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002780 }
2781}
2782
Steve Anton4171afb2017-11-20 10:20:22 -08002783void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2784 cricket::MediaType media_type) {
2785 MediaStreamInterface* stream =
2786 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002787
Henrik Boström933d8b02017-10-10 10:05:16 -07002788 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002789 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002790 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2791 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002792 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002793 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002794 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002795 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002796 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002797 }
2798 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002799 // Stopping or destroying a VideoRtpReceiver will end the
2800 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002801 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002802 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002803 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002804 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002805 // There's no guarantee the track is still available, e.g. the track may
2806 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002807 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002808 }
2809 } else {
nisseede5da42017-01-12 05:15:36 -08002810 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002811 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002812 if (receiver) {
2813 observer_->OnRemoveTrack(receiver);
2814 }
deadbeefab9b2d12015-10-14 11:33:11 -07002815}
2816
2817void PeerConnection::UpdateEndedRemoteMediaStreams() {
2818 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2819 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2820 MediaStreamInterface* stream = remote_streams_->at(i);
2821 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2822 streams_to_remove.push_back(stream);
2823 }
2824 }
2825
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002826 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002827 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002828 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002829 }
2830}
2831
Steve Anton4171afb2017-11-20 10:20:22 -08002832void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002833 const std::vector<cricket::StreamParams>& streams,
2834 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002835 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002836
2837 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2838 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002839 for (auto sender_it = current_senders->begin();
2840 sender_it != current_senders->end();
2841 /* incremented manually */) {
2842 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002843 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002844 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2845 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002846 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002847 OnLocalSenderRemoved(info, media_type);
2848 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002849 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002850 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002851 }
2852 }
2853
Steve Anton4171afb2017-11-20 10:20:22 -08002854 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002855 for (const cricket::StreamParams& params : streams) {
2856 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002857 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002858 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002859 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002860 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002861 const RtpSenderInfo* sender_info =
2862 FindSenderInfo(*current_senders, stream_label, sender_id);
2863 if (!sender_info) {
2864 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2865 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002866 }
2867 }
2868}
2869
Steve Anton4171afb2017-11-20 10:20:22 -08002870void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2871 cricket::MediaType media_type) {
2872 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002873 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002874 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2875 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002876 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002877 return;
2878 }
2879
deadbeeffac06552015-11-25 11:26:01 -08002880 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002881 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2882 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002883 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002884 }
deadbeeffac06552015-11-25 11:26:01 -08002885
Steve Anton4171afb2017-11-20 10:20:22 -08002886 sender->internal()->set_stream_id(sender_info.stream_label);
2887 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002888}
2889
Steve Anton4171afb2017-11-20 10:20:22 -08002890void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2891 cricket::MediaType media_type) {
2892 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002893 if (!sender) {
2894 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002895 // SessionDescriptions has been renegotiated.
2896 return;
2897 }
deadbeeffac06552015-11-25 11:26:01 -08002898
2899 // A sender has been removed from the SessionDescription but it's still
2900 // associated with the PeerConnection. This only occurs if the SDP doesn't
2901 // match with the calls to CreateSender, AddStream and RemoveStream.
2902 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002903 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2904 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002905 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002906 }
deadbeeffac06552015-11-25 11:26:01 -08002907
Steve Anton4171afb2017-11-20 10:20:22 -08002908 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002909}
2910
2911void PeerConnection::UpdateLocalRtpDataChannels(
2912 const cricket::StreamParamsVec& streams) {
2913 std::vector<std::string> existing_channels;
2914
2915 // Find new and active data channels.
2916 for (const cricket::StreamParams& params : streams) {
2917 // |it->sync_label| is actually the data channel label. The reason is that
2918 // we use the same naming of data channels as we do for
2919 // MediaStreams and Tracks.
2920 // For MediaStreams, the sync_label is the MediaStream label and the
2921 // track label is the same as |streamid|.
2922 const std::string& channel_label = params.sync_label;
2923 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002924 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002925 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002926 continue;
2927 }
2928 // Set the SSRC the data channel should use for sending.
2929 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2930 existing_channels.push_back(data_channel_it->first);
2931 }
2932
2933 UpdateClosingRtpDataChannels(existing_channels, true);
2934}
2935
2936void PeerConnection::UpdateRemoteRtpDataChannels(
2937 const cricket::StreamParamsVec& streams) {
2938 std::vector<std::string> existing_channels;
2939
2940 // Find new and active data channels.
2941 for (const cricket::StreamParams& params : streams) {
2942 // The data channel label is either the mslabel or the SSRC if the mslabel
2943 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2944 std::string label = params.sync_label.empty()
2945 ? rtc::ToString(params.first_ssrc())
2946 : params.sync_label;
2947 auto data_channel_it = rtp_data_channels_.find(label);
2948 if (data_channel_it == rtp_data_channels_.end()) {
2949 // This is a new data channel.
2950 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2951 } else {
2952 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2953 }
2954 existing_channels.push_back(label);
2955 }
2956
2957 UpdateClosingRtpDataChannels(existing_channels, false);
2958}
2959
2960void PeerConnection::UpdateClosingRtpDataChannels(
2961 const std::vector<std::string>& active_channels,
2962 bool is_local_update) {
2963 auto it = rtp_data_channels_.begin();
2964 while (it != rtp_data_channels_.end()) {
2965 DataChannel* data_channel = it->second;
2966 if (std::find(active_channels.begin(), active_channels.end(),
2967 data_channel->label()) != active_channels.end()) {
2968 ++it;
2969 continue;
2970 }
2971
2972 if (is_local_update) {
2973 data_channel->SetSendSsrc(0);
2974 } else {
2975 data_channel->RemotePeerRequestClose();
2976 }
2977
2978 if (data_channel->state() == DataChannel::kClosed) {
2979 rtp_data_channels_.erase(it);
2980 it = rtp_data_channels_.begin();
2981 } else {
2982 ++it;
2983 }
2984 }
2985}
2986
2987void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2988 uint32_t remote_ssrc) {
2989 rtc::scoped_refptr<DataChannel> channel(
2990 InternalCreateDataChannel(label, nullptr));
2991 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002992 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2993 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07002994 return;
2995 }
2996 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002997 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2998 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002999 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003000}
3001
3002rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3003 const std::string& label,
3004 const InternalDataChannelInit* config) {
3005 if (IsClosed()) {
3006 return nullptr;
3007 }
Steve Anton75737c02017-11-06 10:37:17 -08003008 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003009 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003010 << "InternalCreateDataChannel: Data is not supported in this call.";
3011 return nullptr;
3012 }
3013 InternalDataChannelInit new_config =
3014 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003015 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003016 if (new_config.id < 0) {
3017 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003018 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003019 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003020 RTC_LOG(LS_ERROR)
3021 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003022 return nullptr;
3023 }
3024 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003025 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3026 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003027 return nullptr;
3028 }
3029 }
3030
Steve Anton75737c02017-11-06 10:37:17 -08003031 rtc::scoped_refptr<DataChannel> channel(
3032 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003033 if (!channel) {
3034 sid_allocator_.ReleaseSid(new_config.id);
3035 return nullptr;
3036 }
3037
3038 if (channel->data_channel_type() == cricket::DCT_RTP) {
3039 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003040 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3041 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003042 return nullptr;
3043 }
3044 rtp_data_channels_[channel->label()] = channel;
3045 } else {
3046 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3047 sctp_data_channels_.push_back(channel);
3048 channel->SignalClosed.connect(this,
3049 &PeerConnection::OnSctpDataChannelClosed);
3050 }
3051
hbos82ebe022016-11-14 01:41:09 -08003052 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003053 return channel;
3054}
3055
3056bool PeerConnection::HasDataChannels() const {
3057 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3058}
3059
3060void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3061 for (const auto& channel : sctp_data_channels_) {
3062 if (channel->id() < 0) {
3063 int sid;
3064 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003065 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003066 continue;
3067 }
3068 channel->SetSctpSid(sid);
3069 }
3070 }
3071}
3072
3073void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003074 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003075 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3076 ++it) {
3077 if (it->get() == channel) {
3078 if (channel->id() >= 0) {
3079 sid_allocator_.ReleaseSid(channel->id());
3080 }
deadbeefbd292462015-12-14 18:15:29 -08003081 // Since this method is triggered by a signal from the DataChannel,
3082 // we can't free it directly here; we need to free it asynchronously.
3083 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003084 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003085 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3086 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003087 return;
3088 }
3089 }
3090}
3091
deadbeefab9b2d12015-10-14 11:33:11 -07003092void PeerConnection::OnDataChannelDestroyed() {
3093 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3094 // DataChannel may callback to us and try to modify the list.
3095 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3096 temp_rtp_dcs.swap(rtp_data_channels_);
3097 for (const auto& kv : temp_rtp_dcs) {
3098 kv.second->OnTransportChannelDestroyed();
3099 }
3100
3101 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3102 temp_sctp_dcs.swap(sctp_data_channels_);
3103 for (const auto& channel : temp_sctp_dcs) {
3104 channel->OnTransportChannelDestroyed();
3105 }
3106}
3107
3108void PeerConnection::OnDataChannelOpenMessage(
3109 const std::string& label,
3110 const InternalDataChannelInit& config) {
3111 rtc::scoped_refptr<DataChannel> channel(
3112 InternalCreateDataChannel(label, &config));
3113 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003114 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003115 return;
3116 }
3117
deadbeefa601f5c2016-06-06 14:27:39 -07003118 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3119 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003120 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003121}
3122
Steve Anton4171afb2017-11-20 10:20:22 -08003123rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3124PeerConnection::GetAudioTransceiver() const {
3125 // This method only works with Plan B SDP, where there is a single
3126 // audio/video transceiver.
3127 RTC_DCHECK(!IsUnifiedPlan());
3128 for (auto transceiver : transceivers_) {
3129 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3130 return transceiver;
3131 }
3132 }
3133 RTC_NOTREACHED();
3134 return nullptr;
3135}
3136
3137rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3138PeerConnection::GetVideoTransceiver() const {
3139 // This method only works with Plan B SDP, where there is a single
3140 // audio/video transceiver.
3141 RTC_DCHECK(!IsUnifiedPlan());
3142 for (auto transceiver : transceivers_) {
3143 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3144 return transceiver;
3145 }
3146 }
3147 RTC_NOTREACHED();
3148 return nullptr;
3149}
3150
3151// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3152// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003153bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003154 switch (type) {
3155 case cricket::MEDIA_TYPE_AUDIO:
3156 return !GetAudioTransceiver()->internal()->senders().empty();
3157 case cricket::MEDIA_TYPE_VIDEO:
3158 return !GetVideoTransceiver()->internal()->senders().empty();
3159 case cricket::MEDIA_TYPE_DATA:
3160 return false;
3161 }
3162 RTC_NOTREACHED();
3163 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003164}
3165
Steve Anton4171afb2017-11-20 10:20:22 -08003166rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3167PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3168 for (auto transceiver : transceivers_) {
3169 for (auto sender : transceiver->internal()->senders()) {
3170 if (sender->track() == track) {
3171 return sender;
3172 }
3173 }
3174 }
3175 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003176}
3177
Steve Anton4171afb2017-11-20 10:20:22 -08003178rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3179PeerConnection::FindSenderById(const std::string& sender_id) const {
3180 for (auto transceiver : transceivers_) {
3181 for (auto sender : transceiver->internal()->senders()) {
3182 if (sender->id() == sender_id) {
3183 return sender;
3184 }
3185 }
3186 }
3187 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003188}
3189
Steve Anton4171afb2017-11-20 10:20:22 -08003190rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3191PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3192 for (auto transceiver : transceivers_) {
3193 for (auto receiver : transceiver->internal()->receivers()) {
3194 if (receiver->id() == receiver_id) {
3195 return receiver;
3196 }
3197 }
3198 }
3199 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003200}
3201
Steve Anton4171afb2017-11-20 10:20:22 -08003202std::vector<PeerConnection::RtpSenderInfo>*
3203PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3204 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3205 media_type == cricket::MEDIA_TYPE_VIDEO);
3206 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3207 ? &remote_audio_sender_infos_
3208 : &remote_video_sender_infos_;
3209}
3210
3211std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003212 cricket::MediaType media_type) {
3213 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3214 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003215 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3216 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003217}
3218
Steve Anton4171afb2017-11-20 10:20:22 -08003219const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3220 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003221 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003222 const std::string sender_id) const {
3223 for (const RtpSenderInfo& sender_info : infos) {
3224 if (sender_info.stream_label == stream_label &&
3225 sender_info.sender_id == sender_id) {
3226 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003227 }
3228 }
3229 return nullptr;
3230}
3231
3232DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3233 for (const auto& channel : sctp_data_channels_) {
3234 if (channel->id() == sid) {
3235 return channel;
3236 }
3237 }
3238 return nullptr;
3239}
3240
deadbeef91dd5672016-05-18 16:55:30 -07003241bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003242 const RTCConfiguration& configuration) {
3243 cricket::ServerAddresses stun_servers;
3244 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003245 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3246 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003247 return false;
3248 }
3249
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003250 port_allocator_->Initialize();
3251
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003252 // To handle both internal and externally created port allocator, we will
3253 // enable BUNDLE here.
3254 int portallocator_flags = port_allocator_->flags();
3255 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003256 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3257 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003258 // If the disable-IPv6 flag was specified, we'll not override it
3259 // by experiment.
3260 if (configuration.disable_ipv6) {
3261 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003262 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3263 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003264 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3265 }
3266
zhihuangb09b3f92017-03-07 14:40:51 -08003267 if (configuration.disable_ipv6_on_wifi) {
3268 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003269 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003270 }
3271
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003272 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3273 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003274 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003275 }
3276
honghaiz60347052016-05-31 18:29:12 -07003277 if (configuration.candidate_network_policy ==
3278 kCandidateNetworkPolicyLowCost) {
3279 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003280 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003281 }
3282
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003283 port_allocator_->set_flags(portallocator_flags);
3284 // No step delay is used while allocating ports.
3285 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3286 port_allocator_->set_candidate_filter(
3287 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003288 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003289
3290 // Call this last since it may create pooled allocator sessions using the
3291 // properties set above.
3292 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003293 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003294 configuration.prune_turn_ports,
3295 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003296 return true;
3297}
3298
deadbeef91dd5672016-05-18 16:55:30 -07003299bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003300 const cricket::ServerAddresses& stun_servers,
3301 const std::vector<cricket::RelayServerConfig>& turn_servers,
3302 IceTransportsType type,
3303 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003304 bool prune_turn_ports,
3305 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003306 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003307 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003308 // Call this last since it may create pooled allocator sessions using the
3309 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003310 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003311 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3312 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003313}
3314
Steve Antonba818672017-11-06 10:21:57 -08003315cricket::ChannelManager* PeerConnection::channel_manager() const {
3316 return factory_->channel_manager();
3317}
3318
3319MetricsObserverInterface* PeerConnection::metrics_observer() const {
3320 return uma_observer_;
3321}
3322
Elad Alon99c3fe52017-10-13 16:29:40 +02003323bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003324 std::unique_ptr<RtcEventLogOutput> output,
3325 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003326 if (!event_log_) {
3327 return false;
3328 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003329 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003330}
3331
3332void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003333 if (event_log_) {
3334 event_log_->StopLogging();
3335 }
ivoc14d5dbe2016-07-04 07:06:55 -07003336}
nisseeaabdf62017-05-05 02:23:02 -07003337
Steve Anton75737c02017-11-06 10:37:17 -08003338cricket::BaseChannel* PeerConnection::GetChannel(
3339 const std::string& content_name) {
3340 if (voice_channel() && voice_channel()->content_name() == content_name) {
3341 return voice_channel();
3342 }
3343 if (video_channel() && video_channel()->content_name() == content_name) {
3344 return video_channel();
3345 }
3346 if (rtp_data_channel() &&
3347 rtp_data_channel()->content_name() == content_name) {
3348 return rtp_data_channel();
3349 }
3350 return nullptr;
3351}
3352
3353bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3354 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003355 RTC_LOG(LS_INFO)
3356 << "Local and Remote descriptions must be applied to get the "
3357 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003358 return false;
3359 }
3360 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003361 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3362 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003363 return false;
3364 }
3365
3366 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3367}
3368
3369bool PeerConnection::GetSslRole(const std::string& content_name,
3370 rtc::SSLRole* role) {
3371 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003372 RTC_LOG(LS_INFO)
3373 << "Local and Remote descriptions must be applied to get the "
3374 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003375 return false;
3376 }
3377
3378 return transport_controller_->GetSslRole(GetTransportName(content_name),
3379 role);
3380}
3381
Henrik Boström31638672017-11-23 17:48:32 +01003382bool PeerConnection::SetCurrentOrPendingLocalDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003383 std::unique_ptr<SessionDescriptionInterface> desc,
3384 std::string* err_desc) {
3385 RTC_DCHECK(signaling_thread()->IsCurrent());
3386
3387 // Validate SDP.
3388 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3389 return false;
3390 }
3391
3392 // Update the initial_offerer flag if this session is the initial_offerer.
3393 Action action = GetAction(desc->type());
3394 if (!initial_offerer_.has_value()) {
3395 initial_offerer_.emplace(action == kOffer);
3396 if (*initial_offerer_) {
3397 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3398 } else {
3399 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3400 }
3401 }
3402
3403 if (action == kAnswer) {
3404 current_local_description_ = std::move(desc);
3405 pending_local_description_ = nullptr;
3406 current_remote_description_ = std::move(pending_remote_description_);
3407 } else {
3408 pending_local_description_ = std::move(desc);
3409 }
3410
3411 // Transport and Media channels will be created only when offer is set.
3412 if (action == kOffer && !CreateChannels(local_description()->description())) {
3413 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3414 // is applied. Restore back to old description.
3415 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3416 err_desc);
3417 }
3418
3419 // Remove unused channels if MediaContentDescription is rejected.
3420 RemoveUnusedChannels(local_description()->description());
3421
3422 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3423 return false;
3424 }
3425 if (remote_description()) {
3426 // Now that we have a local description, we can push down remote candidates.
3427 UseCandidatesInSessionDescription(remote_description());
3428 }
3429
3430 pending_ice_restarts_.clear();
Steve Antonf8470812017-12-04 10:46:21 -08003431 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08003432 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3433 err_desc);
3434 }
3435 return true;
3436}
3437
Henrik Boström31638672017-11-23 17:48:32 +01003438bool PeerConnection::SetCurrentOrPendingRemoteDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003439 std::unique_ptr<SessionDescriptionInterface> desc,
3440 std::string* err_desc) {
3441 RTC_DCHECK(signaling_thread()->IsCurrent());
3442
3443 // Validate SDP.
3444 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3445 return false;
3446 }
3447
3448 // Hold this pointer so candidates can be copied to it later in the method.
3449 SessionDescriptionInterface* desc_ptr = desc.get();
3450
3451 const SessionDescriptionInterface* old_remote_description =
3452 remote_description();
3453 // Grab ownership of the description being replaced for the remainder of this
3454 // method, since it's used below as |old_remote_description|.
3455 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3456 Action action = GetAction(desc->type());
3457 if (action == kAnswer) {
3458 replaced_remote_description = pending_remote_description_
3459 ? std::move(pending_remote_description_)
3460 : std::move(current_remote_description_);
3461 current_remote_description_ = std::move(desc);
3462 pending_remote_description_ = nullptr;
3463 current_local_description_ = std::move(pending_local_description_);
3464 } else {
3465 replaced_remote_description = std::move(pending_remote_description_);
3466 pending_remote_description_ = std::move(desc);
3467 }
3468
3469 // Transport and Media channels will be created only when offer is set.
3470 if (action == kOffer &&
3471 !CreateChannels(remote_description()->description())) {
3472 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3473 // is applied. Restore back to old description.
3474 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3475 err_desc);
3476 }
3477
3478 // Remove unused channels if MediaContentDescription is rejected.
3479 RemoveUnusedChannels(remote_description()->description());
3480
3481 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3482 // is called.
3483 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3484 return false;
3485 }
3486
3487 if (local_description() &&
3488 !UseCandidatesInSessionDescription(remote_description())) {
3489 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3490 err_desc);
3491 }
3492
3493 if (old_remote_description) {
3494 for (const cricket::ContentInfo& content :
3495 old_remote_description->description()->contents()) {
3496 // Check if this new SessionDescription contains new ICE ufrag and
3497 // password that indicates the remote peer requests an ICE restart.
3498 // TODO(deadbeef): When we start storing both the current and pending
3499 // remote description, this should reset pending_ice_restarts and compare
3500 // against the current description.
3501 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3502 content.name)) {
3503 if (action == kOffer) {
3504 pending_ice_restarts_.insert(content.name);
3505 }
3506 } else {
3507 // We retain all received candidates only if ICE is not restarted.
3508 // When ICE is restarted, all previous candidates belong to an old
3509 // generation and should not be kept.
3510 // TODO(deadbeef): This goes against the W3C spec which says the remote
3511 // description should only contain candidates from the last set remote
3512 // description plus any candidates added since then. We should remove
3513 // this once we're sure it won't break anything.
3514 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3515 old_remote_description, content.name, desc_ptr);
3516 }
3517 }
3518 }
3519
Steve Antonf8470812017-12-04 10:46:21 -08003520 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08003521 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3522 err_desc);
3523 }
3524
3525 // Set the the ICE connection state to connecting since the connection may
3526 // become writable with peer reflexive candidates before any remote candidate
3527 // is signaled.
3528 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3529 // is to have a new signal the indicates a change in checking state from the
3530 // transport and expose a new checking() member from transport that can be
3531 // read to determine the current checking state. The existing SignalConnecting
3532 // actually means "gathering candidates", so cannot be be used here.
3533 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3534 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3535 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3536 }
3537 return true;
3538}
3539
3540// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3541// vector of BaseChannel pointers instead of separate voice and video channel
3542// vectors. At that point, this will become a simple getter.
3543std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3544 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003545 if (voice_channel()) {
3546 channels.push_back(voice_channel());
3547 }
3548 if (video_channel()) {
3549 channels.push_back(video_channel());
3550 }
Steve Anton75737c02017-11-06 10:37:17 -08003551 if (rtp_data_channel_) {
3552 channels.push_back(rtp_data_channel_);
3553 }
3554 return channels;
3555}
3556
Steve Antonf8470812017-12-04 10:46:21 -08003557void PeerConnection::SetSessionError(SessionError error,
3558 const std::string& error_desc) {
3559 RTC_DCHECK_RUN_ON(signaling_thread());
3560 if (error != session_error_) {
3561 session_error_ = error;
3562 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003563 }
3564}
3565
3566bool PeerConnection::UpdateSessionState(Action action,
3567 cricket::ContentSource source,
3568 std::string* err_desc) {
3569 RTC_DCHECK(signaling_thread()->IsCurrent());
3570
3571 // If there's already a pending error then no state transition should happen.
3572 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003573 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton75737c02017-11-06 10:37:17 -08003574 std::string td_err;
3575 if (action == kOffer) {
3576 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3577 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3578 }
3579 ChangeSignalingState(source == cricket::CS_LOCAL
3580 ? PeerConnectionInterface::kHaveLocalOffer
3581 : PeerConnectionInterface::kHaveRemoteOffer);
3582 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
Steve Antonf8470812017-12-04 10:46:21 -08003583 SetSessionError(SessionError::kContent, *err_desc);
Steve Anton75737c02017-11-06 10:37:17 -08003584 }
Steve Antonf8470812017-12-04 10:46:21 -08003585 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08003586 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3587 }
3588 } else if (action == kPrAnswer) {
3589 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3590 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3591 }
3592 EnableChannels();
3593 ChangeSignalingState(source == cricket::CS_LOCAL
3594 ? PeerConnectionInterface::kHaveLocalPrAnswer
3595 : PeerConnectionInterface::kHaveRemotePrAnswer);
3596 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
Steve Antonf8470812017-12-04 10:46:21 -08003597 SetSessionError(SessionError::kContent, *err_desc);
Steve Anton75737c02017-11-06 10:37:17 -08003598 }
Steve Antonf8470812017-12-04 10:46:21 -08003599 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08003600 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3601 }
3602 } else if (action == kAnswer) {
3603 const cricket::ContentGroup* local_bundle =
3604 local_description()->description()->GetGroupByName(
3605 cricket::GROUP_TYPE_BUNDLE);
3606 const cricket::ContentGroup* remote_bundle =
3607 remote_description()->description()->GetGroupByName(
3608 cricket::GROUP_TYPE_BUNDLE);
3609 if (local_bundle && remote_bundle) {
3610 // The answerer decides the transport to bundle on.
3611 const cricket::ContentGroup* answer_bundle =
3612 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3613 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003614 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003615 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3616 }
3617 }
3618 // Only push down the transport description after enabling BUNDLE; we don't
3619 // want to push down a description on a transport about to be destroyed.
3620 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3621 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3622 }
3623 EnableChannels();
3624 ChangeSignalingState(PeerConnectionInterface::kStable);
3625 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
Steve Antonf8470812017-12-04 10:46:21 -08003626 SetSessionError(SessionError::kContent, *err_desc);
Steve Anton75737c02017-11-06 10:37:17 -08003627 }
Steve Antonf8470812017-12-04 10:46:21 -08003628 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08003629 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3630 }
3631 }
3632 return true;
3633}
3634
3635PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3636 if (type == SessionDescriptionInterface::kOffer) {
3637 return PeerConnection::kOffer;
3638 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3639 return PeerConnection::kPrAnswer;
3640 } else if (type == SessionDescriptionInterface::kAnswer) {
3641 return PeerConnection::kAnswer;
3642 }
3643 RTC_NOTREACHED() << "unknown action type";
3644 return PeerConnection::kOffer;
3645}
3646
3647bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3648 cricket::ContentSource source,
3649 std::string* err) {
3650 const SessionDescription* sdesc =
3651 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3652 ->description();
3653 RTC_DCHECK(sdesc);
3654 bool all_success = true;
3655 for (auto* channel : Channels()) {
3656 // TODO(steveanton): Add support for multiple channels of the same type.
3657 const ContentInfo* content_info =
3658 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3659 if (!content_info) {
3660 continue;
3661 }
3662 const MediaContentDescription* content_desc =
3663 static_cast<const MediaContentDescription*>(content_info->description);
3664 if (content_desc && !content_info->rejected) {
3665 bool success = (source == cricket::CS_LOCAL)
3666 ? channel->SetLocalContent(content_desc, action, err)
3667 : channel->SetRemoteContent(content_desc, action, err);
3668 if (!success) {
3669 all_success = false;
3670 break;
3671 }
3672 }
3673 }
3674 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3675 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3676 if (sctp_transport_ && local_description() && remote_description() &&
3677 cricket::GetFirstDataContent(local_description()->description()) &&
3678 cricket::GetFirstDataContent(remote_description()->description())) {
3679 all_success &= network_thread()->Invoke<bool>(
3680 RTC_FROM_HERE,
3681 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3682 }
3683 return all_success;
3684}
3685
3686bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3687 RTC_DCHECK(network_thread()->IsCurrent());
3688 RTC_DCHECK(local_description());
3689 RTC_DCHECK(remote_description());
3690 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3691 // When we support "max-message-size", that would also be pushed down here.
3692 return sctp_transport_->Start(
3693 GetSctpPort(local_description()->description()),
3694 GetSctpPort(remote_description()->description()));
3695}
3696
3697bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3698 cricket::ContentAction action,
3699 std::string* error_desc) {
3700 RTC_DCHECK(signaling_thread()->IsCurrent());
3701
3702 if (source == cricket::CS_LOCAL) {
3703 return PushdownLocalTransportDescription(local_description()->description(),
3704 action, error_desc);
3705 }
3706 return PushdownRemoteTransportDescription(remote_description()->description(),
3707 action, error_desc);
3708}
3709
3710bool PeerConnection::PushdownLocalTransportDescription(
3711 const SessionDescription* sdesc,
3712 cricket::ContentAction action,
3713 std::string* err) {
3714 RTC_DCHECK(signaling_thread()->IsCurrent());
3715
3716 if (!sdesc) {
3717 return false;
3718 }
3719
3720 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3721 if (!transport_controller_->SetLocalTransportDescription(
3722 tinfo.content_name, tinfo.description, action, err)) {
3723 return false;
3724 }
3725 }
3726
3727 return true;
3728}
3729
3730bool PeerConnection::PushdownRemoteTransportDescription(
3731 const SessionDescription* sdesc,
3732 cricket::ContentAction action,
3733 std::string* err) {
3734 RTC_DCHECK(signaling_thread()->IsCurrent());
3735
3736 if (!sdesc) {
3737 return false;
3738 }
3739
3740 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3741 if (!transport_controller_->SetRemoteTransportDescription(
3742 tinfo.content_name, tinfo.description, action, err)) {
3743 return false;
3744 }
3745 }
3746
3747 return true;
3748}
3749
3750bool PeerConnection::GetTransportDescription(
3751 const SessionDescription* description,
3752 const std::string& content_name,
3753 cricket::TransportDescription* tdesc) {
3754 if (!description || !tdesc) {
3755 return false;
3756 }
3757 const TransportInfo* transport_info =
3758 description->GetTransportInfoByName(content_name);
3759 if (!transport_info) {
3760 return false;
3761 }
3762 *tdesc = transport_info->description;
3763 return true;
3764}
3765
3766bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3767 const std::string* first_content_name = bundle.FirstContentName();
3768 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003769 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003770 return false;
3771 }
3772 const std::string& transport_name = *first_content_name;
3773
3774 auto maybe_set_transport = [this, bundle,
3775 transport_name](cricket::BaseChannel* ch) {
3776 if (!ch || !bundle.HasContentName(ch->content_name())) {
3777 return true;
3778 }
3779
3780 std::string old_transport_name = ch->transport_name();
3781 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003782 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3783 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003784 return true;
3785 }
3786
3787 cricket::DtlsTransportInternal* rtp_dtls_transport =
3788 transport_controller_->CreateDtlsTransport(
3789 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3790 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3791 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3792 if (need_rtcp) {
3793 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3794 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3795 }
3796
3797 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003798 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3799 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003800 transport_controller_->DestroyDtlsTransport(
3801 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3802 // If the channel needs rtcp, it means that the channel used to have a
3803 // rtcp transport which needs to be deleted now.
3804 if (need_rtcp) {
3805 transport_controller_->DestroyDtlsTransport(
3806 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3807 }
3808 return true;
3809 };
3810
3811 if (!maybe_set_transport(voice_channel()) ||
3812 !maybe_set_transport(video_channel()) ||
3813 !maybe_set_transport(rtp_data_channel())) {
3814 return false;
3815 }
3816 // For SCTP, transport creation/deletion happens here instead of in the
3817 // object itself.
3818 if (sctp_transport_) {
3819 RTC_DCHECK(sctp_transport_name_);
3820 RTC_DCHECK(sctp_content_name_);
3821 if (transport_name != *sctp_transport_name_ &&
3822 bundle.HasContentName(*sctp_content_name_)) {
3823 network_thread()->Invoke<void>(
3824 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3825 transport_name));
3826 }
3827 }
3828
3829 return true;
3830}
3831
Steve Anton75737c02017-11-06 10:37:17 -08003832cricket::IceConfig PeerConnection::ParseIceConfig(
3833 const PeerConnectionInterface::RTCConfiguration& config) const {
3834 cricket::ContinualGatheringPolicy gathering_policy;
3835 // TODO(honghaiz): Add the third continual gathering policy in
3836 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3837 switch (config.continual_gathering_policy) {
3838 case PeerConnectionInterface::GATHER_ONCE:
3839 gathering_policy = cricket::GATHER_ONCE;
3840 break;
3841 case PeerConnectionInterface::GATHER_CONTINUALLY:
3842 gathering_policy = cricket::GATHER_CONTINUALLY;
3843 break;
3844 default:
3845 RTC_NOTREACHED();
3846 gathering_policy = cricket::GATHER_ONCE;
3847 }
3848 cricket::IceConfig ice_config;
3849 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3850 ice_config.prioritize_most_likely_candidate_pairs =
3851 config.prioritize_most_likely_ice_candidate_pairs;
3852 ice_config.backup_connection_ping_interval =
3853 config.ice_backup_candidate_pair_ping_interval;
3854 ice_config.continual_gathering_policy = gathering_policy;
3855 ice_config.presume_writable_when_fully_relayed =
3856 config.presume_writable_when_fully_relayed;
3857 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3858 ice_config.regather_all_networks_interval_range =
3859 config.ice_regather_interval_range;
3860 return ice_config;
3861}
3862
Steve Anton75737c02017-11-06 10:37:17 -08003863bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3864 std::string* track_id) {
3865 if (!local_description()) {
3866 return false;
3867 }
3868 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3869 track_id);
3870}
3871
3872bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3873 std::string* track_id) {
3874 if (!remote_description()) {
3875 return false;
3876 }
3877 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3878 track_id);
3879}
3880
3881bool PeerConnection::SendData(const cricket::SendDataParams& params,
3882 const rtc::CopyOnWriteBuffer& payload,
3883 cricket::SendDataResult* result) {
3884 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003885 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3886 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003887 return false;
3888 }
3889 return rtp_data_channel_
3890 ? rtp_data_channel_->SendData(params, payload, result)
3891 : network_thread()->Invoke<bool>(
3892 RTC_FROM_HERE,
3893 Bind(&cricket::SctpTransportInternal::SendData,
3894 sctp_transport_.get(), params, payload, result));
3895}
3896
3897bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3898 if (!rtp_data_channel_ && !sctp_transport_) {
3899 // Don't log an error here, because DataChannels are expected to call
3900 // ConnectDataChannel in this state. It's the only way to initially tell
3901 // whether or not the underlying transport is ready.
3902 return false;
3903 }
3904 if (rtp_data_channel_) {
3905 rtp_data_channel_->SignalReadyToSendData.connect(
3906 webrtc_data_channel, &DataChannel::OnChannelReady);
3907 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3908 &DataChannel::OnDataReceived);
3909 } else {
3910 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3911 &DataChannel::OnChannelReady);
3912 SignalSctpDataReceived.connect(webrtc_data_channel,
3913 &DataChannel::OnDataReceived);
3914 SignalSctpStreamClosedRemotely.connect(
3915 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3916 }
3917 return true;
3918}
3919
3920void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3921 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003922 RTC_LOG(LS_ERROR)
3923 << "DisconnectDataChannel called when rtp_data_channel_ and "
3924 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003925 return;
3926 }
3927 if (rtp_data_channel_) {
3928 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3929 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3930 } else {
3931 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3932 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3933 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3934 }
3935}
3936
3937void PeerConnection::AddSctpDataStream(int sid) {
3938 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003939 RTC_LOG(LS_ERROR)
3940 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003941 return;
3942 }
3943 network_thread()->Invoke<void>(
3944 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3945 sctp_transport_.get(), sid));
3946}
3947
3948void PeerConnection::RemoveSctpDataStream(int sid) {
3949 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003950 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3951 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003952 return;
3953 }
3954 network_thread()->Invoke<void>(
3955 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3956 sctp_transport_.get(), sid));
3957}
3958
3959bool PeerConnection::ReadyToSendData() const {
3960 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3961 sctp_ready_to_send_data_;
3962}
3963
3964std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3965 RTC_DCHECK(signaling_thread()->IsCurrent());
3966 ChannelNamePairs channel_name_pairs;
3967 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003968 channel_name_pairs.voice = ChannelNamePair(
3969 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003970 }
3971 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003972 channel_name_pairs.video = ChannelNamePair(
3973 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003974 }
3975 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003976 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003977 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003978 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003979 }
3980 if (sctp_transport_) {
3981 RTC_DCHECK(sctp_content_name_);
3982 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003983 channel_name_pairs.data =
3984 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003985 }
3986 return GetSessionStats(channel_name_pairs);
3987}
3988
3989std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3990 const ChannelNamePairs& channel_name_pairs) {
3991 if (network_thread()->IsCurrent()) {
3992 return GetSessionStats_n(channel_name_pairs);
3993 }
3994 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3995 RTC_FROM_HERE,
3996 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3997}
3998
3999bool PeerConnection::GetLocalCertificate(
4000 const std::string& transport_name,
4001 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4002 return transport_controller_->GetLocalCertificate(transport_name,
4003 certificate);
4004}
4005
4006std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4007 const std::string& transport_name) {
4008 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4009}
4010
4011cricket::DataChannelType PeerConnection::data_channel_type() const {
4012 return data_channel_type_;
4013}
4014
4015bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4016 return pending_ice_restarts_.find(content_name) !=
4017 pending_ice_restarts_.end();
4018}
4019
Steve Anton75737c02017-11-06 10:37:17 -08004020bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4021 return transport_controller_->NeedsIceRestart(content_name);
4022}
4023
4024void PeerConnection::OnCertificateReady(
4025 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4026 transport_controller_->SetLocalCertificate(certificate);
4027}
4028
4029void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004030 SetSessionError(SessionError::kTransport,
4031 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004032}
4033
4034void PeerConnection::OnTransportControllerConnectionState(
4035 cricket::IceConnectionState state) {
4036 switch (state) {
4037 case cricket::kIceConnectionConnecting:
4038 // If the current state is Connected or Completed, then there were
4039 // writable channels but now there are not, so the next state must
4040 // be Disconnected.
4041 // kIceConnectionConnecting is currently used as the default,
4042 // un-connected state by the TransportController, so its only use is
4043 // detecting disconnections.
4044 if (ice_connection_state_ ==
4045 PeerConnectionInterface::kIceConnectionConnected ||
4046 ice_connection_state_ ==
4047 PeerConnectionInterface::kIceConnectionCompleted) {
4048 SetIceConnectionState(
4049 PeerConnectionInterface::kIceConnectionDisconnected);
4050 }
4051 break;
4052 case cricket::kIceConnectionFailed:
4053 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4054 break;
4055 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004056 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4057 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004058 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4059 break;
4060 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004061 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4062 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004063 if (ice_connection_state_ !=
4064 PeerConnectionInterface::kIceConnectionConnected) {
4065 // If jumping directly from "checking" to "connected",
4066 // signal "connected" first.
4067 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4068 }
4069 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4070 if (metrics_observer()) {
4071 ReportTransportStats();
4072 }
4073 break;
4074 default:
4075 RTC_NOTREACHED();
4076 }
4077}
4078
4079void PeerConnection::OnTransportControllerCandidatesGathered(
4080 const std::string& transport_name,
4081 const cricket::Candidates& candidates) {
4082 RTC_DCHECK(signaling_thread()->IsCurrent());
4083 int sdp_mline_index;
4084 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004085 RTC_LOG(LS_ERROR)
4086 << "OnTransportControllerCandidatesGathered: content name "
4087 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004088 return;
4089 }
4090
4091 for (cricket::Candidates::const_iterator citer = candidates.begin();
4092 citer != candidates.end(); ++citer) {
4093 // Use transport_name as the candidate media id.
4094 std::unique_ptr<JsepIceCandidate> candidate(
4095 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4096 if (local_description()) {
4097 mutable_local_description()->AddCandidate(candidate.get());
4098 }
4099 OnIceCandidate(std::move(candidate));
4100 }
4101}
4102
4103void PeerConnection::OnTransportControllerCandidatesRemoved(
4104 const std::vector<cricket::Candidate>& candidates) {
4105 RTC_DCHECK(signaling_thread()->IsCurrent());
4106 // Sanity check.
4107 for (const cricket::Candidate& candidate : candidates) {
4108 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4110 << "empty content name in candidate "
4111 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004112 return;
4113 }
4114 }
4115
4116 if (local_description()) {
4117 mutable_local_description()->RemoveCandidates(candidates);
4118 }
4119 OnIceCandidatesRemoved(candidates);
4120}
4121
4122void PeerConnection::OnTransportControllerDtlsHandshakeError(
4123 rtc::SSLHandshakeError error) {
4124 if (metrics_observer()) {
4125 metrics_observer()->IncrementEnumCounter(
4126 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4127 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4128 }
4129}
4130
4131// Enabling voice and video (and RTP data) channels.
4132void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004133 if (voice_channel() && !voice_channel()->enabled()) {
4134 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004135 }
4136
Steve Anton4171afb2017-11-20 10:20:22 -08004137 if (video_channel() && !video_channel()->enabled()) {
4138 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004139 }
4140
Steve Anton4171afb2017-11-20 10:20:22 -08004141 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004142 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004143 }
Steve Anton75737c02017-11-06 10:37:17 -08004144}
4145
4146// Returns the media index for a local ice candidate given the content name.
4147bool PeerConnection::GetLocalCandidateMediaIndex(
4148 const std::string& content_name,
4149 int* sdp_mline_index) {
4150 if (!local_description() || !sdp_mline_index) {
4151 return false;
4152 }
4153
4154 bool content_found = false;
4155 const ContentInfos& contents = local_description()->description()->contents();
4156 for (size_t index = 0; index < contents.size(); ++index) {
4157 if (contents[index].name == content_name) {
4158 *sdp_mline_index = static_cast<int>(index);
4159 content_found = true;
4160 break;
4161 }
4162 }
4163 return content_found;
4164}
4165
4166bool PeerConnection::UseCandidatesInSessionDescription(
4167 const SessionDescriptionInterface* remote_desc) {
4168 if (!remote_desc) {
4169 return true;
4170 }
4171 bool ret = true;
4172
4173 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4174 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4175 for (size_t n = 0; n < candidates->count(); ++n) {
4176 const IceCandidateInterface* candidate = candidates->at(n);
4177 bool valid = false;
4178 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4179 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004180 RTC_LOG(LS_INFO)
4181 << "UseCandidatesInSessionDescription: Not ready to use "
4182 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004183 }
4184 continue;
4185 }
4186 ret = UseCandidate(candidate);
4187 if (!ret) {
4188 break;
4189 }
4190 }
4191 }
4192 return ret;
4193}
4194
4195bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4196 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4197 size_t remote_content_size =
4198 remote_description()->description()->contents().size();
4199 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004200 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004201 return false;
4202 }
4203
4204 cricket::ContentInfo content =
4205 remote_description()->description()->contents()[mediacontent_index];
4206 std::vector<cricket::Candidate> candidates;
4207 candidates.push_back(candidate->candidate());
4208 // Invoking BaseSession method to handle remote candidates.
4209 std::string error;
4210 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4211 &error)) {
4212 // Candidates successfully submitted for checking.
4213 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4214 ice_connection_state_ ==
4215 PeerConnectionInterface::kIceConnectionDisconnected) {
4216 // If state is New, then the session has just gotten its first remote ICE
4217 // candidates, so go to Checking.
4218 // If state is Disconnected, the session is re-using old candidates or
4219 // receiving additional ones, so go to Checking.
4220 // If state is Connected, stay Connected.
4221 // TODO(bemasc): If state is Connected, and the new candidates are for a
4222 // newly added transport, then the state actually _should_ move to
4223 // checking. Add a way to distinguish that case.
4224 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4225 }
4226 // TODO(bemasc): If state is Completed, go back to Connected.
4227 } else {
4228 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004229 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004230 }
4231 }
4232 return true;
4233}
4234
4235void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004236 // Destroy video channel first since it may have a pointer to the
4237 // voice channel.
4238 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004239 if (!video_info || video_info->rejected) {
4240 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004241 }
4242
Steve Anton6fec8802017-12-04 10:37:29 -08004243 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4244 if (!audio_info || audio_info->rejected) {
4245 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004246 }
4247
4248 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4249 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004250 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004251 }
4252}
4253
Steve Antoneda6ccd2017-12-04 10:21:55 -08004254std::string PeerConnection::GetTransportNameForMediaSection(
4255 const std::string& mid,
4256 const cricket::ContentGroup* bundle_group) const {
4257 if (!bundle_group) {
4258 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004259 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004260 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004261 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004262 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004263 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004264 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004265 if (!bundle_group->HasContentName(mid)) {
4266 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4267 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004268 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004269 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4270 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004271}
4272
4273bool PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004274 RTC_DCHECK(desc);
4275
Steve Anton75737c02017-11-06 10:37:17 -08004276 const cricket::ContentGroup* bundle_group = nullptr;
4277 if (configuration_.bundle_policy ==
4278 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4279 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4280 if (!bundle_group) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004281 RTC_LOG(LS_WARNING) << "max-bundle configured but session description "
4282 "has no BUNDLE group";
Steve Anton75737c02017-11-06 10:37:17 -08004283 return false;
4284 }
4285 }
4286
Steve Antoneda6ccd2017-12-04 10:21:55 -08004287 // Creating the media channels and transport proxies.
4288 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4289 if (voice && !voice->rejected &&
4290 !GetAudioTransceiver()->internal()->channel()) {
4291 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4292 voice->name,
4293 GetTransportNameForMediaSection(voice->name, bundle_group));
4294 if (!voice_channel) {
4295 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
4296 return false;
4297 }
4298 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4299 }
4300
Steve Anton75737c02017-11-06 10:37:17 -08004301 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004302 if (video && !video->rejected &&
4303 !GetVideoTransceiver()->internal()->channel()) {
4304 cricket::VideoChannel* video_channel = CreateVideoChannel(
4305 video->name,
4306 GetTransportNameForMediaSection(video->name, bundle_group));
4307 if (!video_channel) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004309 return false;
4310 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004311 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004312 }
4313
4314 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4315 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4316 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004317 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4318 data->name, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004320 return false;
4321 }
4322 }
4323
4324 return true;
4325}
4326
Steve Anton4171afb2017-11-20 10:20:22 -08004327// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004328cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4329 const std::string& mid,
4330 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004331 cricket::DtlsTransportInternal* rtp_dtls_transport =
4332 transport_controller_->CreateDtlsTransport(
4333 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4334 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4335 if (configuration_.rtcp_mux_policy !=
4336 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4337 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4338 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4339 }
4340
4341 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4342 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004343 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4344 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004345 if (!voice_channel) {
4346 transport_controller_->DestroyDtlsTransport(
4347 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4348 if (rtcp_dtls_transport) {
4349 transport_controller_->DestroyDtlsTransport(
4350 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4351 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004352 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004353 }
Steve Anton75737c02017-11-06 10:37:17 -08004354 voice_channel->SignalRtcpMuxFullyActive.connect(
4355 this, &PeerConnection::DestroyRtcpTransport_n);
4356 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4357 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004358 voice_channel->SignalSentPacket.connect(this,
4359 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004360
Steve Antoneda6ccd2017-12-04 10:21:55 -08004361 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004362}
4363
Steve Anton4171afb2017-11-20 10:20:22 -08004364// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004365cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4366 const std::string& mid,
4367 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004368 cricket::DtlsTransportInternal* rtp_dtls_transport =
4369 transport_controller_->CreateDtlsTransport(
4370 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4371 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4372 if (configuration_.rtcp_mux_policy !=
4373 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4374 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4375 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4376 }
4377
4378 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4379 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004380 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4381 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004382
4383 if (!video_channel) {
4384 transport_controller_->DestroyDtlsTransport(
4385 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4386 if (rtcp_dtls_transport) {
4387 transport_controller_->DestroyDtlsTransport(
4388 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4389 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004390 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004391 }
Steve Anton75737c02017-11-06 10:37:17 -08004392 video_channel->SignalRtcpMuxFullyActive.connect(
4393 this, &PeerConnection::DestroyRtcpTransport_n);
4394 video_channel->SignalDtlsSrtpSetupFailure.connect(
4395 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004396 video_channel->SignalSentPacket.connect(this,
4397 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004398
Steve Antoneda6ccd2017-12-04 10:21:55 -08004399 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004400}
4401
Steve Antoneda6ccd2017-12-04 10:21:55 -08004402bool PeerConnection::CreateDataChannel(const std::string& mid,
4403 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004404 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4405 if (sctp) {
4406 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004407 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004408 << "Trying to create SCTP transport, but didn't compile with "
4409 "SCTP support (HAVE_SCTP)";
4410 return false;
4411 }
4412 if (!network_thread()->Invoke<bool>(
4413 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004414 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004415 return false;
4416 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004417 for (const auto& channel : sctp_data_channels_) {
4418 channel->OnTransportChannelCreated();
4419 }
Steve Anton75737c02017-11-06 10:37:17 -08004420 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004421 cricket::DtlsTransportInternal* rtp_dtls_transport =
4422 transport_controller_->CreateDtlsTransport(
4423 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4424 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4425 if (configuration_.rtcp_mux_policy !=
4426 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4427 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4428 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4429 }
4430
4431 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4432 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004433 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004434
4435 if (!rtp_data_channel_) {
4436 transport_controller_->DestroyDtlsTransport(
4437 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4438 if (rtcp_dtls_transport) {
4439 transport_controller_->DestroyDtlsTransport(
4440 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4441 }
4442 return false;
4443 }
4444
4445 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4446 this, &PeerConnection::DestroyRtcpTransport_n);
4447 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4448 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4449 rtp_data_channel_->SignalSentPacket.connect(
4450 this, &PeerConnection::OnSentPacket_w);
4451 }
4452
Steve Anton75737c02017-11-06 10:37:17 -08004453 return true;
4454}
4455
4456Call::Stats PeerConnection::GetCallStats() {
4457 if (!worker_thread()->IsCurrent()) {
4458 return worker_thread()->Invoke<Call::Stats>(
4459 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4460 }
4461 if (call_) {
4462 return call_->GetStats();
4463 } else {
4464 return Call::Stats();
4465 }
4466}
4467
4468std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4469 const ChannelNamePairs& channel_name_pairs) {
4470 RTC_DCHECK(network_thread()->IsCurrent());
4471 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4472 for (const auto channel_name_pair :
4473 {&channel_name_pairs.voice, &channel_name_pairs.video,
4474 &channel_name_pairs.data}) {
4475 if (*channel_name_pair) {
4476 cricket::TransportStats transport_stats;
4477 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4478 &transport_stats)) {
4479 return nullptr;
4480 }
4481 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4482 (*channel_name_pair)->transport_name;
4483 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4484 std::move(transport_stats);
4485 }
4486 }
4487 return session_stats;
4488}
4489
4490bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4491 const std::string& transport_name) {
4492 RTC_DCHECK(network_thread()->IsCurrent());
4493 RTC_DCHECK(sctp_factory_);
4494 cricket::DtlsTransportInternal* tc =
4495 transport_controller_->CreateDtlsTransport_n(
4496 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4497 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4498 RTC_DCHECK(sctp_transport_);
4499 sctp_invoker_.reset(new rtc::AsyncInvoker());
4500 sctp_transport_->SignalReadyToSendData.connect(
4501 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4502 sctp_transport_->SignalDataReceived.connect(
4503 this, &PeerConnection::OnSctpTransportDataReceived_n);
4504 sctp_transport_->SignalStreamClosedRemotely.connect(
4505 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004506 sctp_transport_name_ = transport_name;
4507 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004508 return true;
4509}
4510
4511void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4512 RTC_DCHECK(network_thread()->IsCurrent());
4513 RTC_DCHECK(sctp_transport_);
4514 RTC_DCHECK(sctp_transport_name_);
4515 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004516 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004517 cricket::DtlsTransportInternal* tc =
4518 transport_controller_->CreateDtlsTransport_n(
4519 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4520 sctp_transport_->SetTransportChannel(tc);
4521 transport_controller_->DestroyDtlsTransport_n(
4522 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4523}
4524
4525void PeerConnection::DestroySctpTransport_n() {
4526 RTC_DCHECK(network_thread()->IsCurrent());
4527 sctp_transport_.reset(nullptr);
4528 sctp_content_name_.reset();
4529 sctp_transport_name_.reset();
4530 sctp_invoker_.reset(nullptr);
4531 sctp_ready_to_send_data_ = false;
4532}
4533
4534void PeerConnection::OnSctpTransportReadyToSendData_n() {
4535 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4536 RTC_DCHECK(network_thread()->IsCurrent());
4537 // Note: Cannot use rtc::Bind here because it will grab a reference to
4538 // PeerConnection and potentially cause PeerConnection to live longer than
4539 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4540 // be destroyed before PeerConnection is destroyed, and at that point all
4541 // pending tasks will be cleared.
4542 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4543 OnSctpTransportReadyToSendData_s(true);
4544 });
4545}
4546
4547void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4548 RTC_DCHECK(signaling_thread()->IsCurrent());
4549 sctp_ready_to_send_data_ = ready;
4550 SignalSctpReadyToSendData(ready);
4551}
4552
4553void PeerConnection::OnSctpTransportDataReceived_n(
4554 const cricket::ReceiveDataParams& params,
4555 const rtc::CopyOnWriteBuffer& payload) {
4556 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4557 RTC_DCHECK(network_thread()->IsCurrent());
4558 // Note: Cannot use rtc::Bind here because it will grab a reference to
4559 // PeerConnection and potentially cause PeerConnection to live longer than
4560 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4561 // be destroyed before PeerConnection is destroyed, and at that point all
4562 // pending tasks will be cleared.
4563 sctp_invoker_->AsyncInvoke<void>(
4564 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4565 OnSctpTransportDataReceived_s(params, payload);
4566 });
4567}
4568
4569void PeerConnection::OnSctpTransportDataReceived_s(
4570 const cricket::ReceiveDataParams& params,
4571 const rtc::CopyOnWriteBuffer& payload) {
4572 RTC_DCHECK(signaling_thread()->IsCurrent());
4573 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4574 // Received OPEN message; parse and signal that a new data channel should
4575 // be created.
4576 std::string label;
4577 InternalDataChannelInit config;
4578 config.id = params.ssrc;
4579 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004580 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4581 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004582 return;
4583 }
4584 config.open_handshake_role = InternalDataChannelInit::kAcker;
4585 OnDataChannelOpenMessage(label, config);
4586 } else {
4587 // Otherwise just forward the signal.
4588 SignalSctpDataReceived(params, payload);
4589 }
4590}
4591
4592void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4593 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4594 RTC_DCHECK(network_thread()->IsCurrent());
4595 sctp_invoker_->AsyncInvoke<void>(
4596 RTC_FROM_HERE, signaling_thread(),
4597 rtc::Bind(&sigslot::signal1<int>::operator(),
4598 &SignalSctpStreamClosedRemotely, sid));
4599}
4600
4601// Returns false if bundle is enabled and rtcp_mux is disabled.
4602bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4603 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4604 if (!bundle_enabled)
4605 return true;
4606
4607 const cricket::ContentGroup* bundle_group =
4608 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4609 RTC_DCHECK(bundle_group != NULL);
4610
4611 const cricket::ContentInfos& contents = desc->contents();
4612 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4613 citer != contents.end(); ++citer) {
4614 const cricket::ContentInfo* content = (&*citer);
4615 RTC_DCHECK(content != NULL);
4616 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4617 content->type == cricket::NS_JINGLE_RTP) {
4618 if (!HasRtcpMuxEnabled(content))
4619 return false;
4620 }
4621 }
4622 // RTCP-MUX is enabled in all the contents.
4623 return true;
4624}
4625
4626bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4627 const cricket::MediaContentDescription* description =
4628 static_cast<cricket::MediaContentDescription*>(content->description);
4629 return description->rtcp_mux();
4630}
4631
4632bool PeerConnection::ValidateSessionDescription(
4633 const SessionDescriptionInterface* sdesc,
4634 cricket::ContentSource source,
4635 std::string* err_desc) {
4636 std::string type;
Steve Antonf8470812017-12-04 10:46:21 -08004637 if (session_error() != SessionError::kNone) {
Steve Anton75737c02017-11-06 10:37:17 -08004638 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4639 }
4640
4641 if (!sdesc || !sdesc->description()) {
4642 return BadSdp(source, type, kInvalidSdp, err_desc);
4643 }
4644
4645 type = sdesc->type();
4646 Action action = GetAction(sdesc->type());
4647 if (source == cricket::CS_LOCAL) {
4648 if (!ExpectSetLocalDescription(action))
4649 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4650 } else {
4651 if (!ExpectSetRemoteDescription(action))
4652 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4653 }
4654
4655 // Verify crypto settings.
4656 std::string crypto_error;
4657 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4658 dtls_enabled_) &&
4659 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4660 return BadSdp(source, type, crypto_error, err_desc);
4661 }
4662
4663 // Verify ice-ufrag and ice-pwd.
4664 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4665 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4666 }
4667
4668 if (!ValidateBundleSettings(sdesc->description())) {
4669 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4670 }
4671
4672 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4673 // m-lines that do not rtcp-mux enabled.
4674
4675 // Verify m-lines in Answer when compared against Offer.
4676 if (action == kAnswer || action == kPrAnswer) {
4677 const cricket::SessionDescription* offer_desc =
4678 (source == cricket::CS_LOCAL) ? remote_description()->description()
4679 : local_description()->description();
4680 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4681 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4682 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4683 }
4684 } else {
4685 const cricket::SessionDescription* current_desc = nullptr;
4686 if (source == cricket::CS_LOCAL && local_description()) {
4687 current_desc = local_description()->description();
4688 } else if (source == cricket::CS_REMOTE && remote_description()) {
4689 current_desc = remote_description()->description();
4690 }
4691 // The re-offers should respect the order of m= sections in current
4692 // description. See RFC3264 Section 8 paragraph 4 for more details.
4693 if (current_desc &&
4694 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4695 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4696 }
4697 }
4698
4699 return true;
4700}
4701
4702bool PeerConnection::ExpectSetLocalDescription(Action action) {
4703 PeerConnectionInterface::SignalingState state = signaling_state();
4704 if (action == kOffer) {
4705 return (state == PeerConnectionInterface::kStable) ||
4706 (state == PeerConnectionInterface::kHaveLocalOffer);
4707 } else { // Answer or PrAnswer
4708 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4709 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4710 }
4711}
4712
4713bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4714 PeerConnectionInterface::SignalingState state = signaling_state();
4715 if (action == kOffer) {
4716 return (state == PeerConnectionInterface::kStable) ||
4717 (state == PeerConnectionInterface::kHaveRemoteOffer);
4718 } else { // Answer or PrAnswer.
4719 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4720 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4721 }
4722}
4723
Steve Antonf8470812017-12-04 10:46:21 -08004724const char* PeerConnection::SessionErrorToString(SessionError error) const {
4725 switch (error) {
4726 case SessionError::kNone:
4727 return "ERROR_NONE";
4728 case SessionError::kContent:
4729 return "ERROR_CONTENT";
4730 case SessionError::kTransport:
4731 return "ERROR_TRANSPORT";
4732 }
4733 RTC_NOTREACHED();
4734 return "";
4735}
4736
Steve Anton75737c02017-11-06 10:37:17 -08004737std::string PeerConnection::GetSessionErrorMsg() {
4738 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004739 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4740 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004741 return desc.str();
4742}
4743
4744// We need to check the local/remote description for the Transport instead of
4745// the session, because a new Transport added during renegotiation may have
4746// them unset while the session has them set from the previous negotiation.
4747// Not doing so may trigger the auto generation of transport description and
4748// mess up DTLS identity information, ICE credential, etc.
4749bool PeerConnection::ReadyToUseRemoteCandidate(
4750 const IceCandidateInterface* candidate,
4751 const SessionDescriptionInterface* remote_desc,
4752 bool* valid) {
4753 *valid = true;
4754
4755 const SessionDescriptionInterface* current_remote_desc =
4756 remote_desc ? remote_desc : remote_description();
4757
4758 if (!current_remote_desc) {
4759 return false;
4760 }
4761
4762 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4763 size_t remote_content_size =
4764 current_remote_desc->description()->contents().size();
4765 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004766 RTC_LOG(LS_ERROR)
4767 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4768 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004769
4770 *valid = false;
4771 return false;
4772 }
4773
4774 cricket::ContentInfo content =
4775 current_remote_desc->description()->contents()[mediacontent_index];
4776
4777 const std::string transport_name = GetTransportName(content.name);
4778 if (transport_name.empty()) {
4779 return false;
4780 }
4781 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4782}
4783
4784bool PeerConnection::SrtpRequired() const {
4785 return dtls_enabled_ ||
4786 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4787}
4788
4789void PeerConnection::OnTransportControllerGatheringState(
4790 cricket::IceGatheringState state) {
4791 RTC_DCHECK(signaling_thread()->IsCurrent());
4792 if (state == cricket::kIceGatheringGathering) {
4793 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4794 } else if (state == cricket::kIceGatheringComplete) {
4795 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4796 }
4797}
4798
4799void PeerConnection::ReportTransportStats() {
4800 // Use a set so we don't report the same stats twice if two channels share
4801 // a transport.
4802 std::set<std::string> transport_names;
4803 if (voice_channel()) {
4804 transport_names.insert(voice_channel()->transport_name());
4805 }
4806 if (video_channel()) {
4807 transport_names.insert(video_channel()->transport_name());
4808 }
4809 if (rtp_data_channel()) {
4810 transport_names.insert(rtp_data_channel()->transport_name());
4811 }
4812 if (sctp_transport_name_) {
4813 transport_names.insert(*sctp_transport_name_);
4814 }
4815 for (const auto& name : transport_names) {
4816 cricket::TransportStats stats;
4817 if (transport_controller_->GetStats(name, &stats)) {
4818 ReportBestConnectionState(stats);
4819 ReportNegotiatedCiphers(stats);
4820 }
4821 }
4822}
4823// Walk through the ConnectionInfos to gather best connection usage
4824// for IPv4 and IPv6.
4825void PeerConnection::ReportBestConnectionState(
4826 const cricket::TransportStats& stats) {
4827 RTC_DCHECK(metrics_observer());
4828 for (cricket::TransportChannelStatsList::const_iterator it =
4829 stats.channel_stats.begin();
4830 it != stats.channel_stats.end(); ++it) {
4831 for (cricket::ConnectionInfos::const_iterator it_info =
4832 it->connection_infos.begin();
4833 it_info != it->connection_infos.end(); ++it_info) {
4834 if (!it_info->best_connection) {
4835 continue;
4836 }
4837
4838 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4839 const cricket::Candidate& local = it_info->local_candidate;
4840 const cricket::Candidate& remote = it_info->remote_candidate;
4841
4842 // Increment the counter for IceCandidatePairType.
4843 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4844 (local.type() == RELAY_PORT_TYPE &&
4845 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4846 type = kEnumCounterIceCandidatePairTypeTcp;
4847 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4848 type = kEnumCounterIceCandidatePairTypeUdp;
4849 } else {
4850 RTC_CHECK(0);
4851 }
4852 metrics_observer()->IncrementEnumCounter(
4853 type, GetIceCandidatePairCounter(local, remote),
4854 kIceCandidatePairMax);
4855
4856 // Increment the counter for IP type.
4857 if (local.address().family() == AF_INET) {
4858 metrics_observer()->IncrementEnumCounter(
4859 kEnumCounterAddressFamily, kBestConnections_IPv4,
4860 kPeerConnectionAddressFamilyCounter_Max);
4861
4862 } else if (local.address().family() == AF_INET6) {
4863 metrics_observer()->IncrementEnumCounter(
4864 kEnumCounterAddressFamily, kBestConnections_IPv6,
4865 kPeerConnectionAddressFamilyCounter_Max);
4866 } else {
4867 RTC_CHECK(0);
4868 }
4869
4870 return;
4871 }
4872 }
4873}
4874
4875void PeerConnection::ReportNegotiatedCiphers(
4876 const cricket::TransportStats& stats) {
4877 RTC_DCHECK(metrics_observer());
4878 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4879 return;
4880 }
4881
4882 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4883 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4884 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4885 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4886 return;
4887 }
4888
4889 PeerConnectionEnumCounterType srtp_counter_type;
4890 PeerConnectionEnumCounterType ssl_counter_type;
4891 if (stats.transport_name == cricket::CN_AUDIO) {
4892 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4893 ssl_counter_type = kEnumCounterAudioSslCipher;
4894 } else if (stats.transport_name == cricket::CN_VIDEO) {
4895 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4896 ssl_counter_type = kEnumCounterVideoSslCipher;
4897 } else if (stats.transport_name == cricket::CN_DATA) {
4898 srtp_counter_type = kEnumCounterDataSrtpCipher;
4899 ssl_counter_type = kEnumCounterDataSslCipher;
4900 } else {
4901 RTC_NOTREACHED();
4902 return;
4903 }
4904
4905 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4906 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4907 srtp_crypto_suite);
4908 }
4909 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4910 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4911 ssl_cipher_suite);
4912 }
4913}
4914
4915void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4916 RTC_DCHECK(worker_thread()->IsCurrent());
4917 RTC_DCHECK(call_);
4918 call_->OnSentPacket(sent_packet);
4919}
4920
4921const std::string PeerConnection::GetTransportName(
4922 const std::string& content_name) {
4923 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004924 if (channel) {
4925 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004926 }
Steve Anton6fec8802017-12-04 10:37:29 -08004927 if (sctp_transport_) {
4928 RTC_DCHECK(sctp_content_name_);
4929 RTC_DCHECK(sctp_transport_name_);
4930 if (content_name == *sctp_content_name_) {
4931 return *sctp_transport_name_;
4932 }
4933 }
4934 // Return an empty string if failed to retrieve the transport name.
4935 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004936}
4937
4938void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4939 RTC_DCHECK(network_thread()->IsCurrent());
4940 transport_controller_->DestroyDtlsTransport_n(
4941 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4942}
4943
Steve Anton6fec8802017-12-04 10:37:29 -08004944void PeerConnection::DestroyTransceiverChannel(
4945 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4946 transceiver) {
4947 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004948
Steve Anton6fec8802017-12-04 10:37:29 -08004949 cricket::BaseChannel* channel = transceiver->internal()->channel();
4950 if (channel) {
4951 transceiver->internal()->SetChannel(nullptr);
4952 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004953 }
4954}
4955
4956void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004957 if (rtp_data_channel_) {
4958 OnDataChannelDestroyed();
4959 DestroyBaseChannel(rtp_data_channel_);
4960 rtp_data_channel_ = nullptr;
4961 }
4962
4963 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4964 // grab a reference to this PeerConnection. If this is called from the
4965 // PeerConnection destructor, the RefCountedObject vtable will have already
4966 // been destroyed (since it is a subclass of PeerConnection) and using
4967 // rtc::Bind will cause "Pure virtual function called" error to appear.
4968
4969 if (sctp_transport_) {
4970 OnDataChannelDestroyed();
4971 network_thread()->Invoke<void>(RTC_FROM_HERE,
4972 [this] { DestroySctpTransport_n(); });
4973 }
4974}
4975
4976void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4977 RTC_DCHECK(channel);
4978 RTC_DCHECK(channel->rtp_dtls_transport());
4979
4980 // Need to cache these before destroying the base channel so that we do not
4981 // access uninitialized memory.
4982 const std::string transport_name =
4983 channel->rtp_dtls_transport()->transport_name();
4984 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4985
4986 switch (channel->media_type()) {
4987 case cricket::MEDIA_TYPE_AUDIO:
4988 channel_manager()->DestroyVoiceChannel(
4989 static_cast<cricket::VoiceChannel*>(channel));
4990 break;
4991 case cricket::MEDIA_TYPE_VIDEO:
4992 channel_manager()->DestroyVideoChannel(
4993 static_cast<cricket::VideoChannel*>(channel));
4994 break;
4995 case cricket::MEDIA_TYPE_DATA:
4996 channel_manager()->DestroyRtpDataChannel(
4997 static_cast<cricket::RtpDataChannel*>(channel));
4998 break;
4999 default:
5000 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5001 break;
5002 }
5003
5004 // |channel| can no longer be used.
5005
Steve Anton75737c02017-11-06 10:37:17 -08005006 transport_controller_->DestroyDtlsTransport(
5007 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5008 if (need_to_delete_rtcp) {
5009 transport_controller_->DestroyDtlsTransport(
5010 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5011 }
5012}
5013
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005014} // namespace webrtc