blob: 0011ad726f5812ffe949a8b709559d5d2789a80c [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
151bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
152 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
160 return MediaContentDirectionHasSend(desc->direction())
161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
176 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 } else {
184 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
185 if (video_media_description_options) {
186 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700187 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700188 }
189 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700190 }
zhihuang1c378ed2017-08-17 14:10:50 -0700191}
olka3c747662017-08-17 06:50:32 -0700192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |session_options| from |rtp_data_channels|.
194void AddRtpDataChannelOptions(
195 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
196 rtp_data_channels,
197 cricket::MediaDescriptionOptions* data_media_description_options) {
198 if (!data_media_description_options) {
199 return;
200 }
deadbeefab9b2d12015-10-14 11:33:11 -0700201 // Check for data channels.
202 for (const auto& kv : rtp_data_channels) {
203 const DataChannel* channel = kv.second;
204 if (channel->state() == DataChannel::kConnecting ||
205 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700206 // Legacy RTP data channels are signaled with the track/stream ID set to
207 // the data channel's label.
208 data_media_description_options->AddRtpDataChannel(channel->label(),
209 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700210 }
211 }
212}
213
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700214uint32_t ConvertIceTransportTypeToCandidateFilter(
215 PeerConnectionInterface::IceTransportsType type) {
216 switch (type) {
217 case PeerConnectionInterface::kNone:
218 return cricket::CF_NONE;
219 case PeerConnectionInterface::kRelay:
220 return cricket::CF_RELAY;
221 case PeerConnectionInterface::kNoHost:
222 return (cricket::CF_ALL & ~cricket::CF_HOST);
223 case PeerConnectionInterface::kAll:
224 return cricket::CF_ALL;
225 default:
nissec80e7412017-01-11 05:56:46 -0800226 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700227 }
228 return cricket::CF_NONE;
229}
230
deadbeef293e9262017-01-11 12:28:30 -0800231// Helper to set an error and return from a method.
232bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
233 if (error) {
234 error->set_type(type);
235 }
236 return type == webrtc::RTCErrorType::NONE;
237}
238
Steve Anton038834f2017-07-14 15:59:59 -0700239bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
240 if (error_out) {
241 *error_out = std::move(error);
242 }
243 return error.ok();
244}
245
Steve Antonba818672017-11-06 10:21:57 -0800246std::string GetSignalingStateString(
247 PeerConnectionInterface::SignalingState state) {
248 switch (state) {
249 case PeerConnectionInterface::kStable:
250 return "kStable";
251 case PeerConnectionInterface::kHaveLocalOffer:
252 return "kHaveLocalOffer";
253 case PeerConnectionInterface::kHaveLocalPrAnswer:
254 return "kHavePrAnswer";
255 case PeerConnectionInterface::kHaveRemoteOffer:
256 return "kHaveRemoteOffer";
257 case PeerConnectionInterface::kHaveRemotePrAnswer:
258 return "kHaveRemotePrAnswer";
259 case PeerConnectionInterface::kClosed:
260 return "kClosed";
261 }
262 RTC_NOTREACHED();
263 return "";
264}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265
Steve Anton75737c02017-11-06 10:37:17 -0800266IceCandidatePairType GetIceCandidatePairCounter(
267 const cricket::Candidate& local,
268 const cricket::Candidate& remote) {
269 const auto& l = local.type();
270 const auto& r = remote.type();
271 const auto& host = LOCAL_PORT_TYPE;
272 const auto& srflx = STUN_PORT_TYPE;
273 const auto& relay = RELAY_PORT_TYPE;
274 const auto& prflx = PRFLX_PORT_TYPE;
275 if (l == host && r == host) {
276 bool local_private = IPIsPrivate(local.address().ipaddr());
277 bool remote_private = IPIsPrivate(remote.address().ipaddr());
278 if (local_private) {
279 if (remote_private) {
280 return kIceCandidatePairHostPrivateHostPrivate;
281 } else {
282 return kIceCandidatePairHostPrivateHostPublic;
283 }
284 } else {
285 if (remote_private) {
286 return kIceCandidatePairHostPublicHostPrivate;
287 } else {
288 return kIceCandidatePairHostPublicHostPublic;
289 }
290 }
291 }
292 if (l == host && r == srflx)
293 return kIceCandidatePairHostSrflx;
294 if (l == host && r == relay)
295 return kIceCandidatePairHostRelay;
296 if (l == host && r == prflx)
297 return kIceCandidatePairHostPrflx;
298 if (l == srflx && r == host)
299 return kIceCandidatePairSrflxHost;
300 if (l == srflx && r == srflx)
301 return kIceCandidatePairSrflxSrflx;
302 if (l == srflx && r == relay)
303 return kIceCandidatePairSrflxRelay;
304 if (l == srflx && r == prflx)
305 return kIceCandidatePairSrflxPrflx;
306 if (l == relay && r == host)
307 return kIceCandidatePairRelayHost;
308 if (l == relay && r == srflx)
309 return kIceCandidatePairRelaySrflx;
310 if (l == relay && r == relay)
311 return kIceCandidatePairRelayRelay;
312 if (l == relay && r == prflx)
313 return kIceCandidatePairRelayPrflx;
314 if (l == prflx && r == host)
315 return kIceCandidatePairPrflxHost;
316 if (l == prflx && r == srflx)
317 return kIceCandidatePairPrflxSrflx;
318 if (l == prflx && r == relay)
319 return kIceCandidatePairPrflxRelay;
320 return kIceCandidatePairMax;
321}
322
323// Verify that the order of media sections in |new_desc| matches
324// |existing_desc|. The number of m= sections in |new_desc| should be no less
325// than |existing_desc|.
326bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
327 const SessionDescription* new_desc) {
328 if (!existing_desc || !new_desc) {
329 return false;
330 }
331
332 if (existing_desc->contents().size() > new_desc->contents().size()) {
333 return false;
334 }
335
336 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
337 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
338 return false;
339 }
340 const MediaContentDescription* new_desc_mdesc =
341 static_cast<const MediaContentDescription*>(
342 new_desc->contents()[i].description);
343 const MediaContentDescription* existing_desc_mdesc =
344 static_cast<const MediaContentDescription*>(
345 existing_desc->contents()[i].description);
346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
367bool VerifyCrypto(const SessionDescription* desc,
368 bool dtls_enabled,
369 std::string* error) {
370 const cricket::ContentGroup* bundle =
371 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
372 const ContentInfos& contents = desc->contents();
373 for (size_t index = 0; index < contents.size(); ++index) {
374 const ContentInfo* cinfo = &contents[index];
375 if (cinfo->rejected) {
376 continue;
377 }
378 if (bundle && bundle->HasContentName(cinfo->name) &&
379 cinfo->name != *(bundle->FirstContentName())) {
380 // This isn't the first media section in the BUNDLE group, so it's not
381 // required to have crypto attributes, since only the crypto attributes
382 // from the first section actually get used.
383 continue;
384 }
385
386 // If the content isn't rejected or bundled into another m= section, crypto
387 // must be present.
388 const MediaContentDescription* media =
389 static_cast<const MediaContentDescription*>(cinfo->description);
390 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
391 if (!media || !tinfo) {
392 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800394 *error = kInvalidSdp;
395 return false;
396 }
397 if (dtls_enabled) {
398 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100399 RTC_LOG(LS_WARNING)
400 << "Session description must have DTLS fingerprint if "
401 "DTLS enabled.";
Steve Anton75737c02017-11-06 10:37:17 -0800402 *error = kSdpWithoutDtlsFingerprint;
403 return false;
404 }
405 } else {
406 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100407 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800408 << "Session description must have SDES when DTLS disabled.";
409 *error = kSdpWithoutSdesCrypto;
410 return false;
411 }
412 }
413 }
414
415 return true;
416}
417
418// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
419// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
420// media section/description in the BUNDLE group) needs a ufrag and pwd.
421bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
422 const cricket::ContentGroup* bundle =
423 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
424 const ContentInfos& contents = desc->contents();
425 for (size_t index = 0; index < contents.size(); ++index) {
426 const ContentInfo* cinfo = &contents[index];
427 if (cinfo->rejected) {
428 continue;
429 }
430 if (bundle && bundle->HasContentName(cinfo->name) &&
431 cinfo->name != *(bundle->FirstContentName())) {
432 // This isn't the first media section in the BUNDLE group, so it's not
433 // required to have ufrag/password, since only the ufrag/password from
434 // the first section actually get used.
435 continue;
436 }
437
438 // If the content isn't rejected or bundled into another m= section,
439 // ice-ufrag and ice-pwd must be present.
440 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
441 if (!tinfo) {
442 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100443 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800444 return false;
445 }
446 if (tinfo->description.ice_ufrag.empty() ||
447 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100448 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800449 return false;
450 }
451 }
452 return true;
453}
454
455bool GetTrackIdBySsrc(const SessionDescription* session_description,
456 uint32_t ssrc,
457 std::string* track_id) {
458 RTC_DCHECK(track_id != NULL);
459
460 const cricket::ContentInfo* audio_info =
461 cricket::GetFirstAudioContent(session_description);
462 if (audio_info) {
463 const cricket::MediaContentDescription* audio_content =
464 static_cast<const cricket::MediaContentDescription*>(
465 audio_info->description);
466
467 const auto* found =
468 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
469 if (found) {
470 *track_id = found->id;
471 return true;
472 }
473 }
474
475 const cricket::ContentInfo* video_info =
476 cricket::GetFirstVideoContent(session_description);
477 if (video_info) {
478 const cricket::MediaContentDescription* video_content =
479 static_cast<const cricket::MediaContentDescription*>(
480 video_info->description);
481
482 const auto* found =
483 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
484 if (found) {
485 *track_id = found->id;
486 return true;
487 }
488 }
489 return false;
490}
491
492// Get the SCTP port out of a SessionDescription.
493// Return -1 if not found.
494int GetSctpPort(const SessionDescription* session_description) {
495 const ContentInfo* content_info = GetFirstDataContent(session_description);
496 RTC_DCHECK(content_info);
497 if (!content_info) {
498 return -1;
499 }
500 const cricket::DataContentDescription* data =
501 static_cast<const cricket::DataContentDescription*>(
502 (content_info->description));
503 std::string value;
504 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
505 cricket::kGoogleSctpDataCodecName);
506 for (const cricket::DataCodec& codec : data->codecs()) {
507 if (!codec.Matches(match_pattern)) {
508 continue;
509 }
510 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
511 return rtc::FromString<int>(value);
512 }
513 }
514 return -1;
515}
516
517bool BadSdp(const std::string& source,
518 const std::string& type,
519 const std::string& reason,
520 std::string* err_desc) {
521 std::ostringstream desc;
522 desc << "Failed to set " << source;
523 if (!type.empty()) {
524 desc << " " << type;
525 }
526 desc << " sdp: " << reason;
527
528 if (err_desc) {
529 *err_desc = desc.str();
530 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_ERROR) << desc.str();
Steve Anton75737c02017-11-06 10:37:17 -0800532 return false;
533}
534
535bool BadSdp(cricket::ContentSource source,
536 const std::string& type,
537 const std::string& reason,
538 std::string* err_desc) {
539 if (source == cricket::CS_LOCAL) {
540 return BadSdp("local", type, reason, err_desc);
541 } else {
542 return BadSdp("remote", type, reason, err_desc);
543 }
544}
545
546bool BadLocalSdp(const std::string& type,
547 const std::string& reason,
548 std::string* err_desc) {
549 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
550}
551
552bool BadRemoteSdp(const std::string& type,
553 const std::string& reason,
554 std::string* err_desc) {
555 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
556}
557
558bool BadOfferSdp(cricket::ContentSource source,
559 const std::string& reason,
560 std::string* err_desc) {
561 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
562}
563
564bool BadPranswerSdp(cricket::ContentSource source,
565 const std::string& reason,
566 std::string* err_desc) {
567 return BadSdp(source, SessionDescriptionInterface::kPrAnswer, reason,
568 err_desc);
569}
570
571bool BadAnswerSdp(cricket::ContentSource source,
572 const std::string& reason,
573 std::string* err_desc) {
574 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
575}
576
577std::string BadStateErrMsg(PeerConnectionInterface::SignalingState state) {
578 std::ostringstream desc;
579 desc << "Called in wrong state: " << GetSignalingStateString(state);
580 return desc.str();
581}
582
583#define GET_STRING_OF_ERROR_CODE(err) \
584 case webrtc::PeerConnection::err: \
585 result = #err; \
586 break;
587
588std::string GetErrorCodeString(webrtc::PeerConnection::Error err) {
589 std::string result;
590 switch (err) {
591 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
592 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
593 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
594 default:
595 RTC_NOTREACHED();
596 break;
597 }
598 return result;
599}
600
601std::string MakeErrorString(const std::string& error, const std::string& desc) {
602 std::ostringstream ret;
603 ret << error << " " << desc;
604 return ret.str();
605}
606
607std::string MakeTdErrorString(const std::string& desc) {
608 return MakeErrorString(kPushDownTDFailed, desc);
609}
610
611// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
612bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
613 const SessionDescriptionInterface* new_desc,
614 const std::string& content_name) {
615 if (!old_desc) {
616 return false;
617 }
618 const SessionDescription* new_sd = new_desc->description();
619 const SessionDescription* old_sd = old_desc->description();
620 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
621 if (!cinfo || cinfo->rejected) {
622 return false;
623 }
624 // If the content isn't rejected, check if ufrag and password has changed.
625 const cricket::TransportDescription* new_transport_desc =
626 new_sd->GetTransportDescriptionByName(content_name);
627 const cricket::TransportDescription* old_transport_desc =
628 old_sd->GetTransportDescriptionByName(content_name);
629 if (!new_transport_desc || !old_transport_desc) {
630 // No transport description exists. This is not an ICE restart.
631 return false;
632 }
633 if (cricket::IceCredentialsChanged(
634 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
635 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100636 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
637 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800638 return true;
639 }
640 return false;
641}
642
643} // namespace
644
Henrik Boström31638672017-11-23 17:48:32 +0100645// Upon completion, posts a task to execute the callback of the
646// SetSessionDescriptionObserver asynchronously on the same thread. At this
647// point, the state of the peer connection might no longer reflect the effects
648// of the SetRemoteDescription operation, as the peer connection could have been
649// modified during the post.
650// TODO(hbos): Remove this class once we remove the version of
651// PeerConnectionInterface::SetRemoteDescription() that takes a
652// SetSessionDescriptionObserver as an argument.
653class PeerConnection::SetRemoteDescriptionObserverAdapter
654 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
655 public:
656 SetRemoteDescriptionObserverAdapter(
657 rtc::scoped_refptr<PeerConnection> pc,
658 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
659 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
660
661 // SetRemoteDescriptionObserverInterface implementation.
662 void OnSetRemoteDescriptionComplete(RTCError error) override {
663 if (error.ok())
664 pc_->PostSetSessionDescriptionSuccess(wrapper_);
665 else
666 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
667 }
668
669 private:
670 rtc::scoped_refptr<PeerConnection> pc_;
671 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
672};
673
deadbeef293e9262017-01-11 12:28:30 -0800674bool PeerConnectionInterface::RTCConfiguration::operator==(
675 const PeerConnectionInterface::RTCConfiguration& o) const {
676 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700677 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800678 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000679 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800681 BundlePolicy bundle_policy;
682 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700683 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
684 int ice_candidate_pool_size;
685 bool disable_ipv6;
686 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700687 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700688 bool enable_rtp_data_channel;
689 rtc::Optional<int> screencast_min_bitrate;
690 rtc::Optional<bool> combined_audio_video_bwe;
691 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800692 TcpCandidatePolicy tcp_candidate_policy;
693 CandidateNetworkPolicy candidate_network_policy;
694 int audio_jitter_buffer_max_packets;
695 bool audio_jitter_buffer_fast_accelerate;
696 int ice_connection_receiving_timeout;
697 int ice_backup_candidate_pair_ping_interval;
698 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800699 bool prioritize_most_likely_ice_candidate_pairs;
700 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800701 bool prune_turn_ports;
702 bool presume_writable_when_fully_relayed;
703 bool enable_ice_renomination;
704 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800705 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700706 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200707 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800708 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800709 };
710 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
711 "Did you add something to RTCConfiguration and forget to "
712 "update operator==?");
713 return type == o.type && servers == o.servers &&
714 bundle_policy == o.bundle_policy &&
715 rtcp_mux_policy == o.rtcp_mux_policy &&
716 tcp_candidate_policy == o.tcp_candidate_policy &&
717 candidate_network_policy == o.candidate_network_policy &&
718 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
719 audio_jitter_buffer_fast_accelerate ==
720 o.audio_jitter_buffer_fast_accelerate &&
721 ice_connection_receiving_timeout ==
722 o.ice_connection_receiving_timeout &&
723 ice_backup_candidate_pair_ping_interval ==
724 o.ice_backup_candidate_pair_ping_interval &&
725 continual_gathering_policy == o.continual_gathering_policy &&
726 certificates == o.certificates &&
727 prioritize_most_likely_ice_candidate_pairs ==
728 o.prioritize_most_likely_ice_candidate_pairs &&
729 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800730 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700731 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800732 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800733 screencast_min_bitrate == o.screencast_min_bitrate &&
734 combined_audio_video_bwe == o.combined_audio_video_bwe &&
735 enable_dtls_srtp == o.enable_dtls_srtp &&
736 ice_candidate_pool_size == o.ice_candidate_pool_size &&
737 prune_turn_ports == o.prune_turn_ports &&
738 presume_writable_when_fully_relayed ==
739 o.presume_writable_when_fully_relayed &&
740 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800741 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700742 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200743 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800744 turn_customizer == o.turn_customizer &&
745 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800746}
747
748bool PeerConnectionInterface::RTCConfiguration::operator!=(
749 const PeerConnectionInterface::RTCConfiguration& o) const {
750 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800751}
752
zhihuang8f65cdf2016-05-06 18:40:30 -0700753// Generate a RTCP CNAME when a PeerConnection is created.
754std::string GenerateRtcpCname() {
755 std::string cname;
756 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100757 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800758 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700759 }
760 return cname;
761}
762
zhihuang1c378ed2017-08-17 14:10:50 -0700763bool ValidateOfferAnswerOptions(
764 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
765 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
766 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700767}
768
zhihuang1c378ed2017-08-17 14:10:50 -0700769// From |rtc_options|, fill parts of |session_options| shared by all generated
770// m= sections (in other words, nothing that involves a map/array).
771void ExtractSharedMediaSessionOptions(
772 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
773 cricket::MediaSessionOptions* session_options) {
774 session_options->vad_enabled = rtc_options.voice_activity_detection;
775 session_options->bundle_enabled = rtc_options.use_rtp_mux;
776}
zhihuanga77e6bb2017-08-14 18:17:48 -0700777
zhihuang1c378ed2017-08-17 14:10:50 -0700778bool ConvertConstraintsToOfferAnswerOptions(
779 const MediaConstraintsInterface* constraints,
780 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700781 if (!constraints) {
782 return true;
783 }
zhihuang1c378ed2017-08-17 14:10:50 -0700784
785 bool value = false;
786 size_t mandatory_constraints_satisfied = 0;
787
788 if (FindConstraint(constraints,
789 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
790 &mandatory_constraints_satisfied)) {
791 offer_answer_options->offer_to_receive_audio =
792 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
793 kOfferToReceiveMediaTrue
794 : 0;
795 }
796
797 if (FindConstraint(constraints,
798 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
799 &mandatory_constraints_satisfied)) {
800 offer_answer_options->offer_to_receive_video =
801 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
802 kOfferToReceiveMediaTrue
803 : 0;
804 }
805 if (FindConstraint(constraints,
806 MediaConstraintsInterface::kVoiceActivityDetection, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->voice_activity_detection = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
811 &mandatory_constraints_satisfied)) {
812 offer_answer_options->use_rtp_mux = value;
813 }
814 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
815 &value, &mandatory_constraints_satisfied)) {
816 offer_answer_options->ice_restart = value;
817 }
818
deadbeefab9b2d12015-10-14 11:33:11 -0700819 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
820}
821
zhihuang38ede132017-06-15 12:52:32 -0700822PeerConnection::PeerConnection(PeerConnectionFactory* factory,
823 std::unique_ptr<RtcEventLog> event_log,
824 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700826 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700827 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700828 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700829 remote_streams_(StreamCollection::Create()),
830 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
832PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100833 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800834 RTC_DCHECK_RUN_ON(signaling_thread());
835
836 // Need to detach RTP transceivers from PeerConnection, since it's about to be
837 // destroyed.
838 for (auto transceiver : transceivers_) {
839 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700840 }
Steve Anton4171afb2017-11-20 10:20:22 -0800841
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 // Destroy stats_ because it depends on session_.
843 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800844 if (stats_collector_) {
845 stats_collector_->WaitForPendingRequest();
846 stats_collector_ = nullptr;
847 }
Steve Anton75737c02017-11-06 10:37:17 -0800848
849 // Destroy video channels first since they may have a pointer to a voice
850 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800851 for (auto transceiver : transceivers_) {
852 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO &&
853 transceiver->internal()->channel()) {
854 DestroyVideoChannel(static_cast<cricket::VideoChannel*>(
855 transceiver->internal()->channel()));
856 }
Steve Anton75737c02017-11-06 10:37:17 -0800857 }
Steve Anton4171afb2017-11-20 10:20:22 -0800858 for (auto transceiver : transceivers_) {
859 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO &&
860 transceiver->internal()->channel()) {
861 DestroyVoiceChannel(static_cast<cricket::VoiceChannel*>(
862 transceiver->internal()->channel()));
863 }
Steve Anton75737c02017-11-06 10:37:17 -0800864 }
865 if (rtp_data_channel_) {
866 DestroyDataChannel();
867 }
868
869 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
870 // grab a reference to this PeerConnection. The RefCountedObject vtable will
871 // have already been destroyed (since it is a subclass of PeerConnection) and
872 // using rtc::Bind will cause "Pure virtual function called" error to appear.
873
874 if (sctp_transport_) {
875 OnDataChannelDestroyed();
876 network_thread()->Invoke<void>(RTC_FROM_HERE,
877 [this] { DestroySctpTransport_n(); });
878 }
879
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800881
882 webrtc_session_desc_factory_.reset();
883 sctp_invoker_.reset();
884 sctp_factory_.reset();
885 transport_controller_.reset();
886
deadbeef91dd5672016-05-18 16:55:30 -0700887 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700888 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700889 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700890 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700891 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700892 call_.reset();
893 event_log_.reset();
894 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895}
896
897bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000898 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700899 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200900 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800901 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100902 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700903
904 RTCError config_error = ValidateConfiguration(configuration);
905 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700907 return false;
908 }
909
deadbeef293e9262017-01-11 12:28:30 -0800910 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100911 RTC_LOG(LS_ERROR)
912 << "PeerConnection initialized without a PortAllocator? "
913 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800914 return false;
915 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200916
deadbeef653b8e02015-11-11 12:55:10 -0800917 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800918 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100919 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
920 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800921 return false;
922 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000923 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800924 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800925
deadbeef91dd5672016-05-18 16:55:30 -0700926 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700927 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700928 if (!network_thread()->Invoke<bool>(
929 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
930 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return false;
932 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933
Steve Anton75737c02017-11-06 10:37:17 -0800934 // RFC 3264: The numeric value of the session id and version in the
935 // o line MUST be representable with a "64 bit signed integer".
936 // Due to this constraint session id |session_id_| is max limited to
937 // LLONG_MAX.
938 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
939 transport_controller_.reset(factory_->CreateTransportController(
940 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
941 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
942 transport_controller_->SignalConnectionState.connect(
943 this, &PeerConnection::OnTransportControllerConnectionState);
944 transport_controller_->SignalGatheringState.connect(
945 this, &PeerConnection::OnTransportControllerGatheringState);
946 transport_controller_->SignalCandidatesGathered.connect(
947 this, &PeerConnection::OnTransportControllerCandidatesGathered);
948 transport_controller_->SignalCandidatesRemoved.connect(
949 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
950 transport_controller_->SignalDtlsHandshakeError.connect(
951 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
952
953 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700954
deadbeefab9b2d12015-10-14 11:33:11 -0700955 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700956 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957
Steve Antonba818672017-11-06 10:21:57 -0800958 configuration_ = configuration;
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 const PeerConnectionFactoryInterface::Options& options = factory_->options();
961
962 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
963
964 // Obtain a certificate from RTCConfiguration if any were provided (optional).
965 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
966 if (!configuration.certificates.empty()) {
967 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
968 // just picking the first one. The decision should be made based on the DTLS
969 // handshake. The DTLS negotiations need to know about all certificates.
970 certificate = configuration.certificates[0];
971 }
972
Steve Antond25da372017-11-06 14:50:29 -0800973 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800974
975 if (options.disable_encryption) {
976 dtls_enabled_ = false;
977 } else {
978 // Enable DTLS by default if we have an identity store or a certificate.
979 dtls_enabled_ = (cert_generator || certificate);
980 // |configuration| can override the default |dtls_enabled_| value.
981 if (configuration.enable_dtls_srtp) {
982 dtls_enabled_ = *(configuration.enable_dtls_srtp);
983 }
984 }
985
986 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
987 // It takes precendence over the disable_sctp_data_channels
988 // PeerConnectionFactoryInterface::Options.
989 if (configuration.enable_rtp_data_channel) {
990 data_channel_type_ = cricket::DCT_RTP;
991 } else {
992 // DTLS has to be enabled to use SCTP.
993 if (!options.disable_sctp_data_channels && dtls_enabled_) {
994 data_channel_type_ = cricket::DCT_SCTP;
995 }
996 }
997
998 video_options_.screencast_min_bitrate_kbps =
999 configuration.screencast_min_bitrate;
1000 audio_options_.combined_audio_video_bwe =
1001 configuration.combined_audio_video_bwe;
1002
1003 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001004 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001005
1006 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001007 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001008
1009 // Whether the certificate generator/certificate is null or not determines
1010 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1011 // the right instructions by clearing the variables if needed.
1012 if (!dtls_enabled_) {
1013 cert_generator.reset();
1014 certificate = nullptr;
1015 } else if (certificate) {
1016 // Favor generated certificate over the certificate generator.
1017 cert_generator.reset();
1018 }
1019
1020 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1021 signaling_thread(), channel_manager(), this, session_id(),
1022 std::move(cert_generator), certificate));
1023 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1024 this, &PeerConnection::OnCertificateReady);
1025
1026 if (options.disable_encryption) {
1027 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1028 }
1029
1030 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1031 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032
Steve Anton4171afb2017-11-20 10:20:22 -08001033 // Add default audio/video transceivers for Plan B SDP.
1034 if (!IsUnifiedPlan()) {
1035 transceivers_.push_back(
1036 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1037 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1038 transceivers_.push_back(
1039 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1040 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1041 }
1042
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043 return true;
1044}
1045
Steve Anton038834f2017-07-14 15:59:59 -07001046RTCError PeerConnection::ValidateConfiguration(
1047 const RTCConfiguration& config) const {
1048 if (config.ice_regather_interval_range &&
1049 config.continual_gathering_policy == GATHER_ONCE) {
1050 return RTCError(RTCErrorType::INVALID_PARAMETER,
1051 "ice_regather_interval_range specified but continual "
1052 "gathering policy is GATHER_ONCE");
1053 }
1054 return RTCError::OK();
1055}
1056
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001057rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001062rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001064 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065}
1066
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001067bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001068 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001069 if (IsClosed()) {
1070 return false;
1071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 return false;
1074 }
deadbeefab9b2d12015-10-14 11:33:11 -07001075
1076 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001077 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1078 observer->SignalAudioTrackAdded.connect(this,
1079 &PeerConnection::OnAudioTrackAdded);
1080 observer->SignalAudioTrackRemoved.connect(
1081 this, &PeerConnection::OnAudioTrackRemoved);
1082 observer->SignalVideoTrackAdded.connect(this,
1083 &PeerConnection::OnVideoTrackAdded);
1084 observer->SignalVideoTrackRemoved.connect(
1085 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001086 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001087
deadbeefab9b2d12015-10-14 11:33:11 -07001088 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001089 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001090 }
1091 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001092 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001093 }
1094
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001095 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 observer_->OnRenegotiationNeeded();
1097 return true;
1098}
1099
1100void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001101 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001102 if (!IsClosed()) {
1103 for (const auto& track : local_stream->GetAudioTracks()) {
1104 RemoveAudioTrack(track.get(), local_stream);
1105 }
1106 for (const auto& track : local_stream->GetVideoTracks()) {
1107 RemoveVideoTrack(track.get(), local_stream);
1108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 }
deadbeefab9b2d12015-10-14 11:33:11 -07001110 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001111 stream_observers_.erase(
1112 std::remove_if(
1113 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001114 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001115 return observer->stream()->label().compare(local_stream->label()) ==
1116 0;
1117 }),
1118 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001119
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120 if (IsClosed()) {
1121 return;
1122 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123 observer_->OnRenegotiationNeeded();
1124}
1125
deadbeefe1f9d832016-01-14 15:35:42 -08001126rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1127 MediaStreamTrackInterface* track,
1128 std::vector<MediaStreamInterface*> streams) {
1129 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1130 if (IsClosed()) {
1131 return nullptr;
1132 }
1133 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001134 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001135 << "Adding a track with two streams is not currently supported.";
1136 return nullptr;
1137 }
Steve Anton4171afb2017-11-20 10:20:22 -08001138 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001139 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1140 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001141 return nullptr;
1142 }
1143
1144 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001145 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001146 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001147 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001148 signaling_thread(),
1149 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001150 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001151 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001152 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001153 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
Steve Anton4171afb2017-11-20 10:20:22 -08001155 const RtpSenderInfo* sender_info =
1156 FindSenderInfo(local_audio_sender_infos_,
1157 new_sender->internal()->stream_id(), track->id());
1158 if (sender_info) {
1159 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001160 }
1161 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001162 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001163 signaling_thread(),
1164 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001165 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001166 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001167 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001168 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001169 }
Steve Anton4171afb2017-11-20 10:20:22 -08001170 const RtpSenderInfo* sender_info =
1171 FindSenderInfo(local_video_sender_infos_,
1172 new_sender->internal()->stream_id(), track->id());
1173 if (sender_info) {
1174 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001175 }
1176 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001177 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1178 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001179 return rtc::scoped_refptr<RtpSenderInterface>();
1180 }
1181
deadbeefe1f9d832016-01-14 15:35:42 -08001182 observer_->OnRenegotiationNeeded();
1183 return new_sender;
1184}
1185
1186bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1187 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1188 if (IsClosed()) {
1189 return false;
1190 }
1191
Steve Anton4171afb2017-11-20 10:20:22 -08001192 bool removed;
1193 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1194 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1195 } else {
1196 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1197 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1198 }
1199 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001200 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1201 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001202 return false;
1203 }
deadbeefe1f9d832016-01-14 15:35:42 -08001204
1205 observer_->OnRenegotiationNeeded();
1206 return true;
1207}
1208
Steve Anton9158ef62017-11-27 13:01:52 -08001209RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1210PeerConnection::AddTransceiver(
1211 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1212 return AddTransceiver(track, RtpTransceiverInit());
1213}
1214
1215RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1216PeerConnection::AddTransceiver(
1217 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1218 const RtpTransceiverInit& init) {
1219 if (!IsUnifiedPlan()) {
1220 LOG_AND_RETURN_ERROR(
1221 RTCErrorType::INTERNAL_ERROR,
1222 "AddTransceiver only supported when Unified Plan is enabled.");
1223 }
1224 if (!track) {
1225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1226 }
1227 cricket::MediaType media_type;
1228 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1229 media_type = cricket::MEDIA_TYPE_AUDIO;
1230 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1231 media_type = cricket::MEDIA_TYPE_VIDEO;
1232 } else {
1233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1234 "Track kind is not audio or video");
1235 }
1236 return AddTransceiver(media_type, track, init);
1237}
1238
1239RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1240PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1241 return AddTransceiver(media_type, RtpTransceiverInit());
1242}
1243
1244RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1245PeerConnection::AddTransceiver(cricket::MediaType media_type,
1246 const RtpTransceiverInit& init) {
1247 if (!IsUnifiedPlan()) {
1248 LOG_AND_RETURN_ERROR(
1249 RTCErrorType::INTERNAL_ERROR,
1250 "AddTransceiver only supported when Unified Plan is enabled.");
1251 }
1252 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1253 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1255 "media type is not audio or video");
1256 }
1257 return AddTransceiver(media_type, nullptr, init);
1258}
1259
1260RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1261PeerConnection::AddTransceiver(
1262 cricket::MediaType media_type,
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1264 const RtpTransceiverInit& init) {
1265 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1266 media_type == cricket::MEDIA_TYPE_VIDEO));
1267 if (track) {
1268 RTC_DCHECK_EQ(media_type,
1269 (track->kind() == MediaStreamTrackInterface::kAudioKind
1270 ? cricket::MEDIA_TYPE_AUDIO
1271 : cricket::MEDIA_TYPE_VIDEO));
1272 }
1273
1274 // TODO(bugs.webrtc.org/7600): Verify init.
1275
1276 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1277 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1278 receiver;
1279 std::string receiver_id = rtc::CreateRandomUuid();
1280 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1281 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1282 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1283 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1284 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1285 } else {
1286 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1287 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1288 signaling_thread(), new VideoRtpSender(nullptr));
1289 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1290 signaling_thread(),
1291 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1292 }
1293 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1294 // channel prevents users from calling SetParameters on them, which is needed
1295 // to be in compliance with the spec.
1296
1297 if (track) {
1298 sender->SetTrack(track);
1299 }
1300
1301 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1302 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1303 signaling_thread(), new RtpTransceiver(sender, receiver));
1304 transceiver->SetDirection(init.direction);
1305
1306 transceivers_.push_back(transceiver);
1307
1308 observer_->OnRenegotiationNeeded();
1309
1310 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1311}
1312
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001313rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001315 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001316 if (IsClosed()) {
1317 return nullptr;
1318 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001320 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001321 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 }
Steve Anton4171afb2017-11-20 10:20:22 -08001323 auto track_sender = FindSenderForTrack(track);
1324 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001325 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001326 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327 }
1328
Steve Anton4171afb2017-11-20 10:20:22 -08001329 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330}
1331
deadbeeffac06552015-11-25 11:26:01 -08001332rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001333 const std::string& kind,
1334 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001335 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001336 if (IsClosed()) {
1337 return nullptr;
1338 }
Steve Anton4171afb2017-11-20 10:20:22 -08001339
1340 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001341 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001342 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001343 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001344 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001345 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001346 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001347 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001348 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001349 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001350 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001351 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001352 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001353 }
Steve Anton4171afb2017-11-20 10:20:22 -08001354
deadbeefbd7d8f72015-12-18 16:58:44 -08001355 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001356 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001357 }
Steve Anton4171afb2017-11-20 10:20:22 -08001358
deadbeefe1f9d832016-01-14 15:35:42 -08001359 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001360}
1361
deadbeef70ab1a12015-09-28 16:53:55 -07001362std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1363 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001364 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001365 for (auto sender : GetSendersInternal()) {
1366 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001367 }
1368 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001369}
1370
Steve Anton4171afb2017-11-20 10:20:22 -08001371std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1372PeerConnection::GetSendersInternal() const {
1373 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1374 all_senders;
1375 for (auto transceiver : transceivers_) {
1376 auto senders = transceiver->internal()->senders();
1377 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1378 }
1379 return all_senders;
1380}
1381
deadbeef70ab1a12015-09-28 16:53:55 -07001382std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1383PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001384 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001385 for (const auto& receiver : GetReceiversInternal()) {
1386 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001387 }
1388 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001389}
1390
Steve Anton4171afb2017-11-20 10:20:22 -08001391std::vector<
1392 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1393PeerConnection::GetReceiversInternal() const {
1394 std::vector<
1395 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1396 all_receivers;
1397 for (auto transceiver : transceivers_) {
1398 auto receivers = transceiver->internal()->receivers();
1399 all_receivers.insert(all_receivers.end(), receivers.begin(),
1400 receivers.end());
1401 }
1402 return all_receivers;
1403}
1404
Steve Anton9158ef62017-11-27 13:01:52 -08001405std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::GetTransceivers() const {
1407 RTC_DCHECK(IsUnifiedPlan());
1408 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1409 for (auto transceiver : transceivers_) {
1410 all_transceivers.push_back(transceiver);
1411 }
1412 return all_transceivers;
1413}
1414
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001416 MediaStreamTrackInterface* track,
1417 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001418 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001419 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001420 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001421 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 return false;
1423 }
1424
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001425 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001426 // The StatsCollector is used to tell if a track is valid because it may
1427 // remember tracks that the PeerConnection previously removed.
1428 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001429 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1430 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001431 return false;
1432 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001433 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001434 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435 return true;
1436}
1437
hbos74e1a4f2016-09-15 23:33:01 -07001438void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1439 RTC_DCHECK(stats_collector_);
1440 stats_collector_->GetStatsReport(callback);
1441}
1442
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1444 return signaling_state_;
1445}
1446
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447PeerConnectionInterface::IceConnectionState
1448PeerConnection::ice_connection_state() {
1449 return ice_connection_state_;
1450}
1451
1452PeerConnectionInterface::IceGatheringState
1453PeerConnection::ice_gathering_state() {
1454 return ice_gathering_state_;
1455}
1456
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001457rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458PeerConnection::CreateDataChannel(
1459 const std::string& label,
1460 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001461 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001462
deadbeefab9b2d12015-10-14 11:33:11 -07001463 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001464
kwibergd1fe2812016-04-27 06:47:29 -07001465 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001466 if (config) {
1467 internal_config.reset(new InternalDataChannelInit(*config));
1468 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001469 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001470 InternalCreateDataChannel(label, internal_config.get()));
1471 if (!channel.get()) {
1472 return nullptr;
1473 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001475 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1476 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001477 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001478 observer_->OnRenegotiationNeeded();
1479 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001480
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 return DataChannelProxy::Create(signaling_thread(), channel.get());
1482}
1483
1484void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1485 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001486 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001487
zhihuang1c378ed2017-08-17 14:10:50 -07001488 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1489 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1490 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1491 // compares the mandatory fields parsed with the mandatory fields added in the
1492 // |constraints| and some downstream applications might create offers with
1493 // mandatory fields which would not be parsed in the helper method. For
1494 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1495 // |constraints| as a mandatory field but it is not parsed.
1496 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001497
zhihuang1c378ed2017-08-17 14:10:50 -07001498 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001499}
1500
1501void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1502 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001503 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001504
nisse7ce109a2017-01-31 00:57:56 -08001505 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001506 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001507 return;
1508 }
deadbeefab9b2d12015-10-14 11:33:11 -07001509
Steve Anton8d3444d2017-10-20 15:30:51 -07001510 if (IsClosed()) {
1511 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001512 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001513 PostCreateSessionDescriptionFailure(observer, error);
1514 return;
1515 }
1516
zhihuang1c378ed2017-08-17 14:10:50 -07001517 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001518 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001519 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001520 PostCreateSessionDescriptionFailure(observer, error);
1521 return;
1522 }
1523
zhihuang1c378ed2017-08-17 14:10:50 -07001524 cricket::MediaSessionOptions session_options;
1525 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001526 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527}
1528
1529void PeerConnection::CreateAnswer(
1530 CreateSessionDescriptionObserver* observer,
1531 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001532 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001533
nisse7ce109a2017-01-31 00:57:56 -08001534 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001535 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536 return;
1537 }
deadbeefab9b2d12015-10-14 11:33:11 -07001538
zhihuang1c378ed2017-08-17 14:10:50 -07001539 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1540 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1541 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001542 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001543 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001544 PostCreateSessionDescriptionFailure(observer, error);
1545 return;
1546 }
1547
Steve Anton8d3444d2017-10-20 15:30:51 -07001548 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001549}
1550
1551void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1552 const RTCOfferAnswerOptions& options) {
1553 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001554 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001555 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001556 return;
1557 }
1558
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 if (IsClosed()) {
1560 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001561 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001562 PostCreateSessionDescriptionFailure(observer, error);
1563 return;
1564 }
1565
Steve Anton75737c02017-11-06 10:37:17 -08001566 if (remote_description() &&
1567 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001568 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001569 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001570 PostCreateSessionDescriptionFailure(observer, error);
1571 return;
1572 }
1573
htaa2a49d92016-03-04 02:51:39 -08001574 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001575 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001576
Steve Antond25da372017-11-06 14:50:29 -08001577 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001578}
1579
1580void PeerConnection::SetLocalDescription(
1581 SetSessionDescriptionObserver* observer,
1582 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001583 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001584 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001585 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586 return;
1587 }
1588 if (!desc) {
1589 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1590 return;
1591 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001592
1593 // Takes the ownership of |desc| regardless of the result.
1594 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1595
1596 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001597 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001598 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001599 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001600 PostSetSessionDescriptionFailure(observer, error);
1601 return;
1602 }
1603
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604 // Update stats here so that we have the most recent stats for tracks and
1605 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001606 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001608 // Takes the ownership of |desc_temp|. On success, local_description() is
1609 // updated to reflect the description that was passed in.
Henrik Boström31638672017-11-23 17:48:32 +01001610 if (!SetCurrentOrPendingLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001611 PostSetSessionDescriptionFailure(observer, error);
1612 return;
1613 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001614 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001615
1616 // If setting the description decided our SSL role, allocate any necessary
1617 // SCTP sids.
1618 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001619 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001620 AllocateSctpSids(role);
1621 }
1622
1623 // Update state and SSRC of local MediaStreams and DataChannels based on the
1624 // local session description.
1625 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001626 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001627 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001628 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001629 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001630 } else {
1631 const cricket::AudioContentDescription* audio_desc =
1632 static_cast<const cricket::AudioContentDescription*>(
1633 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001634 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001635 }
deadbeefab9b2d12015-10-14 11:33:11 -07001636 }
1637
1638 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001639 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001640 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001641 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001642 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001643 } else {
1644 const cricket::VideoContentDescription* video_desc =
1645 static_cast<const cricket::VideoContentDescription*>(
1646 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001647 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001648 }
deadbeefab9b2d12015-10-14 11:33:11 -07001649 }
1650
1651 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001652 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001653 if (data_content) {
1654 const cricket::DataContentDescription* data_desc =
1655 static_cast<const cricket::DataContentDescription*>(
1656 data_content->description);
1657 if (rtc::starts_with(data_desc->protocol().data(),
1658 cricket::kMediaProtocolRtpPrefix)) {
1659 UpdateLocalRtpDataChannels(data_desc->streams());
1660 }
1661 }
1662
Henrik Boström31638672017-11-23 17:48:32 +01001663 PostSetSessionDescriptionSuccess(observer);
deadbeefab9b2d12015-10-14 11:33:11 -07001664
deadbeef42a42632017-03-10 15:18:00 -08001665 // According to JSEP, after setLocalDescription, changing the candidate pool
1666 // size is not allowed, and changing the set of ICE servers will not result
1667 // in new candidates being gathered.
1668 port_allocator_->FreezeCandidatePool();
1669
deadbeefcbecd352015-09-23 11:50:27 -07001670 // MaybeStartGathering needs to be called after posting
1671 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1672 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001673 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001674
Henrik Boströmfdb92012017-11-09 19:55:44 +01001675 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001676 // TODO(deadbeef): We already had to hop to the network thread for
1677 // MaybeStartGathering...
1678 network_thread()->Invoke<void>(
1679 RTC_FROM_HERE,
1680 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1681 port_allocator_.get()));
1682 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683}
1684
1685void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001686 SetSessionDescriptionObserver* observer,
1687 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001688 SetRemoteDescription(
1689 std::unique_ptr<SessionDescriptionInterface>(desc),
1690 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1691 new SetRemoteDescriptionObserverAdapter(this, observer)));
1692}
1693
1694void PeerConnection::SetRemoteDescription(
1695 std::unique_ptr<SessionDescriptionInterface> desc,
1696 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001697 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001698 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001699 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 return;
1701 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001702 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001703 observer->OnSetRemoteDescriptionComplete(RTCError(
1704 RTCErrorType::UNSUPPORTED_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705 return;
1706 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001707
Steve Anton8d3444d2017-10-20 15:30:51 -07001708 if (IsClosed()) {
Henrik Boström31638672017-11-23 17:48:32 +01001709 std::string error = "Failed to set remote " + desc->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001710 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001711 RTC_LOG(LS_ERROR) << error;
Henrik Boström31638672017-11-23 17:48:32 +01001712 observer->OnSetRemoteDescriptionComplete(
1713 RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001714 return;
1715 }
1716
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717 // Update stats here so that we have the most recent stats for tracks and
1718 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001719 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001720 std::string error;
Henrik Boström31638672017-11-23 17:48:32 +01001721 // Takes the ownership of |desc|. On success, remote_description() is updated
1722 // to reflect the description that was passed in.
1723 if (!SetCurrentOrPendingRemoteDescription(std::move(desc), &error)) {
1724 observer->OnSetRemoteDescriptionComplete(
1725 RTCError(RTCErrorType::UNSUPPORTED_PARAMETER, std::move(error)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001726 return;
1727 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001728 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729
deadbeefab9b2d12015-10-14 11:33:11 -07001730 // If setting the description decided our SSL role, allocate any necessary
1731 // SCTP sids.
1732 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001733 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001734 AllocateSctpSids(role);
1735 }
1736
Henrik Boströmfdb92012017-11-09 19:55:44 +01001737 const cricket::ContentInfo* audio_content =
1738 GetFirstAudioContent(remote_description()->description());
1739 const cricket::ContentInfo* video_content =
1740 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001741 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001742 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001743 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001744 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001745 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001746 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001747
1748 // Check if the descriptions include streams, just in case the peer supports
1749 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001750 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001751 (audio_desc && !audio_desc->streams().empty()) ||
1752 (video_desc && !video_desc->streams().empty())) {
1753 remote_peer_supports_msid_ = true;
1754 }
deadbeefab9b2d12015-10-14 11:33:11 -07001755
1756 // We wait to signal new streams until we finish processing the description,
1757 // since only at that point will new streams have all their tracks.
1758 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1759
Steve Anton8d3444d2017-10-20 15:30:51 -07001760 // TODO(steveanton): When removing RTP senders/receivers in response to a
1761 // rejected media section, there is some cleanup logic that expects the voice/
1762 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001763 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001764 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001765 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001766
deadbeefab9b2d12015-10-14 11:33:11 -07001767 // Find all audio rtp streams and create corresponding remote AudioTracks
1768 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001769 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001770 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001771 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001772 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001773 bool default_audio_track_needed =
1774 !remote_peer_supports_msid_ &&
1775 MediaContentDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001776 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001777 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001778 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001779 }
deadbeefab9b2d12015-10-14 11:33:11 -07001780 }
1781
1782 // Find all video rtp streams and create corresponding remote VideoTracks
1783 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001784 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001785 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001786 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001787 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001788 bool default_video_track_needed =
1789 !remote_peer_supports_msid_ &&
1790 MediaContentDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001791 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001792 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001793 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001794 }
deadbeefab9b2d12015-10-14 11:33:11 -07001795 }
1796
1797 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001798 if (data_desc) {
1799 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001800 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001801 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001802 }
1803 }
1804
1805 // Iterate new_streams and notify the observer about new MediaStreams.
1806 for (size_t i = 0; i < new_streams->count(); ++i) {
1807 MediaStreamInterface* new_stream = new_streams->at(i);
1808 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001809 observer_->OnAddStream(
1810 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001811 }
1812
deadbeefbda7e0b2015-12-08 17:13:40 -08001813 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001814
Henrik Boström31638672017-11-23 17:48:32 +01001815 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
deadbeef42a42632017-03-10 15:18:00 -08001816
Henrik Boströmfdb92012017-11-09 19:55:44 +01001817 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001818 // TODO(deadbeef): We already had to hop to the network thread for
1819 // MaybeStartGathering...
1820 network_thread()->Invoke<void>(
1821 RTC_FROM_HERE,
1822 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1823 port_allocator_.get()));
1824 }
deadbeeffc648b62015-10-13 16:42:33 -07001825}
1826
deadbeef46c73892016-11-16 19:42:04 -08001827PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1828 return configuration_;
1829}
1830
deadbeef293e9262017-01-11 12:28:30 -08001831bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1832 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001833 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001834
Steve Anton75737c02017-11-06 10:37:17 -08001835 if (local_description() && configuration.ice_candidate_pool_size !=
1836 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001837 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1838 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001839 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001840 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001841
deadbeef293e9262017-01-11 12:28:30 -08001842 // The simplest (and most future-compatible) way to tell if the config was
1843 // modified in an invalid way is to copy each property we do support
1844 // modifying, then use operator==. There are far more properties we don't
1845 // support modifying than those we do, and more could be added.
1846 RTCConfiguration modified_config = configuration_;
1847 modified_config.servers = configuration.servers;
1848 modified_config.type = configuration.type;
1849 modified_config.ice_candidate_pool_size =
1850 configuration.ice_candidate_pool_size;
1851 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001852 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001853 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001854 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001855 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001856 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1857 }
1858
Steve Anton038834f2017-07-14 15:59:59 -07001859 // Validate the modified configuration.
1860 RTCError validate_error = ValidateConfiguration(modified_config);
1861 if (!validate_error.ok()) {
1862 return SafeSetError(std::move(validate_error), error);
1863 }
1864
deadbeef293e9262017-01-11 12:28:30 -08001865 // Note that this isn't possible through chromium, since it's an unsigned
1866 // short in WebIDL.
1867 if (configuration.ice_candidate_pool_size < 0 ||
1868 configuration.ice_candidate_pool_size > UINT16_MAX) {
1869 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1870 }
1871
1872 // Parse ICE servers before hopping to network thread.
1873 cricket::ServerAddresses stun_servers;
1874 std::vector<cricket::RelayServerConfig> turn_servers;
1875 RTCErrorType parse_error =
1876 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1877 if (parse_error != RTCErrorType::NONE) {
1878 return SafeSetError(parse_error, error);
1879 }
1880
1881 // In theory this shouldn't fail.
1882 if (!network_thread()->Invoke<bool>(
1883 RTC_FROM_HERE,
1884 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1885 stun_servers, turn_servers, modified_config.type,
1886 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001887 modified_config.prune_turn_ports,
1888 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001890 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1891 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001892
deadbeefd1a38b52016-12-10 13:15:33 -08001893 // As described in JSEP, calling setConfiguration with new ICE servers or
1894 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1895 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001896 if (modified_config.servers != configuration_.servers ||
1897 modified_config.type != configuration_.type ||
1898 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001899 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001900 }
skvladd1f5fda2017-02-03 16:54:05 -08001901
1902 if (modified_config.ice_check_min_interval !=
1903 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001904 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001905 }
1906
deadbeef293e9262017-01-11 12:28:30 -08001907 configuration_ = modified_config;
1908 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001909}
1910
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911bool PeerConnection::AddIceCandidate(
1912 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001913 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001914 if (IsClosed()) {
1915 return false;
1916 }
Steve Antond25da372017-11-06 14:50:29 -08001917
1918 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001919 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1920 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001921 return false;
1922 }
1923
1924 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001925 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001926 return false;
1927 }
1928
1929 bool valid = false;
1930 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1931 if (!valid) {
1932 return false;
1933 }
1934
1935 // Add this candidate to the remote session description.
1936 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001938 return false;
1939 }
1940
1941 if (ready) {
1942 return UseCandidate(ice_candidate);
1943 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001944 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001945 return true;
1946 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947}
1948
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001949bool PeerConnection::RemoveIceCandidates(
1950 const std::vector<cricket::Candidate>& candidates) {
1951 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001952 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001953 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1954 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001955 return false;
1956 }
1957
1958 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001959 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001960 return false;
1961 }
1962
1963 size_t number_removed =
1964 mutable_remote_description()->RemoveCandidates(candidates);
1965 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001966 RTC_LOG(LS_ERROR)
1967 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1968 << "Requested " << candidates.size() << " but only " << number_removed
1969 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001970 }
1971
1972 // Remove the candidates from the transport controller.
1973 std::string error;
1974 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1975 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001976 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001977 }
1978 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001979}
1980
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001981void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001982 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001983 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001984
Steve Anton75737c02017-11-06 10:37:17 -08001985 if (transport_controller()) {
1986 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001987 }
1988
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001989 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001990 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001991 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001992 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001993 uma_observer_->IncrementEnumCounter(
1994 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1995 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001996 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001997 uma_observer_->IncrementEnumCounter(
1998 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1999 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002000 }
2001 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002002}
2003
zstein4b979802017-06-02 14:37:37 -07002004RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002005 if (!worker_thread()->IsCurrent()) {
2006 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002007 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2008 }
2009
2010 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2011 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2012 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2013 if (has_min && *bitrate.min_bitrate_bps < 0) {
2014 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2015 "min_bitrate_bps <= 0");
2016 }
2017 if (has_current) {
2018 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2019 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2020 "current_bitrate_bps < min_bitrate_bps");
2021 } else if (*bitrate.current_bitrate_bps < 0) {
2022 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2023 "curent_bitrate_bps < 0");
2024 }
2025 }
2026 if (has_max) {
2027 if (has_current &&
2028 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2030 "max_bitrate_bps < current_bitrate_bps");
2031 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2032 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2033 "max_bitrate_bps < min_bitrate_bps");
2034 } else if (*bitrate.max_bitrate_bps < 0) {
2035 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2036 "max_bitrate_bps < 0");
2037 }
2038 }
2039
2040 Call::Config::BitrateConfigMask mask;
2041 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2042 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2043 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2044
2045 RTC_DCHECK(call_.get());
2046 call_->SetBitrateConfigMask(mask);
2047
2048 return RTCError::OK();
2049}
2050
Alex Narest78609d52017-10-20 10:37:47 +02002051void PeerConnection::SetBitrateAllocationStrategy(
2052 std::unique_ptr<rtc::BitrateAllocationStrategy>
2053 bitrate_allocation_strategy) {
2054 rtc::Thread* worker_thread = factory_->worker_thread();
2055 if (!worker_thread->IsCurrent()) {
2056 rtc::BitrateAllocationStrategy* strategy_raw =
2057 bitrate_allocation_strategy.release();
2058 auto functor = [this, strategy_raw]() {
2059 call_->SetBitrateAllocationStrategy(
2060 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2061 };
2062 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2063 return;
2064 }
2065 RTC_DCHECK(call_.get());
2066 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2067}
2068
henrika5f6bf242017-11-01 11:06:56 +01002069void PeerConnection::SetAudioPlayout(bool playout) {
2070 if (!worker_thread()->IsCurrent()) {
2071 worker_thread()->Invoke<void>(
2072 RTC_FROM_HERE,
2073 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2074 return;
2075 }
2076 auto audio_state =
2077 factory_->channel_manager()->media_engine()->GetAudioState();
2078 audio_state->SetPlayout(playout);
2079}
2080
2081void PeerConnection::SetAudioRecording(bool recording) {
2082 if (!worker_thread()->IsCurrent()) {
2083 worker_thread()->Invoke<void>(
2084 RTC_FROM_HERE,
2085 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2086 return;
2087 }
2088 auto audio_state =
2089 factory_->channel_manager()->media_engine()->GetAudioState();
2090 audio_state->SetRecording(recording);
2091}
2092
Steve Anton8c0f7a72017-10-03 10:03:10 -07002093std::unique_ptr<rtc::SSLCertificate>
2094PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002095 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002096 return nullptr;
2097 }
Steve Anton75737c02017-11-06 10:37:17 -08002098 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002099}
2100
ivoc14d5dbe2016-07-04 07:06:55 -07002101bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2102 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002103 // TODO(eladalon): It would be better to not allow negative values into PC.
2104 const size_t max_size = (max_size_bytes < 0)
2105 ? RtcEventLog::kUnlimitedOutput
2106 : rtc::saturated_cast<size_t>(max_size_bytes);
2107 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002108 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2109 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002110}
2111
Bjorn Tereliusde939432017-11-20 17:38:14 +01002112bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2113 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002114 // TODO(eladalon): In C++14, this can be done with a lambda.
2115 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002116 bool operator()() {
2117 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2118 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002119 PeerConnection* const pc;
2120 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002121 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002122 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002123 return worker_thread()->Invoke<bool>(
2124 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002125}
2126
2127void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002128 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002129 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2130}
2131
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002133 return pending_local_description_ ? pending_local_description_.get()
2134 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135}
2136
2137const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002138 return pending_remote_description_ ? pending_remote_description_.get()
2139 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140}
2141
deadbeeffe4a8a42016-12-20 17:56:17 -08002142const SessionDescriptionInterface* PeerConnection::current_local_description()
2143 const {
Steve Anton75737c02017-11-06 10:37:17 -08002144 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002145}
2146
2147const SessionDescriptionInterface* PeerConnection::current_remote_description()
2148 const {
Steve Anton75737c02017-11-06 10:37:17 -08002149 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002150}
2151
2152const SessionDescriptionInterface* PeerConnection::pending_local_description()
2153 const {
Steve Anton75737c02017-11-06 10:37:17 -08002154 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002155}
2156
2157const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2158 const {
Steve Anton75737c02017-11-06 10:37:17 -08002159 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002160}
2161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002163 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164 // Update stats here so that we have the most recent stats for tracks and
2165 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002166 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167
Steve Anton75737c02017-11-06 10:37:17 -08002168 ChangeSignalingState(PeerConnectionInterface::kClosed);
2169 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002170 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2171 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002172 RTC_DCHECK(!rtp_data_channel_);
2173 RTC_DCHECK(!sctp_transport_);
2174
deadbeef42a42632017-03-10 15:18:00 -08002175 network_thread()->Invoke<void>(
2176 RTC_FROM_HERE,
2177 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2178 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002179
Steve Anton978b8762017-09-29 12:15:02 -07002180 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002181 call_.reset();
2182 // The event log must outlive call (and any other object that uses it).
2183 event_log_.reset();
2184 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185}
2186
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002187void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2190 SetSessionDescriptionMsg* param =
2191 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2192 param->observer->OnSuccess();
2193 delete param;
2194 break;
2195 }
2196 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2197 SetSessionDescriptionMsg* param =
2198 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2199 param->observer->OnFailure(param->error);
2200 delete param;
2201 break;
2202 }
deadbeefab9b2d12015-10-14 11:33:11 -07002203 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2204 CreateSessionDescriptionMsg* param =
2205 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2206 param->observer->OnFailure(param->error);
2207 delete param;
2208 break;
2209 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 case MSG_GETSTATS: {
2211 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002212 StatsReports reports;
2213 stats_->GetStats(param->track, &reports);
2214 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 delete param;
2216 break;
2217 }
deadbeefbd292462015-12-14 18:15:29 -08002218 case MSG_FREE_DATACHANNELS: {
2219 sctp_data_channels_to_free_.clear();
2220 break;
2221 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002222 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002223 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 break;
2225 }
2226}
2227
Steve Anton4171afb2017-11-20 10:20:22 -08002228void PeerConnection::CreateAudioReceiver(
2229 MediaStreamInterface* stream,
2230 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002231 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2232 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002233 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2234 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002235 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002236 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002237 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002238 stream->AddTrack(
2239 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002240 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002241 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242}
2243
Steve Anton4171afb2017-11-20 10:20:22 -08002244void PeerConnection::CreateVideoReceiver(
2245 MediaStreamInterface* stream,
2246 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002247 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2248 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002249 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2250 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002251 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002252 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2253 worker_thread(), remote_sender_info.first_ssrc,
2254 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002255 stream->AddTrack(
2256 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002257 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002258 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259}
2260
deadbeef70ab1a12015-09-28 16:53:55 -07002261// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2262// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002263rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002264 const RtpSenderInfo& remote_sender_info) {
2265 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2266 if (!receiver) {
2267 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2268 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002269 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002270 }
Steve Anton4171afb2017-11-20 10:20:22 -08002271 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2272 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2273 } else {
2274 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2275 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002276 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277}
2278
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002279void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2280 MediaStreamInterface* stream) {
2281 RTC_DCHECK(!IsClosed());
2282 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002283 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002284 // We already have a sender for this track, so just change the stream_id
2285 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002286 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002287 return;
2288 }
2289
2290 // Normal case; we've never seen this track before.
2291 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2292 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2293 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002294 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2295 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002296 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002297 // If the sender has already been configured in SDP, we call SetSsrc,
2298 // which will connect the sender to the underlying transport. This can
2299 // occur if a local session description that contains the ID of the sender
2300 // is set before AddStream is called. It can also occur if the local
2301 // session description is not changed and RemoveStream is called, and
2302 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002303 const RtpSenderInfo* sender_info =
2304 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2305 if (sender_info) {
2306 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002307 }
2308}
2309
2310// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2311// indefinitely, when we have unified plan SDP.
2312void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2313 MediaStreamInterface* stream) {
2314 RTC_DCHECK(!IsClosed());
2315 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002316 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002317 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2318 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002319 return;
2320 }
Steve Anton4171afb2017-11-20 10:20:22 -08002321 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002322}
2323
2324void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2325 MediaStreamInterface* stream) {
2326 RTC_DCHECK(!IsClosed());
2327 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002328 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002329 // We already have a sender for this track, so just change the stream_id
2330 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002331 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002332 return;
2333 }
2334
2335 // Normal case; we've never seen this track before.
2336 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2337 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002338 signaling_thread(),
2339 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002340 GetVideoTransceiver()->internal()->AddSender(new_sender);
2341 const RtpSenderInfo* sender_info =
2342 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2343 if (sender_info) {
2344 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002345 }
2346}
2347
2348void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2349 MediaStreamInterface* stream) {
2350 RTC_DCHECK(!IsClosed());
2351 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002352 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002353 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2354 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002355 return;
2356 }
Steve Anton4171afb2017-11-20 10:20:22 -08002357 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002358}
2359
Steve Antonba818672017-11-06 10:21:57 -08002360void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002361 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002362 if (ice_connection_state_ == new_state) {
2363 return;
2364 }
2365
deadbeefcbecd352015-09-23 11:50:27 -07002366 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002367 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002368 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002369 return;
2370 }
Steve Antonba818672017-11-06 10:21:57 -08002371
Mirko Bonadei675513b2017-11-09 11:09:25 +01002372 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2373 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002374 RTC_DCHECK(ice_connection_state_ !=
2375 PeerConnectionInterface::kIceConnectionClosed);
2376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002378 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379}
2380
2381void PeerConnection::OnIceGatheringChange(
2382 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002383 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 if (IsClosed()) {
2385 return;
2386 }
2387 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002388 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389}
2390
jbauch81bf7b02017-03-25 08:31:12 -07002391void PeerConnection::OnIceCandidate(
2392 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002393 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002394 if (IsClosed()) {
2395 return;
2396 }
jbauch81bf7b02017-03-25 08:31:12 -07002397 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398}
2399
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002400void PeerConnection::OnIceCandidatesRemoved(
2401 const std::vector<cricket::Candidate>& candidates) {
2402 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002403 if (IsClosed()) {
2404 return;
2405 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002406 observer_->OnIceCandidatesRemoved(candidates);
2407}
2408
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002409void PeerConnection::ChangeSignalingState(
2410 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002411 RTC_DCHECK(signaling_thread()->IsCurrent());
2412 if (signaling_state_ == signaling_state) {
2413 return;
2414 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002415 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2416 << GetSignalingStateString(signaling_state_)
2417 << " New state: "
2418 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 signaling_state_ = signaling_state;
2420 if (signaling_state == kClosed) {
2421 ice_connection_state_ = kIceConnectionClosed;
2422 observer_->OnIceConnectionChange(ice_connection_state_);
2423 if (ice_gathering_state_ != kIceGatheringComplete) {
2424 ice_gathering_state_ = kIceGatheringComplete;
2425 observer_->OnIceGatheringChange(ice_gathering_state_);
2426 }
2427 }
2428 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002429}
2430
deadbeefeb459812015-12-15 19:24:43 -08002431void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2432 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002433 if (IsClosed()) {
2434 return;
2435 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002436 AddAudioTrack(track, stream);
2437 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002438}
2439
deadbeefeb459812015-12-15 19:24:43 -08002440void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2441 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002442 if (IsClosed()) {
2443 return;
2444 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002445 RemoveAudioTrack(track, stream);
2446 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002447}
2448
2449void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2450 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002451 if (IsClosed()) {
2452 return;
2453 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002454 AddVideoTrack(track, stream);
2455 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002456}
2457
2458void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2459 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002460 if (IsClosed()) {
2461 return;
2462 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002463 RemoveVideoTrack(track, stream);
2464 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002465}
2466
Henrik Boström31638672017-11-23 17:48:32 +01002467void PeerConnection::PostSetSessionDescriptionSuccess(
2468 SetSessionDescriptionObserver* observer) {
2469 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2470 signaling_thread()->Post(RTC_FROM_HERE, this,
2471 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2472}
2473
deadbeefab9b2d12015-10-14 11:33:11 -07002474void PeerConnection::PostSetSessionDescriptionFailure(
2475 SetSessionDescriptionObserver* observer,
2476 const std::string& error) {
2477 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2478 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002479 signaling_thread()->Post(RTC_FROM_HERE, this,
2480 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002481}
2482
2483void PeerConnection::PostCreateSessionDescriptionFailure(
2484 CreateSessionDescriptionObserver* observer,
2485 const std::string& error) {
2486 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2487 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002488 signaling_thread()->Post(RTC_FROM_HERE, this,
2489 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002490}
2491
zhihuang1c378ed2017-08-17 14:10:50 -07002492void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002493 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2494 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002495 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2496
2497 // Figure out transceiver directional preferences.
2498 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2499 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2500
2501 // By default, generate sendrecv/recvonly m= sections.
2502 bool recv_audio = true;
2503 bool recv_video = true;
2504
2505 // By default, only offer a new m= section if we have media to send with it.
2506 bool offer_new_audio_description = send_audio;
2507 bool offer_new_video_description = send_video;
2508 bool offer_new_data_description = HasDataChannels();
2509
2510 // The "offer_to_receive_X" options allow those defaults to be overridden.
2511 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2512 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2513 offer_new_audio_description =
2514 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2515 }
2516 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2517 recv_video = (rtc_options.offer_to_receive_video > 0);
2518 offer_new_video_description =
2519 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2520 }
2521
2522 rtc::Optional<size_t> audio_index;
2523 rtc::Optional<size_t> video_index;
2524 rtc::Optional<size_t> data_index;
2525 // If a current description exists, generate m= sections in the same order,
2526 // using the first audio/video/data section that appears and rejecting
2527 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002528 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002529 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002530 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002531 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2532 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2533 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002534 }
2535
zhihuang1c378ed2017-08-17 14:10:50 -07002536 // Add audio/video/data m= sections to the end if needed.
2537 if (!audio_index && offer_new_audio_description) {
2538 session_options->media_description_options.push_back(
2539 cricket::MediaDescriptionOptions(
2540 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002541 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2542 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002543 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002544 }
zhihuang1c378ed2017-08-17 14:10:50 -07002545 if (!video_index && offer_new_video_description) {
2546 session_options->media_description_options.push_back(
2547 cricket::MediaDescriptionOptions(
2548 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002549 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2550 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002551 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002552 }
zhihuang1c378ed2017-08-17 14:10:50 -07002553 if (!data_index && offer_new_data_description) {
2554 session_options->media_description_options.push_back(
2555 cricket::MediaDescriptionOptions(
2556 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002557 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002558 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002559 }
2560
2561 cricket::MediaDescriptionOptions* audio_media_description_options =
2562 !audio_index ? nullptr
2563 : &session_options->media_description_options[*audio_index];
2564 cricket::MediaDescriptionOptions* video_media_description_options =
2565 !video_index ? nullptr
2566 : &session_options->media_description_options[*video_index];
2567 cricket::MediaDescriptionOptions* data_media_description_options =
2568 !data_index ? nullptr
2569 : &session_options->media_description_options[*data_index];
2570
2571 // Apply ICE restart flag and renomination flag.
2572 for (auto& options : session_options->media_description_options) {
2573 options.transport_options.ice_restart = rtc_options.ice_restart;
2574 options.transport_options.enable_ice_renomination =
2575 configuration_.enable_ice_renomination;
2576 }
2577
Steve Anton4171afb2017-11-20 10:20:22 -08002578 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002579 video_media_description_options);
2580 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002581
zhihuang9763d562016-08-05 11:14:50 -07002582 // Intentionally unset the data channel type for RTP data channel with the
2583 // second condition. Otherwise the RTP data channels would be successfully
2584 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2585 // when building with chromium. We want to leave RTP data channels broken, so
2586 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002587 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2588 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002589 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002590
2591 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002592 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002593}
2594
zhihuang1c378ed2017-08-17 14:10:50 -07002595void PeerConnection::GetOptionsForAnswer(
2596 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002597 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002598 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002599
zhihuang1c378ed2017-08-17 14:10:50 -07002600 // Figure out transceiver directional preferences.
2601 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2602 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2603
2604 // By default, generate sendrecv/recvonly m= sections. The direction is also
2605 // restricted by the direction in the offer.
2606 bool recv_audio = true;
2607 bool recv_video = true;
2608
2609 // The "offer_to_receive_X" options allow those defaults to be overridden.
2610 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2611 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002612 }
zhihuang1c378ed2017-08-17 14:10:50 -07002613 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2614 recv_video = (rtc_options.offer_to_receive_video > 0);
2615 }
2616
2617 rtc::Optional<size_t> audio_index;
2618 rtc::Optional<size_t> video_index;
2619 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002620 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002621 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002622 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002623 SessionDescriptionInterface::kOffer);
2624 // Generate m= sections that match those in the offer.
2625 // Note that mediasession.cc will handle intersection our preferred
2626 // direction with the offered direction.
2627 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002628 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002629 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2630 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2631 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002632 }
zhihuang1c378ed2017-08-17 14:10:50 -07002633
2634 cricket::MediaDescriptionOptions* audio_media_description_options =
2635 !audio_index ? nullptr
2636 : &session_options->media_description_options[*audio_index];
2637 cricket::MediaDescriptionOptions* video_media_description_options =
2638 !video_index ? nullptr
2639 : &session_options->media_description_options[*video_index];
2640 cricket::MediaDescriptionOptions* data_media_description_options =
2641 !data_index ? nullptr
2642 : &session_options->media_description_options[*data_index];
2643
2644 // Apply ICE renomination flag.
2645 for (auto& options : session_options->media_description_options) {
2646 options.transport_options.enable_ice_renomination =
2647 configuration_.enable_ice_renomination;
2648 }
2649
Steve Anton4171afb2017-11-20 10:20:22 -08002650 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002651 video_media_description_options);
2652 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2653
zhihuang9763d562016-08-05 11:14:50 -07002654 // Intentionally unset the data channel type for RTP data channel. Otherwise
2655 // the RTP data channels would be successfully negotiated by default and the
2656 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2657 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002658 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2659 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002660 }
zhihuangaf388472016-11-02 16:49:48 -07002661
zhihuang1c378ed2017-08-17 14:10:50 -07002662 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002663 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002664}
2665
zhihuang1c378ed2017-08-17 14:10:50 -07002666void PeerConnection::GenerateMediaDescriptionOptions(
2667 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002668 RtpTransceiverDirection audio_direction,
2669 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002670 rtc::Optional<size_t>* audio_index,
2671 rtc::Optional<size_t>* video_index,
2672 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002673 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002674 for (const cricket::ContentInfo& content :
2675 session_desc->description()->contents()) {
2676 if (IsAudioContent(&content)) {
2677 // If we already have an audio m= section, reject this extra one.
2678 if (*audio_index) {
2679 session_options->media_description_options.push_back(
2680 cricket::MediaDescriptionOptions(
2681 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002682 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002683 } else {
2684 session_options->media_description_options.push_back(
2685 cricket::MediaDescriptionOptions(
2686 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002687 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002688 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002689 }
2690 } else if (IsVideoContent(&content)) {
2691 // If we already have an video m= section, reject this extra one.
2692 if (*video_index) {
2693 session_options->media_description_options.push_back(
2694 cricket::MediaDescriptionOptions(
2695 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002696 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002697 } else {
2698 session_options->media_description_options.push_back(
2699 cricket::MediaDescriptionOptions(
2700 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002701 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002702 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002703 }
2704 } else {
2705 RTC_DCHECK(IsDataContent(&content));
2706 // If we already have an data m= section, reject this extra one.
2707 if (*data_index) {
2708 session_options->media_description_options.push_back(
2709 cricket::MediaDescriptionOptions(
2710 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002711 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002712 } else {
2713 session_options->media_description_options.push_back(
2714 cricket::MediaDescriptionOptions(
2715 cricket::MEDIA_TYPE_DATA, content.name,
2716 // Direction for data sections is meaningless, but legacy
2717 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002718 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002719 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002720 }
2721 }
htaa2a49d92016-03-04 02:51:39 -08002722 }
deadbeefab9b2d12015-10-14 11:33:11 -07002723}
2724
Steve Anton4171afb2017-11-20 10:20:22 -08002725void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2726 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2727 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002728 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002729}
2730
Steve Anton4171afb2017-11-20 10:20:22 -08002731void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002732 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002733 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002734 cricket::MediaType media_type,
2735 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002736 std::vector<RtpSenderInfo>* current_senders =
2737 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002738
Steve Anton4171afb2017-11-20 10:20:22 -08002739 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002740 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002741 for (auto sender_it = current_senders->begin();
2742 sender_it != current_senders->end();
2743 /* incremented manually */) {
2744 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002745 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002746 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2747 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002748 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002749 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2750 sender_exists) {
2751 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002752 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002753 OnRemoteSenderRemoved(info, media_type);
2754 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002755 }
2756 }
2757
Steve Anton4171afb2017-11-20 10:20:22 -08002758 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002759 for (const cricket::StreamParams& params : streams) {
2760 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002761 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002762 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002763 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002764 uint32_t ssrc = params.first_ssrc();
2765
2766 rtc::scoped_refptr<MediaStreamInterface> stream =
2767 remote_streams_->find(stream_label);
2768 if (!stream) {
2769 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002770 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2771 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002772 remote_streams_->AddStream(stream);
2773 new_streams->AddStream(stream);
2774 }
2775
Steve Anton4171afb2017-11-20 10:20:22 -08002776 const RtpSenderInfo* sender_info =
2777 FindSenderInfo(*current_senders, stream_label, sender_id);
2778 if (!sender_info) {
2779 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2780 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002781 }
2782 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002783
Steve Anton4171afb2017-11-20 10:20:22 -08002784 // Add default sender if necessary.
2785 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002786 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2787 remote_streams_->find(kDefaultStreamLabel);
2788 if (!default_stream) {
2789 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002790 default_stream = MediaStreamProxy::Create(
2791 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002792 remote_streams_->AddStream(default_stream);
2793 new_streams->AddStream(default_stream);
2794 }
Steve Anton4171afb2017-11-20 10:20:22 -08002795 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2796 ? kDefaultAudioSenderId
2797 : kDefaultVideoSenderId;
2798 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2799 *current_senders, kDefaultStreamLabel, default_sender_id);
2800 if (!default_sender_info) {
2801 current_senders->push_back(
2802 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2803 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002804 }
2805 }
deadbeefab9b2d12015-10-14 11:33:11 -07002806}
2807
Steve Anton4171afb2017-11-20 10:20:22 -08002808void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2809 cricket::MediaType media_type) {
2810 MediaStreamInterface* stream =
2811 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002812
2813 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002814 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002815 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002816 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002817 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002818 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002819 }
2820}
2821
Steve Anton4171afb2017-11-20 10:20:22 -08002822void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2823 cricket::MediaType media_type) {
2824 MediaStreamInterface* stream =
2825 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002826
Henrik Boström933d8b02017-10-10 10:05:16 -07002827 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002828 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002829 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2830 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002831 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002832 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002833 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002834 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002835 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002836 }
2837 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002838 // Stopping or destroying a VideoRtpReceiver will end the
2839 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002840 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002841 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002842 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002843 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002844 // There's no guarantee the track is still available, e.g. the track may
2845 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002846 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002847 }
2848 } else {
nisseede5da42017-01-12 05:15:36 -08002849 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002850 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002851 if (receiver) {
2852 observer_->OnRemoveTrack(receiver);
2853 }
deadbeefab9b2d12015-10-14 11:33:11 -07002854}
2855
2856void PeerConnection::UpdateEndedRemoteMediaStreams() {
2857 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2858 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2859 MediaStreamInterface* stream = remote_streams_->at(i);
2860 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2861 streams_to_remove.push_back(stream);
2862 }
2863 }
2864
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002865 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002866 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002867 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002868 }
2869}
2870
Steve Anton4171afb2017-11-20 10:20:22 -08002871void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002872 const std::vector<cricket::StreamParams>& streams,
2873 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002874 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002875
2876 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2877 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002878 for (auto sender_it = current_senders->begin();
2879 sender_it != current_senders->end();
2880 /* incremented manually */) {
2881 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002882 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002883 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2884 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002885 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002886 OnLocalSenderRemoved(info, media_type);
2887 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002888 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002889 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002890 }
2891 }
2892
Steve Anton4171afb2017-11-20 10:20:22 -08002893 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002894 for (const cricket::StreamParams& params : streams) {
2895 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002896 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002897 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002898 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002899 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002900 const RtpSenderInfo* sender_info =
2901 FindSenderInfo(*current_senders, stream_label, sender_id);
2902 if (!sender_info) {
2903 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2904 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002905 }
2906 }
2907}
2908
Steve Anton4171afb2017-11-20 10:20:22 -08002909void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2910 cricket::MediaType media_type) {
2911 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002912 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002913 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2914 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002915 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002916 return;
2917 }
2918
deadbeeffac06552015-11-25 11:26:01 -08002919 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002920 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2921 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002922 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002923 }
deadbeeffac06552015-11-25 11:26:01 -08002924
Steve Anton4171afb2017-11-20 10:20:22 -08002925 sender->internal()->set_stream_id(sender_info.stream_label);
2926 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002927}
2928
Steve Anton4171afb2017-11-20 10:20:22 -08002929void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2930 cricket::MediaType media_type) {
2931 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002932 if (!sender) {
2933 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002934 // SessionDescriptions has been renegotiated.
2935 return;
2936 }
deadbeeffac06552015-11-25 11:26:01 -08002937
2938 // A sender has been removed from the SessionDescription but it's still
2939 // associated with the PeerConnection. This only occurs if the SDP doesn't
2940 // match with the calls to CreateSender, AddStream and RemoveStream.
2941 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002942 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2943 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002944 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002945 }
deadbeeffac06552015-11-25 11:26:01 -08002946
Steve Anton4171afb2017-11-20 10:20:22 -08002947 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002948}
2949
2950void PeerConnection::UpdateLocalRtpDataChannels(
2951 const cricket::StreamParamsVec& streams) {
2952 std::vector<std::string> existing_channels;
2953
2954 // Find new and active data channels.
2955 for (const cricket::StreamParams& params : streams) {
2956 // |it->sync_label| is actually the data channel label. The reason is that
2957 // we use the same naming of data channels as we do for
2958 // MediaStreams and Tracks.
2959 // For MediaStreams, the sync_label is the MediaStream label and the
2960 // track label is the same as |streamid|.
2961 const std::string& channel_label = params.sync_label;
2962 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002963 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002964 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002965 continue;
2966 }
2967 // Set the SSRC the data channel should use for sending.
2968 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2969 existing_channels.push_back(data_channel_it->first);
2970 }
2971
2972 UpdateClosingRtpDataChannels(existing_channels, true);
2973}
2974
2975void PeerConnection::UpdateRemoteRtpDataChannels(
2976 const cricket::StreamParamsVec& streams) {
2977 std::vector<std::string> existing_channels;
2978
2979 // Find new and active data channels.
2980 for (const cricket::StreamParams& params : streams) {
2981 // The data channel label is either the mslabel or the SSRC if the mslabel
2982 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2983 std::string label = params.sync_label.empty()
2984 ? rtc::ToString(params.first_ssrc())
2985 : params.sync_label;
2986 auto data_channel_it = rtp_data_channels_.find(label);
2987 if (data_channel_it == rtp_data_channels_.end()) {
2988 // This is a new data channel.
2989 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2990 } else {
2991 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2992 }
2993 existing_channels.push_back(label);
2994 }
2995
2996 UpdateClosingRtpDataChannels(existing_channels, false);
2997}
2998
2999void PeerConnection::UpdateClosingRtpDataChannels(
3000 const std::vector<std::string>& active_channels,
3001 bool is_local_update) {
3002 auto it = rtp_data_channels_.begin();
3003 while (it != rtp_data_channels_.end()) {
3004 DataChannel* data_channel = it->second;
3005 if (std::find(active_channels.begin(), active_channels.end(),
3006 data_channel->label()) != active_channels.end()) {
3007 ++it;
3008 continue;
3009 }
3010
3011 if (is_local_update) {
3012 data_channel->SetSendSsrc(0);
3013 } else {
3014 data_channel->RemotePeerRequestClose();
3015 }
3016
3017 if (data_channel->state() == DataChannel::kClosed) {
3018 rtp_data_channels_.erase(it);
3019 it = rtp_data_channels_.begin();
3020 } else {
3021 ++it;
3022 }
3023 }
3024}
3025
3026void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3027 uint32_t remote_ssrc) {
3028 rtc::scoped_refptr<DataChannel> channel(
3029 InternalCreateDataChannel(label, nullptr));
3030 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003031 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3032 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003033 return;
3034 }
3035 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003036 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3037 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003038 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003039}
3040
3041rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3042 const std::string& label,
3043 const InternalDataChannelInit* config) {
3044 if (IsClosed()) {
3045 return nullptr;
3046 }
Steve Anton75737c02017-11-06 10:37:17 -08003047 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003048 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003049 << "InternalCreateDataChannel: Data is not supported in this call.";
3050 return nullptr;
3051 }
3052 InternalDataChannelInit new_config =
3053 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003054 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003055 if (new_config.id < 0) {
3056 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003057 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003058 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003059 RTC_LOG(LS_ERROR)
3060 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003061 return nullptr;
3062 }
3063 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003064 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3065 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003066 return nullptr;
3067 }
3068 }
3069
Steve Anton75737c02017-11-06 10:37:17 -08003070 rtc::scoped_refptr<DataChannel> channel(
3071 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003072 if (!channel) {
3073 sid_allocator_.ReleaseSid(new_config.id);
3074 return nullptr;
3075 }
3076
3077 if (channel->data_channel_type() == cricket::DCT_RTP) {
3078 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003079 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3080 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003081 return nullptr;
3082 }
3083 rtp_data_channels_[channel->label()] = channel;
3084 } else {
3085 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3086 sctp_data_channels_.push_back(channel);
3087 channel->SignalClosed.connect(this,
3088 &PeerConnection::OnSctpDataChannelClosed);
3089 }
3090
hbos82ebe022016-11-14 01:41:09 -08003091 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003092 return channel;
3093}
3094
3095bool PeerConnection::HasDataChannels() const {
3096 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3097}
3098
3099void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3100 for (const auto& channel : sctp_data_channels_) {
3101 if (channel->id() < 0) {
3102 int sid;
3103 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003104 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003105 continue;
3106 }
3107 channel->SetSctpSid(sid);
3108 }
3109 }
3110}
3111
3112void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003113 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003114 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3115 ++it) {
3116 if (it->get() == channel) {
3117 if (channel->id() >= 0) {
3118 sid_allocator_.ReleaseSid(channel->id());
3119 }
deadbeefbd292462015-12-14 18:15:29 -08003120 // Since this method is triggered by a signal from the DataChannel,
3121 // we can't free it directly here; we need to free it asynchronously.
3122 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003123 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003124 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3125 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003126 return;
3127 }
3128 }
3129}
3130
deadbeefab9b2d12015-10-14 11:33:11 -07003131void PeerConnection::OnDataChannelDestroyed() {
3132 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3133 // DataChannel may callback to us and try to modify the list.
3134 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3135 temp_rtp_dcs.swap(rtp_data_channels_);
3136 for (const auto& kv : temp_rtp_dcs) {
3137 kv.second->OnTransportChannelDestroyed();
3138 }
3139
3140 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3141 temp_sctp_dcs.swap(sctp_data_channels_);
3142 for (const auto& channel : temp_sctp_dcs) {
3143 channel->OnTransportChannelDestroyed();
3144 }
3145}
3146
3147void PeerConnection::OnDataChannelOpenMessage(
3148 const std::string& label,
3149 const InternalDataChannelInit& config) {
3150 rtc::scoped_refptr<DataChannel> channel(
3151 InternalCreateDataChannel(label, &config));
3152 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003153 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003154 return;
3155 }
3156
deadbeefa601f5c2016-06-06 14:27:39 -07003157 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3158 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003159 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003160}
3161
Steve Anton4171afb2017-11-20 10:20:22 -08003162rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3163PeerConnection::GetAudioTransceiver() const {
3164 // This method only works with Plan B SDP, where there is a single
3165 // audio/video transceiver.
3166 RTC_DCHECK(!IsUnifiedPlan());
3167 for (auto transceiver : transceivers_) {
3168 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3169 return transceiver;
3170 }
3171 }
3172 RTC_NOTREACHED();
3173 return nullptr;
3174}
3175
3176rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3177PeerConnection::GetVideoTransceiver() const {
3178 // This method only works with Plan B SDP, where there is a single
3179 // audio/video transceiver.
3180 RTC_DCHECK(!IsUnifiedPlan());
3181 for (auto transceiver : transceivers_) {
3182 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3183 return transceiver;
3184 }
3185 }
3186 RTC_NOTREACHED();
3187 return nullptr;
3188}
3189
3190// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3191// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003192bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003193 switch (type) {
3194 case cricket::MEDIA_TYPE_AUDIO:
3195 return !GetAudioTransceiver()->internal()->senders().empty();
3196 case cricket::MEDIA_TYPE_VIDEO:
3197 return !GetVideoTransceiver()->internal()->senders().empty();
3198 case cricket::MEDIA_TYPE_DATA:
3199 return false;
3200 }
3201 RTC_NOTREACHED();
3202 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003203}
3204
Steve Anton4171afb2017-11-20 10:20:22 -08003205rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3206PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3207 for (auto transceiver : transceivers_) {
3208 for (auto sender : transceiver->internal()->senders()) {
3209 if (sender->track() == track) {
3210 return sender;
3211 }
3212 }
3213 }
3214 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003215}
3216
Steve Anton4171afb2017-11-20 10:20:22 -08003217rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3218PeerConnection::FindSenderById(const std::string& sender_id) const {
3219 for (auto transceiver : transceivers_) {
3220 for (auto sender : transceiver->internal()->senders()) {
3221 if (sender->id() == sender_id) {
3222 return sender;
3223 }
3224 }
3225 }
3226 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003227}
3228
Steve Anton4171afb2017-11-20 10:20:22 -08003229rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3230PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3231 for (auto transceiver : transceivers_) {
3232 for (auto receiver : transceiver->internal()->receivers()) {
3233 if (receiver->id() == receiver_id) {
3234 return receiver;
3235 }
3236 }
3237 }
3238 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003239}
3240
Steve Anton4171afb2017-11-20 10:20:22 -08003241std::vector<PeerConnection::RtpSenderInfo>*
3242PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3243 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3244 media_type == cricket::MEDIA_TYPE_VIDEO);
3245 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3246 ? &remote_audio_sender_infos_
3247 : &remote_video_sender_infos_;
3248}
3249
3250std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003251 cricket::MediaType media_type) {
3252 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3253 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003254 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3255 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003256}
3257
Steve Anton4171afb2017-11-20 10:20:22 -08003258const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3259 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003260 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003261 const std::string sender_id) const {
3262 for (const RtpSenderInfo& sender_info : infos) {
3263 if (sender_info.stream_label == stream_label &&
3264 sender_info.sender_id == sender_id) {
3265 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003266 }
3267 }
3268 return nullptr;
3269}
3270
3271DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3272 for (const auto& channel : sctp_data_channels_) {
3273 if (channel->id() == sid) {
3274 return channel;
3275 }
3276 }
3277 return nullptr;
3278}
3279
deadbeef91dd5672016-05-18 16:55:30 -07003280bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003281 const RTCConfiguration& configuration) {
3282 cricket::ServerAddresses stun_servers;
3283 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003284 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3285 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003286 return false;
3287 }
3288
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003289 port_allocator_->Initialize();
3290
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003291 // To handle both internal and externally created port allocator, we will
3292 // enable BUNDLE here.
3293 int portallocator_flags = port_allocator_->flags();
3294 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003295 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3296 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003297 // If the disable-IPv6 flag was specified, we'll not override it
3298 // by experiment.
3299 if (configuration.disable_ipv6) {
3300 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003301 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3302 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003303 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3304 }
3305
zhihuangb09b3f92017-03-07 14:40:51 -08003306 if (configuration.disable_ipv6_on_wifi) {
3307 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003308 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003309 }
3310
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003311 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3312 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003313 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003314 }
3315
honghaiz60347052016-05-31 18:29:12 -07003316 if (configuration.candidate_network_policy ==
3317 kCandidateNetworkPolicyLowCost) {
3318 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003319 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003320 }
3321
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003322 port_allocator_->set_flags(portallocator_flags);
3323 // No step delay is used while allocating ports.
3324 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3325 port_allocator_->set_candidate_filter(
3326 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003327 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003328
3329 // Call this last since it may create pooled allocator sessions using the
3330 // properties set above.
3331 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003332 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003333 configuration.prune_turn_ports,
3334 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003335 return true;
3336}
3337
deadbeef91dd5672016-05-18 16:55:30 -07003338bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003339 const cricket::ServerAddresses& stun_servers,
3340 const std::vector<cricket::RelayServerConfig>& turn_servers,
3341 IceTransportsType type,
3342 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003343 bool prune_turn_ports,
3344 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003345 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003346 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003347 // Call this last since it may create pooled allocator sessions using the
3348 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003349 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003350 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3351 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003352}
3353
Steve Antonba818672017-11-06 10:21:57 -08003354cricket::ChannelManager* PeerConnection::channel_manager() const {
3355 return factory_->channel_manager();
3356}
3357
3358MetricsObserverInterface* PeerConnection::metrics_observer() const {
3359 return uma_observer_;
3360}
3361
Elad Alon99c3fe52017-10-13 16:29:40 +02003362bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003363 std::unique_ptr<RtcEventLogOutput> output,
3364 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003365 if (!event_log_) {
3366 return false;
3367 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003368 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003369}
3370
3371void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003372 if (event_log_) {
3373 event_log_->StopLogging();
3374 }
ivoc14d5dbe2016-07-04 07:06:55 -07003375}
nisseeaabdf62017-05-05 02:23:02 -07003376
Steve Anton75737c02017-11-06 10:37:17 -08003377cricket::BaseChannel* PeerConnection::GetChannel(
3378 const std::string& content_name) {
3379 if (voice_channel() && voice_channel()->content_name() == content_name) {
3380 return voice_channel();
3381 }
3382 if (video_channel() && video_channel()->content_name() == content_name) {
3383 return video_channel();
3384 }
3385 if (rtp_data_channel() &&
3386 rtp_data_channel()->content_name() == content_name) {
3387 return rtp_data_channel();
3388 }
3389 return nullptr;
3390}
3391
3392bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3393 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003394 RTC_LOG(LS_INFO)
3395 << "Local and Remote descriptions must be applied to get the "
3396 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003397 return false;
3398 }
3399 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003400 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3401 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003402 return false;
3403 }
3404
3405 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3406}
3407
3408bool PeerConnection::GetSslRole(const std::string& content_name,
3409 rtc::SSLRole* role) {
3410 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003411 RTC_LOG(LS_INFO)
3412 << "Local and Remote descriptions must be applied to get the "
3413 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003414 return false;
3415 }
3416
3417 return transport_controller_->GetSslRole(GetTransportName(content_name),
3418 role);
3419}
3420
Henrik Boström31638672017-11-23 17:48:32 +01003421bool PeerConnection::SetCurrentOrPendingLocalDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003422 std::unique_ptr<SessionDescriptionInterface> desc,
3423 std::string* err_desc) {
3424 RTC_DCHECK(signaling_thread()->IsCurrent());
3425
3426 // Validate SDP.
3427 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3428 return false;
3429 }
3430
3431 // Update the initial_offerer flag if this session is the initial_offerer.
3432 Action action = GetAction(desc->type());
3433 if (!initial_offerer_.has_value()) {
3434 initial_offerer_.emplace(action == kOffer);
3435 if (*initial_offerer_) {
3436 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3437 } else {
3438 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3439 }
3440 }
3441
3442 if (action == kAnswer) {
3443 current_local_description_ = std::move(desc);
3444 pending_local_description_ = nullptr;
3445 current_remote_description_ = std::move(pending_remote_description_);
3446 } else {
3447 pending_local_description_ = std::move(desc);
3448 }
3449
3450 // Transport and Media channels will be created only when offer is set.
3451 if (action == kOffer && !CreateChannels(local_description()->description())) {
3452 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3453 // is applied. Restore back to old description.
3454 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3455 err_desc);
3456 }
3457
3458 // Remove unused channels if MediaContentDescription is rejected.
3459 RemoveUnusedChannels(local_description()->description());
3460
3461 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3462 return false;
3463 }
3464 if (remote_description()) {
3465 // Now that we have a local description, we can push down remote candidates.
3466 UseCandidatesInSessionDescription(remote_description());
3467 }
3468
3469 pending_ice_restarts_.clear();
3470 if (error() != ERROR_NONE) {
3471 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3472 err_desc);
3473 }
3474 return true;
3475}
3476
Henrik Boström31638672017-11-23 17:48:32 +01003477bool PeerConnection::SetCurrentOrPendingRemoteDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003478 std::unique_ptr<SessionDescriptionInterface> desc,
3479 std::string* err_desc) {
3480 RTC_DCHECK(signaling_thread()->IsCurrent());
3481
3482 // Validate SDP.
3483 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3484 return false;
3485 }
3486
3487 // Hold this pointer so candidates can be copied to it later in the method.
3488 SessionDescriptionInterface* desc_ptr = desc.get();
3489
3490 const SessionDescriptionInterface* old_remote_description =
3491 remote_description();
3492 // Grab ownership of the description being replaced for the remainder of this
3493 // method, since it's used below as |old_remote_description|.
3494 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3495 Action action = GetAction(desc->type());
3496 if (action == kAnswer) {
3497 replaced_remote_description = pending_remote_description_
3498 ? std::move(pending_remote_description_)
3499 : std::move(current_remote_description_);
3500 current_remote_description_ = std::move(desc);
3501 pending_remote_description_ = nullptr;
3502 current_local_description_ = std::move(pending_local_description_);
3503 } else {
3504 replaced_remote_description = std::move(pending_remote_description_);
3505 pending_remote_description_ = std::move(desc);
3506 }
3507
3508 // Transport and Media channels will be created only when offer is set.
3509 if (action == kOffer &&
3510 !CreateChannels(remote_description()->description())) {
3511 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3512 // is applied. Restore back to old description.
3513 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3514 err_desc);
3515 }
3516
3517 // Remove unused channels if MediaContentDescription is rejected.
3518 RemoveUnusedChannels(remote_description()->description());
3519
3520 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3521 // is called.
3522 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3523 return false;
3524 }
3525
3526 if (local_description() &&
3527 !UseCandidatesInSessionDescription(remote_description())) {
3528 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3529 err_desc);
3530 }
3531
3532 if (old_remote_description) {
3533 for (const cricket::ContentInfo& content :
3534 old_remote_description->description()->contents()) {
3535 // Check if this new SessionDescription contains new ICE ufrag and
3536 // password that indicates the remote peer requests an ICE restart.
3537 // TODO(deadbeef): When we start storing both the current and pending
3538 // remote description, this should reset pending_ice_restarts and compare
3539 // against the current description.
3540 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3541 content.name)) {
3542 if (action == kOffer) {
3543 pending_ice_restarts_.insert(content.name);
3544 }
3545 } else {
3546 // We retain all received candidates only if ICE is not restarted.
3547 // When ICE is restarted, all previous candidates belong to an old
3548 // generation and should not be kept.
3549 // TODO(deadbeef): This goes against the W3C spec which says the remote
3550 // description should only contain candidates from the last set remote
3551 // description plus any candidates added since then. We should remove
3552 // this once we're sure it won't break anything.
3553 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3554 old_remote_description, content.name, desc_ptr);
3555 }
3556 }
3557 }
3558
3559 if (error() != ERROR_NONE) {
3560 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3561 err_desc);
3562 }
3563
3564 // Set the the ICE connection state to connecting since the connection may
3565 // become writable with peer reflexive candidates before any remote candidate
3566 // is signaled.
3567 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3568 // is to have a new signal the indicates a change in checking state from the
3569 // transport and expose a new checking() member from transport that can be
3570 // read to determine the current checking state. The existing SignalConnecting
3571 // actually means "gathering candidates", so cannot be be used here.
3572 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3573 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3574 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3575 }
3576 return true;
3577}
3578
3579// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3580// vector of BaseChannel pointers instead of separate voice and video channel
3581// vectors. At that point, this will become a simple getter.
3582std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3583 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003584 if (voice_channel()) {
3585 channels.push_back(voice_channel());
3586 }
3587 if (video_channel()) {
3588 channels.push_back(video_channel());
3589 }
Steve Anton75737c02017-11-06 10:37:17 -08003590 if (rtp_data_channel_) {
3591 channels.push_back(rtp_data_channel_);
3592 }
3593 return channels;
3594}
3595
3596void PeerConnection::SetError(Error error, const std::string& error_desc) {
3597 RTC_DCHECK(signaling_thread()->IsCurrent());
3598 if (error != error_) {
3599 error_ = error;
3600 error_desc_ = error_desc;
3601 }
3602}
3603
3604bool PeerConnection::UpdateSessionState(Action action,
3605 cricket::ContentSource source,
3606 std::string* err_desc) {
3607 RTC_DCHECK(signaling_thread()->IsCurrent());
3608
3609 // If there's already a pending error then no state transition should happen.
3610 // But all call-sites should be verifying this before calling us!
3611 RTC_DCHECK(error() == ERROR_NONE);
3612 std::string td_err;
3613 if (action == kOffer) {
3614 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3615 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3616 }
3617 ChangeSignalingState(source == cricket::CS_LOCAL
3618 ? PeerConnectionInterface::kHaveLocalOffer
3619 : PeerConnectionInterface::kHaveRemoteOffer);
3620 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3621 SetError(ERROR_CONTENT, *err_desc);
3622 }
3623 if (error() != ERROR_NONE) {
3624 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3625 }
3626 } else if (action == kPrAnswer) {
3627 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3628 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3629 }
3630 EnableChannels();
3631 ChangeSignalingState(source == cricket::CS_LOCAL
3632 ? PeerConnectionInterface::kHaveLocalPrAnswer
3633 : PeerConnectionInterface::kHaveRemotePrAnswer);
3634 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3635 SetError(ERROR_CONTENT, *err_desc);
3636 }
3637 if (error() != ERROR_NONE) {
3638 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3639 }
3640 } else if (action == kAnswer) {
3641 const cricket::ContentGroup* local_bundle =
3642 local_description()->description()->GetGroupByName(
3643 cricket::GROUP_TYPE_BUNDLE);
3644 const cricket::ContentGroup* remote_bundle =
3645 remote_description()->description()->GetGroupByName(
3646 cricket::GROUP_TYPE_BUNDLE);
3647 if (local_bundle && remote_bundle) {
3648 // The answerer decides the transport to bundle on.
3649 const cricket::ContentGroup* answer_bundle =
3650 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3651 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003652 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003653 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3654 }
3655 }
3656 // Only push down the transport description after enabling BUNDLE; we don't
3657 // want to push down a description on a transport about to be destroyed.
3658 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3659 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3660 }
3661 EnableChannels();
3662 ChangeSignalingState(PeerConnectionInterface::kStable);
3663 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3664 SetError(ERROR_CONTENT, *err_desc);
3665 }
3666 if (error() != ERROR_NONE) {
3667 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3668 }
3669 }
3670 return true;
3671}
3672
3673PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3674 if (type == SessionDescriptionInterface::kOffer) {
3675 return PeerConnection::kOffer;
3676 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3677 return PeerConnection::kPrAnswer;
3678 } else if (type == SessionDescriptionInterface::kAnswer) {
3679 return PeerConnection::kAnswer;
3680 }
3681 RTC_NOTREACHED() << "unknown action type";
3682 return PeerConnection::kOffer;
3683}
3684
3685bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3686 cricket::ContentSource source,
3687 std::string* err) {
3688 const SessionDescription* sdesc =
3689 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3690 ->description();
3691 RTC_DCHECK(sdesc);
3692 bool all_success = true;
3693 for (auto* channel : Channels()) {
3694 // TODO(steveanton): Add support for multiple channels of the same type.
3695 const ContentInfo* content_info =
3696 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3697 if (!content_info) {
3698 continue;
3699 }
3700 const MediaContentDescription* content_desc =
3701 static_cast<const MediaContentDescription*>(content_info->description);
3702 if (content_desc && !content_info->rejected) {
3703 bool success = (source == cricket::CS_LOCAL)
3704 ? channel->SetLocalContent(content_desc, action, err)
3705 : channel->SetRemoteContent(content_desc, action, err);
3706 if (!success) {
3707 all_success = false;
3708 break;
3709 }
3710 }
3711 }
3712 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3713 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3714 if (sctp_transport_ && local_description() && remote_description() &&
3715 cricket::GetFirstDataContent(local_description()->description()) &&
3716 cricket::GetFirstDataContent(remote_description()->description())) {
3717 all_success &= network_thread()->Invoke<bool>(
3718 RTC_FROM_HERE,
3719 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3720 }
3721 return all_success;
3722}
3723
3724bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3725 RTC_DCHECK(network_thread()->IsCurrent());
3726 RTC_DCHECK(local_description());
3727 RTC_DCHECK(remote_description());
3728 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3729 // When we support "max-message-size", that would also be pushed down here.
3730 return sctp_transport_->Start(
3731 GetSctpPort(local_description()->description()),
3732 GetSctpPort(remote_description()->description()));
3733}
3734
3735bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3736 cricket::ContentAction action,
3737 std::string* error_desc) {
3738 RTC_DCHECK(signaling_thread()->IsCurrent());
3739
3740 if (source == cricket::CS_LOCAL) {
3741 return PushdownLocalTransportDescription(local_description()->description(),
3742 action, error_desc);
3743 }
3744 return PushdownRemoteTransportDescription(remote_description()->description(),
3745 action, error_desc);
3746}
3747
3748bool PeerConnection::PushdownLocalTransportDescription(
3749 const SessionDescription* sdesc,
3750 cricket::ContentAction action,
3751 std::string* err) {
3752 RTC_DCHECK(signaling_thread()->IsCurrent());
3753
3754 if (!sdesc) {
3755 return false;
3756 }
3757
3758 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3759 if (!transport_controller_->SetLocalTransportDescription(
3760 tinfo.content_name, tinfo.description, action, err)) {
3761 return false;
3762 }
3763 }
3764
3765 return true;
3766}
3767
3768bool PeerConnection::PushdownRemoteTransportDescription(
3769 const SessionDescription* sdesc,
3770 cricket::ContentAction action,
3771 std::string* err) {
3772 RTC_DCHECK(signaling_thread()->IsCurrent());
3773
3774 if (!sdesc) {
3775 return false;
3776 }
3777
3778 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3779 if (!transport_controller_->SetRemoteTransportDescription(
3780 tinfo.content_name, tinfo.description, action, err)) {
3781 return false;
3782 }
3783 }
3784
3785 return true;
3786}
3787
3788bool PeerConnection::GetTransportDescription(
3789 const SessionDescription* description,
3790 const std::string& content_name,
3791 cricket::TransportDescription* tdesc) {
3792 if (!description || !tdesc) {
3793 return false;
3794 }
3795 const TransportInfo* transport_info =
3796 description->GetTransportInfoByName(content_name);
3797 if (!transport_info) {
3798 return false;
3799 }
3800 *tdesc = transport_info->description;
3801 return true;
3802}
3803
3804bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3805 const std::string* first_content_name = bundle.FirstContentName();
3806 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003807 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003808 return false;
3809 }
3810 const std::string& transport_name = *first_content_name;
3811
3812 auto maybe_set_transport = [this, bundle,
3813 transport_name](cricket::BaseChannel* ch) {
3814 if (!ch || !bundle.HasContentName(ch->content_name())) {
3815 return true;
3816 }
3817
3818 std::string old_transport_name = ch->transport_name();
3819 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003820 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3821 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003822 return true;
3823 }
3824
3825 cricket::DtlsTransportInternal* rtp_dtls_transport =
3826 transport_controller_->CreateDtlsTransport(
3827 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3828 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3829 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3830 if (need_rtcp) {
3831 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3832 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3833 }
3834
3835 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003836 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3837 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003838 transport_controller_->DestroyDtlsTransport(
3839 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3840 // If the channel needs rtcp, it means that the channel used to have a
3841 // rtcp transport which needs to be deleted now.
3842 if (need_rtcp) {
3843 transport_controller_->DestroyDtlsTransport(
3844 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3845 }
3846 return true;
3847 };
3848
3849 if (!maybe_set_transport(voice_channel()) ||
3850 !maybe_set_transport(video_channel()) ||
3851 !maybe_set_transport(rtp_data_channel())) {
3852 return false;
3853 }
3854 // For SCTP, transport creation/deletion happens here instead of in the
3855 // object itself.
3856 if (sctp_transport_) {
3857 RTC_DCHECK(sctp_transport_name_);
3858 RTC_DCHECK(sctp_content_name_);
3859 if (transport_name != *sctp_transport_name_ &&
3860 bundle.HasContentName(*sctp_content_name_)) {
3861 network_thread()->Invoke<void>(
3862 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3863 transport_name));
3864 }
3865 }
3866
3867 return true;
3868}
3869
Steve Anton75737c02017-11-06 10:37:17 -08003870cricket::IceConfig PeerConnection::ParseIceConfig(
3871 const PeerConnectionInterface::RTCConfiguration& config) const {
3872 cricket::ContinualGatheringPolicy gathering_policy;
3873 // TODO(honghaiz): Add the third continual gathering policy in
3874 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3875 switch (config.continual_gathering_policy) {
3876 case PeerConnectionInterface::GATHER_ONCE:
3877 gathering_policy = cricket::GATHER_ONCE;
3878 break;
3879 case PeerConnectionInterface::GATHER_CONTINUALLY:
3880 gathering_policy = cricket::GATHER_CONTINUALLY;
3881 break;
3882 default:
3883 RTC_NOTREACHED();
3884 gathering_policy = cricket::GATHER_ONCE;
3885 }
3886 cricket::IceConfig ice_config;
3887 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3888 ice_config.prioritize_most_likely_candidate_pairs =
3889 config.prioritize_most_likely_ice_candidate_pairs;
3890 ice_config.backup_connection_ping_interval =
3891 config.ice_backup_candidate_pair_ping_interval;
3892 ice_config.continual_gathering_policy = gathering_policy;
3893 ice_config.presume_writable_when_fully_relayed =
3894 config.presume_writable_when_fully_relayed;
3895 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3896 ice_config.regather_all_networks_interval_range =
3897 config.ice_regather_interval_range;
3898 return ice_config;
3899}
3900
Steve Anton75737c02017-11-06 10:37:17 -08003901bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3902 std::string* track_id) {
3903 if (!local_description()) {
3904 return false;
3905 }
3906 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3907 track_id);
3908}
3909
3910bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3911 std::string* track_id) {
3912 if (!remote_description()) {
3913 return false;
3914 }
3915 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3916 track_id);
3917}
3918
3919bool PeerConnection::SendData(const cricket::SendDataParams& params,
3920 const rtc::CopyOnWriteBuffer& payload,
3921 cricket::SendDataResult* result) {
3922 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003923 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3924 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003925 return false;
3926 }
3927 return rtp_data_channel_
3928 ? rtp_data_channel_->SendData(params, payload, result)
3929 : network_thread()->Invoke<bool>(
3930 RTC_FROM_HERE,
3931 Bind(&cricket::SctpTransportInternal::SendData,
3932 sctp_transport_.get(), params, payload, result));
3933}
3934
3935bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3936 if (!rtp_data_channel_ && !sctp_transport_) {
3937 // Don't log an error here, because DataChannels are expected to call
3938 // ConnectDataChannel in this state. It's the only way to initially tell
3939 // whether or not the underlying transport is ready.
3940 return false;
3941 }
3942 if (rtp_data_channel_) {
3943 rtp_data_channel_->SignalReadyToSendData.connect(
3944 webrtc_data_channel, &DataChannel::OnChannelReady);
3945 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3946 &DataChannel::OnDataReceived);
3947 } else {
3948 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3949 &DataChannel::OnChannelReady);
3950 SignalSctpDataReceived.connect(webrtc_data_channel,
3951 &DataChannel::OnDataReceived);
3952 SignalSctpStreamClosedRemotely.connect(
3953 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3954 }
3955 return true;
3956}
3957
3958void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3959 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003960 RTC_LOG(LS_ERROR)
3961 << "DisconnectDataChannel called when rtp_data_channel_ and "
3962 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003963 return;
3964 }
3965 if (rtp_data_channel_) {
3966 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3967 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3968 } else {
3969 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3970 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3971 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3972 }
3973}
3974
3975void PeerConnection::AddSctpDataStream(int sid) {
3976 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003977 RTC_LOG(LS_ERROR)
3978 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003979 return;
3980 }
3981 network_thread()->Invoke<void>(
3982 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3983 sctp_transport_.get(), sid));
3984}
3985
3986void PeerConnection::RemoveSctpDataStream(int sid) {
3987 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003988 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3989 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003990 return;
3991 }
3992 network_thread()->Invoke<void>(
3993 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3994 sctp_transport_.get(), sid));
3995}
3996
3997bool PeerConnection::ReadyToSendData() const {
3998 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3999 sctp_ready_to_send_data_;
4000}
4001
4002std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4003 RTC_DCHECK(signaling_thread()->IsCurrent());
4004 ChannelNamePairs channel_name_pairs;
4005 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004006 channel_name_pairs.voice = ChannelNamePair(
4007 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004008 }
4009 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004010 channel_name_pairs.video = ChannelNamePair(
4011 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004012 }
4013 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004014 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004015 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004016 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004017 }
4018 if (sctp_transport_) {
4019 RTC_DCHECK(sctp_content_name_);
4020 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004021 channel_name_pairs.data =
4022 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004023 }
4024 return GetSessionStats(channel_name_pairs);
4025}
4026
4027std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4028 const ChannelNamePairs& channel_name_pairs) {
4029 if (network_thread()->IsCurrent()) {
4030 return GetSessionStats_n(channel_name_pairs);
4031 }
4032 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4033 RTC_FROM_HERE,
4034 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4035}
4036
4037bool PeerConnection::GetLocalCertificate(
4038 const std::string& transport_name,
4039 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4040 return transport_controller_->GetLocalCertificate(transport_name,
4041 certificate);
4042}
4043
4044std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4045 const std::string& transport_name) {
4046 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4047}
4048
4049cricket::DataChannelType PeerConnection::data_channel_type() const {
4050 return data_channel_type_;
4051}
4052
4053bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4054 return pending_ice_restarts_.find(content_name) !=
4055 pending_ice_restarts_.end();
4056}
4057
Steve Anton75737c02017-11-06 10:37:17 -08004058bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4059 return transport_controller_->NeedsIceRestart(content_name);
4060}
4061
4062void PeerConnection::OnCertificateReady(
4063 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4064 transport_controller_->SetLocalCertificate(certificate);
4065}
4066
4067void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
4068 SetError(ERROR_TRANSPORT,
4069 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
4070}
4071
4072void PeerConnection::OnTransportControllerConnectionState(
4073 cricket::IceConnectionState state) {
4074 switch (state) {
4075 case cricket::kIceConnectionConnecting:
4076 // If the current state is Connected or Completed, then there were
4077 // writable channels but now there are not, so the next state must
4078 // be Disconnected.
4079 // kIceConnectionConnecting is currently used as the default,
4080 // un-connected state by the TransportController, so its only use is
4081 // detecting disconnections.
4082 if (ice_connection_state_ ==
4083 PeerConnectionInterface::kIceConnectionConnected ||
4084 ice_connection_state_ ==
4085 PeerConnectionInterface::kIceConnectionCompleted) {
4086 SetIceConnectionState(
4087 PeerConnectionInterface::kIceConnectionDisconnected);
4088 }
4089 break;
4090 case cricket::kIceConnectionFailed:
4091 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4092 break;
4093 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004094 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4095 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004096 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4097 break;
4098 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004099 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4100 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004101 if (ice_connection_state_ !=
4102 PeerConnectionInterface::kIceConnectionConnected) {
4103 // If jumping directly from "checking" to "connected",
4104 // signal "connected" first.
4105 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4106 }
4107 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4108 if (metrics_observer()) {
4109 ReportTransportStats();
4110 }
4111 break;
4112 default:
4113 RTC_NOTREACHED();
4114 }
4115}
4116
4117void PeerConnection::OnTransportControllerCandidatesGathered(
4118 const std::string& transport_name,
4119 const cricket::Candidates& candidates) {
4120 RTC_DCHECK(signaling_thread()->IsCurrent());
4121 int sdp_mline_index;
4122 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004123 RTC_LOG(LS_ERROR)
4124 << "OnTransportControllerCandidatesGathered: content name "
4125 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004126 return;
4127 }
4128
4129 for (cricket::Candidates::const_iterator citer = candidates.begin();
4130 citer != candidates.end(); ++citer) {
4131 // Use transport_name as the candidate media id.
4132 std::unique_ptr<JsepIceCandidate> candidate(
4133 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4134 if (local_description()) {
4135 mutable_local_description()->AddCandidate(candidate.get());
4136 }
4137 OnIceCandidate(std::move(candidate));
4138 }
4139}
4140
4141void PeerConnection::OnTransportControllerCandidatesRemoved(
4142 const std::vector<cricket::Candidate>& candidates) {
4143 RTC_DCHECK(signaling_thread()->IsCurrent());
4144 // Sanity check.
4145 for (const cricket::Candidate& candidate : candidates) {
4146 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004147 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4148 << "empty content name in candidate "
4149 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004150 return;
4151 }
4152 }
4153
4154 if (local_description()) {
4155 mutable_local_description()->RemoveCandidates(candidates);
4156 }
4157 OnIceCandidatesRemoved(candidates);
4158}
4159
4160void PeerConnection::OnTransportControllerDtlsHandshakeError(
4161 rtc::SSLHandshakeError error) {
4162 if (metrics_observer()) {
4163 metrics_observer()->IncrementEnumCounter(
4164 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4165 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4166 }
4167}
4168
4169// Enabling voice and video (and RTP data) channels.
4170void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004171 if (voice_channel() && !voice_channel()->enabled()) {
4172 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004173 }
4174
Steve Anton4171afb2017-11-20 10:20:22 -08004175 if (video_channel() && !video_channel()->enabled()) {
4176 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004177 }
4178
Steve Anton4171afb2017-11-20 10:20:22 -08004179 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004180 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004181 }
Steve Anton75737c02017-11-06 10:37:17 -08004182}
4183
4184// Returns the media index for a local ice candidate given the content name.
4185bool PeerConnection::GetLocalCandidateMediaIndex(
4186 const std::string& content_name,
4187 int* sdp_mline_index) {
4188 if (!local_description() || !sdp_mline_index) {
4189 return false;
4190 }
4191
4192 bool content_found = false;
4193 const ContentInfos& contents = local_description()->description()->contents();
4194 for (size_t index = 0; index < contents.size(); ++index) {
4195 if (contents[index].name == content_name) {
4196 *sdp_mline_index = static_cast<int>(index);
4197 content_found = true;
4198 break;
4199 }
4200 }
4201 return content_found;
4202}
4203
4204bool PeerConnection::UseCandidatesInSessionDescription(
4205 const SessionDescriptionInterface* remote_desc) {
4206 if (!remote_desc) {
4207 return true;
4208 }
4209 bool ret = true;
4210
4211 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4212 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4213 for (size_t n = 0; n < candidates->count(); ++n) {
4214 const IceCandidateInterface* candidate = candidates->at(n);
4215 bool valid = false;
4216 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4217 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004218 RTC_LOG(LS_INFO)
4219 << "UseCandidatesInSessionDescription: Not ready to use "
4220 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004221 }
4222 continue;
4223 }
4224 ret = UseCandidate(candidate);
4225 if (!ret) {
4226 break;
4227 }
4228 }
4229 }
4230 return ret;
4231}
4232
4233bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4234 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4235 size_t remote_content_size =
4236 remote_description()->description()->contents().size();
4237 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004238 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004239 return false;
4240 }
4241
4242 cricket::ContentInfo content =
4243 remote_description()->description()->contents()[mediacontent_index];
4244 std::vector<cricket::Candidate> candidates;
4245 candidates.push_back(candidate->candidate());
4246 // Invoking BaseSession method to handle remote candidates.
4247 std::string error;
4248 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4249 &error)) {
4250 // Candidates successfully submitted for checking.
4251 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4252 ice_connection_state_ ==
4253 PeerConnectionInterface::kIceConnectionDisconnected) {
4254 // If state is New, then the session has just gotten its first remote ICE
4255 // candidates, so go to Checking.
4256 // If state is Disconnected, the session is re-using old candidates or
4257 // receiving additional ones, so go to Checking.
4258 // If state is Connected, stay Connected.
4259 // TODO(bemasc): If state is Connected, and the new candidates are for a
4260 // newly added transport, then the state actually _should_ move to
4261 // checking. Add a way to distinguish that case.
4262 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4263 }
4264 // TODO(bemasc): If state is Completed, go back to Connected.
4265 } else {
4266 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004267 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004268 }
4269 }
4270 return true;
4271}
4272
4273void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4274 // TODO(steveanton): Add support for multiple audio/video channels.
4275 // Destroy video channel first since it may have a pointer to the
4276 // voice channel.
4277 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4278 if ((!video_info || video_info->rejected) && video_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004279 DestroyVideoChannel(video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004280 }
4281
4282 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4283 if ((!voice_info || voice_info->rejected) && voice_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004284 DestroyVoiceChannel(voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004285 }
4286
4287 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4288 if (!data_info || data_info->rejected) {
4289 if (rtp_data_channel_) {
4290 DestroyDataChannel();
4291 }
4292 if (sctp_transport_) {
4293 OnDataChannelDestroyed();
4294 network_thread()->Invoke<void>(
4295 RTC_FROM_HERE,
4296 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4297 }
4298 }
4299}
4300
4301// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4302// if the channel is not part of any bundle.
4303const std::string* PeerConnection::GetBundleTransportName(
4304 const cricket::ContentInfo* content,
4305 const cricket::ContentGroup* bundle) {
4306 if (!bundle) {
4307 return nullptr;
4308 }
4309 const std::string* first_content_name = bundle->FirstContentName();
4310 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004312 return nullptr;
4313 }
4314 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004316 return nullptr;
4317 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004318 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4319 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004320 return first_content_name;
4321}
4322
4323bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4324 // TODO(steveanton): Add support for multiple audio/video channels.
4325 const cricket::ContentGroup* bundle_group = nullptr;
4326 if (configuration_.bundle_policy ==
4327 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4328 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4329 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004331 return false;
4332 }
4333 }
4334 // Creating the media channels and transport proxies.
4335 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4336 if (voice && !voice->rejected && !voice_channel()) {
4337 if (!CreateVoiceChannel(voice,
4338 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004339 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004340 return false;
4341 }
4342 }
4343
4344 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4345 if (video && !video->rejected && !video_channel()) {
4346 if (!CreateVideoChannel(video,
4347 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004348 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004349 return false;
4350 }
4351 }
4352
4353 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4354 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4355 !rtp_data_channel_ && !sctp_transport_) {
4356 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004357 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004358 return false;
4359 }
4360 }
4361
4362 return true;
4363}
4364
Steve Anton4171afb2017-11-20 10:20:22 -08004365// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004366bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4367 const std::string* bundle_transport) {
4368 // TODO(steveanton): Check to see if it's safe to create multiple voice
4369 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004370 RTC_DCHECK(!voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004371
4372 std::string transport_name =
4373 bundle_transport ? *bundle_transport : content->name;
4374
4375 cricket::DtlsTransportInternal* rtp_dtls_transport =
4376 transport_controller_->CreateDtlsTransport(
4377 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4378 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4379 if (configuration_.rtcp_mux_policy !=
4380 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4381 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4382 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4383 }
4384
4385 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4386 call_.get(), configuration_.media_config, rtp_dtls_transport,
4387 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4388 content->name, SrtpRequired(), audio_options_);
4389 if (!voice_channel) {
4390 transport_controller_->DestroyDtlsTransport(
4391 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4392 if (rtcp_dtls_transport) {
4393 transport_controller_->DestroyDtlsTransport(
4394 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4395 }
4396 return false;
4397 }
Steve Anton75737c02017-11-06 10:37:17 -08004398 voice_channel->SignalRtcpMuxFullyActive.connect(
4399 this, &PeerConnection::DestroyRtcpTransport_n);
4400 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4401 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004402 voice_channel->SignalSentPacket.connect(this,
4403 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004404
4405 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4406
Steve Anton75737c02017-11-06 10:37:17 -08004407 return true;
4408}
4409
Steve Anton4171afb2017-11-20 10:20:22 -08004410// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004411bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4412 const std::string* bundle_transport) {
4413 // TODO(steveanton): Check to see if it's safe to create multiple video
4414 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004415 RTC_DCHECK(!video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004416
4417 std::string transport_name =
4418 bundle_transport ? *bundle_transport : content->name;
4419
4420 cricket::DtlsTransportInternal* rtp_dtls_transport =
4421 transport_controller_->CreateDtlsTransport(
4422 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4423 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4424 if (configuration_.rtcp_mux_policy !=
4425 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4426 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4428 }
4429
4430 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4431 call_.get(), configuration_.media_config, rtp_dtls_transport,
4432 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4433 content->name, SrtpRequired(), video_options_);
4434
4435 if (!video_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 }
Steve Anton75737c02017-11-06 10:37:17 -08004444 video_channel->SignalRtcpMuxFullyActive.connect(
4445 this, &PeerConnection::DestroyRtcpTransport_n);
4446 video_channel->SignalDtlsSrtpSetupFailure.connect(
4447 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004448 video_channel->SignalSentPacket.connect(this,
4449 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004450
4451 GetVideoTransceiver()->internal()->SetChannel(video_channel);
4452
Steve Anton75737c02017-11-06 10:37:17 -08004453 return true;
4454}
4455
4456bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4457 const std::string* bundle_transport) {
4458 const std::string transport_name =
4459 bundle_transport ? *bundle_transport : content->name;
4460 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4461 if (sctp) {
4462 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004463 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004464 << "Trying to create SCTP transport, but didn't compile with "
4465 "SCTP support (HAVE_SCTP)";
4466 return false;
4467 }
4468 if (!network_thread()->Invoke<bool>(
4469 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4470 this, content->name, transport_name))) {
4471 return false;
4472 }
4473 } else {
4474 std::string transport_name =
4475 bundle_transport ? *bundle_transport : content->name;
4476 cricket::DtlsTransportInternal* rtp_dtls_transport =
4477 transport_controller_->CreateDtlsTransport(
4478 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4479 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4480 if (configuration_.rtcp_mux_policy !=
4481 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4482 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4483 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4484 }
4485
4486 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4487 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4488 transport_controller_->signaling_thread(), content->name,
4489 SrtpRequired());
4490
4491 if (!rtp_data_channel_) {
4492 transport_controller_->DestroyDtlsTransport(
4493 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4494 if (rtcp_dtls_transport) {
4495 transport_controller_->DestroyDtlsTransport(
4496 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4497 }
4498 return false;
4499 }
4500
4501 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4502 this, &PeerConnection::DestroyRtcpTransport_n);
4503 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4504 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4505 rtp_data_channel_->SignalSentPacket.connect(
4506 this, &PeerConnection::OnSentPacket_w);
4507 }
4508
Steve Antond25da372017-11-06 14:50:29 -08004509 for (const auto& channel : sctp_data_channels_) {
4510 channel->OnTransportChannelCreated();
4511 }
Steve Anton75737c02017-11-06 10:37:17 -08004512
4513 return true;
4514}
4515
4516Call::Stats PeerConnection::GetCallStats() {
4517 if (!worker_thread()->IsCurrent()) {
4518 return worker_thread()->Invoke<Call::Stats>(
4519 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4520 }
4521 if (call_) {
4522 return call_->GetStats();
4523 } else {
4524 return Call::Stats();
4525 }
4526}
4527
4528std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4529 const ChannelNamePairs& channel_name_pairs) {
4530 RTC_DCHECK(network_thread()->IsCurrent());
4531 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4532 for (const auto channel_name_pair :
4533 {&channel_name_pairs.voice, &channel_name_pairs.video,
4534 &channel_name_pairs.data}) {
4535 if (*channel_name_pair) {
4536 cricket::TransportStats transport_stats;
4537 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4538 &transport_stats)) {
4539 return nullptr;
4540 }
4541 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4542 (*channel_name_pair)->transport_name;
4543 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4544 std::move(transport_stats);
4545 }
4546 }
4547 return session_stats;
4548}
4549
4550bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4551 const std::string& transport_name) {
4552 RTC_DCHECK(network_thread()->IsCurrent());
4553 RTC_DCHECK(sctp_factory_);
4554 cricket::DtlsTransportInternal* tc =
4555 transport_controller_->CreateDtlsTransport_n(
4556 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4557 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4558 RTC_DCHECK(sctp_transport_);
4559 sctp_invoker_.reset(new rtc::AsyncInvoker());
4560 sctp_transport_->SignalReadyToSendData.connect(
4561 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4562 sctp_transport_->SignalDataReceived.connect(
4563 this, &PeerConnection::OnSctpTransportDataReceived_n);
4564 sctp_transport_->SignalStreamClosedRemotely.connect(
4565 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004566 sctp_transport_name_ = transport_name;
4567 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004568 return true;
4569}
4570
4571void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4572 RTC_DCHECK(network_thread()->IsCurrent());
4573 RTC_DCHECK(sctp_transport_);
4574 RTC_DCHECK(sctp_transport_name_);
4575 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004576 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004577 cricket::DtlsTransportInternal* tc =
4578 transport_controller_->CreateDtlsTransport_n(
4579 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4580 sctp_transport_->SetTransportChannel(tc);
4581 transport_controller_->DestroyDtlsTransport_n(
4582 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4583}
4584
4585void PeerConnection::DestroySctpTransport_n() {
4586 RTC_DCHECK(network_thread()->IsCurrent());
4587 sctp_transport_.reset(nullptr);
4588 sctp_content_name_.reset();
4589 sctp_transport_name_.reset();
4590 sctp_invoker_.reset(nullptr);
4591 sctp_ready_to_send_data_ = false;
4592}
4593
4594void PeerConnection::OnSctpTransportReadyToSendData_n() {
4595 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4596 RTC_DCHECK(network_thread()->IsCurrent());
4597 // Note: Cannot use rtc::Bind here because it will grab a reference to
4598 // PeerConnection and potentially cause PeerConnection to live longer than
4599 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4600 // be destroyed before PeerConnection is destroyed, and at that point all
4601 // pending tasks will be cleared.
4602 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4603 OnSctpTransportReadyToSendData_s(true);
4604 });
4605}
4606
4607void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4608 RTC_DCHECK(signaling_thread()->IsCurrent());
4609 sctp_ready_to_send_data_ = ready;
4610 SignalSctpReadyToSendData(ready);
4611}
4612
4613void PeerConnection::OnSctpTransportDataReceived_n(
4614 const cricket::ReceiveDataParams& params,
4615 const rtc::CopyOnWriteBuffer& payload) {
4616 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4617 RTC_DCHECK(network_thread()->IsCurrent());
4618 // Note: Cannot use rtc::Bind here because it will grab a reference to
4619 // PeerConnection and potentially cause PeerConnection to live longer than
4620 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4621 // be destroyed before PeerConnection is destroyed, and at that point all
4622 // pending tasks will be cleared.
4623 sctp_invoker_->AsyncInvoke<void>(
4624 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4625 OnSctpTransportDataReceived_s(params, payload);
4626 });
4627}
4628
4629void PeerConnection::OnSctpTransportDataReceived_s(
4630 const cricket::ReceiveDataParams& params,
4631 const rtc::CopyOnWriteBuffer& payload) {
4632 RTC_DCHECK(signaling_thread()->IsCurrent());
4633 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4634 // Received OPEN message; parse and signal that a new data channel should
4635 // be created.
4636 std::string label;
4637 InternalDataChannelInit config;
4638 config.id = params.ssrc;
4639 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004640 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4641 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004642 return;
4643 }
4644 config.open_handshake_role = InternalDataChannelInit::kAcker;
4645 OnDataChannelOpenMessage(label, config);
4646 } else {
4647 // Otherwise just forward the signal.
4648 SignalSctpDataReceived(params, payload);
4649 }
4650}
4651
4652void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4653 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4654 RTC_DCHECK(network_thread()->IsCurrent());
4655 sctp_invoker_->AsyncInvoke<void>(
4656 RTC_FROM_HERE, signaling_thread(),
4657 rtc::Bind(&sigslot::signal1<int>::operator(),
4658 &SignalSctpStreamClosedRemotely, sid));
4659}
4660
4661// Returns false if bundle is enabled and rtcp_mux is disabled.
4662bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4663 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4664 if (!bundle_enabled)
4665 return true;
4666
4667 const cricket::ContentGroup* bundle_group =
4668 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4669 RTC_DCHECK(bundle_group != NULL);
4670
4671 const cricket::ContentInfos& contents = desc->contents();
4672 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4673 citer != contents.end(); ++citer) {
4674 const cricket::ContentInfo* content = (&*citer);
4675 RTC_DCHECK(content != NULL);
4676 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4677 content->type == cricket::NS_JINGLE_RTP) {
4678 if (!HasRtcpMuxEnabled(content))
4679 return false;
4680 }
4681 }
4682 // RTCP-MUX is enabled in all the contents.
4683 return true;
4684}
4685
4686bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4687 const cricket::MediaContentDescription* description =
4688 static_cast<cricket::MediaContentDescription*>(content->description);
4689 return description->rtcp_mux();
4690}
4691
4692bool PeerConnection::ValidateSessionDescription(
4693 const SessionDescriptionInterface* sdesc,
4694 cricket::ContentSource source,
4695 std::string* err_desc) {
4696 std::string type;
4697 if (error() != ERROR_NONE) {
4698 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4699 }
4700
4701 if (!sdesc || !sdesc->description()) {
4702 return BadSdp(source, type, kInvalidSdp, err_desc);
4703 }
4704
4705 type = sdesc->type();
4706 Action action = GetAction(sdesc->type());
4707 if (source == cricket::CS_LOCAL) {
4708 if (!ExpectSetLocalDescription(action))
4709 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4710 } else {
4711 if (!ExpectSetRemoteDescription(action))
4712 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4713 }
4714
4715 // Verify crypto settings.
4716 std::string crypto_error;
4717 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4718 dtls_enabled_) &&
4719 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4720 return BadSdp(source, type, crypto_error, err_desc);
4721 }
4722
4723 // Verify ice-ufrag and ice-pwd.
4724 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4725 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4726 }
4727
4728 if (!ValidateBundleSettings(sdesc->description())) {
4729 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4730 }
4731
4732 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4733 // m-lines that do not rtcp-mux enabled.
4734
4735 // Verify m-lines in Answer when compared against Offer.
4736 if (action == kAnswer || action == kPrAnswer) {
4737 const cricket::SessionDescription* offer_desc =
4738 (source == cricket::CS_LOCAL) ? remote_description()->description()
4739 : local_description()->description();
4740 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4741 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4742 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4743 }
4744 } else {
4745 const cricket::SessionDescription* current_desc = nullptr;
4746 if (source == cricket::CS_LOCAL && local_description()) {
4747 current_desc = local_description()->description();
4748 } else if (source == cricket::CS_REMOTE && remote_description()) {
4749 current_desc = remote_description()->description();
4750 }
4751 // The re-offers should respect the order of m= sections in current
4752 // description. See RFC3264 Section 8 paragraph 4 for more details.
4753 if (current_desc &&
4754 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4755 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4756 }
4757 }
4758
4759 return true;
4760}
4761
4762bool PeerConnection::ExpectSetLocalDescription(Action action) {
4763 PeerConnectionInterface::SignalingState state = signaling_state();
4764 if (action == kOffer) {
4765 return (state == PeerConnectionInterface::kStable) ||
4766 (state == PeerConnectionInterface::kHaveLocalOffer);
4767 } else { // Answer or PrAnswer
4768 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4769 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4770 }
4771}
4772
4773bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4774 PeerConnectionInterface::SignalingState state = signaling_state();
4775 if (action == kOffer) {
4776 return (state == PeerConnectionInterface::kStable) ||
4777 (state == PeerConnectionInterface::kHaveRemoteOffer);
4778 } else { // Answer or PrAnswer.
4779 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4780 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4781 }
4782}
4783
4784std::string PeerConnection::GetSessionErrorMsg() {
4785 std::ostringstream desc;
4786 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4787 desc << kSessionErrorDesc << error_desc() << ".";
4788 return desc.str();
4789}
4790
4791// We need to check the local/remote description for the Transport instead of
4792// the session, because a new Transport added during renegotiation may have
4793// them unset while the session has them set from the previous negotiation.
4794// Not doing so may trigger the auto generation of transport description and
4795// mess up DTLS identity information, ICE credential, etc.
4796bool PeerConnection::ReadyToUseRemoteCandidate(
4797 const IceCandidateInterface* candidate,
4798 const SessionDescriptionInterface* remote_desc,
4799 bool* valid) {
4800 *valid = true;
4801
4802 const SessionDescriptionInterface* current_remote_desc =
4803 remote_desc ? remote_desc : remote_description();
4804
4805 if (!current_remote_desc) {
4806 return false;
4807 }
4808
4809 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4810 size_t remote_content_size =
4811 current_remote_desc->description()->contents().size();
4812 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004813 RTC_LOG(LS_ERROR)
4814 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4815 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004816
4817 *valid = false;
4818 return false;
4819 }
4820
4821 cricket::ContentInfo content =
4822 current_remote_desc->description()->contents()[mediacontent_index];
4823
4824 const std::string transport_name = GetTransportName(content.name);
4825 if (transport_name.empty()) {
4826 return false;
4827 }
4828 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4829}
4830
4831bool PeerConnection::SrtpRequired() const {
4832 return dtls_enabled_ ||
4833 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4834}
4835
4836void PeerConnection::OnTransportControllerGatheringState(
4837 cricket::IceGatheringState state) {
4838 RTC_DCHECK(signaling_thread()->IsCurrent());
4839 if (state == cricket::kIceGatheringGathering) {
4840 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4841 } else if (state == cricket::kIceGatheringComplete) {
4842 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4843 }
4844}
4845
4846void PeerConnection::ReportTransportStats() {
4847 // Use a set so we don't report the same stats twice if two channels share
4848 // a transport.
4849 std::set<std::string> transport_names;
4850 if (voice_channel()) {
4851 transport_names.insert(voice_channel()->transport_name());
4852 }
4853 if (video_channel()) {
4854 transport_names.insert(video_channel()->transport_name());
4855 }
4856 if (rtp_data_channel()) {
4857 transport_names.insert(rtp_data_channel()->transport_name());
4858 }
4859 if (sctp_transport_name_) {
4860 transport_names.insert(*sctp_transport_name_);
4861 }
4862 for (const auto& name : transport_names) {
4863 cricket::TransportStats stats;
4864 if (transport_controller_->GetStats(name, &stats)) {
4865 ReportBestConnectionState(stats);
4866 ReportNegotiatedCiphers(stats);
4867 }
4868 }
4869}
4870// Walk through the ConnectionInfos to gather best connection usage
4871// for IPv4 and IPv6.
4872void PeerConnection::ReportBestConnectionState(
4873 const cricket::TransportStats& stats) {
4874 RTC_DCHECK(metrics_observer());
4875 for (cricket::TransportChannelStatsList::const_iterator it =
4876 stats.channel_stats.begin();
4877 it != stats.channel_stats.end(); ++it) {
4878 for (cricket::ConnectionInfos::const_iterator it_info =
4879 it->connection_infos.begin();
4880 it_info != it->connection_infos.end(); ++it_info) {
4881 if (!it_info->best_connection) {
4882 continue;
4883 }
4884
4885 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4886 const cricket::Candidate& local = it_info->local_candidate;
4887 const cricket::Candidate& remote = it_info->remote_candidate;
4888
4889 // Increment the counter for IceCandidatePairType.
4890 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4891 (local.type() == RELAY_PORT_TYPE &&
4892 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4893 type = kEnumCounterIceCandidatePairTypeTcp;
4894 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4895 type = kEnumCounterIceCandidatePairTypeUdp;
4896 } else {
4897 RTC_CHECK(0);
4898 }
4899 metrics_observer()->IncrementEnumCounter(
4900 type, GetIceCandidatePairCounter(local, remote),
4901 kIceCandidatePairMax);
4902
4903 // Increment the counter for IP type.
4904 if (local.address().family() == AF_INET) {
4905 metrics_observer()->IncrementEnumCounter(
4906 kEnumCounterAddressFamily, kBestConnections_IPv4,
4907 kPeerConnectionAddressFamilyCounter_Max);
4908
4909 } else if (local.address().family() == AF_INET6) {
4910 metrics_observer()->IncrementEnumCounter(
4911 kEnumCounterAddressFamily, kBestConnections_IPv6,
4912 kPeerConnectionAddressFamilyCounter_Max);
4913 } else {
4914 RTC_CHECK(0);
4915 }
4916
4917 return;
4918 }
4919 }
4920}
4921
4922void PeerConnection::ReportNegotiatedCiphers(
4923 const cricket::TransportStats& stats) {
4924 RTC_DCHECK(metrics_observer());
4925 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4926 return;
4927 }
4928
4929 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4930 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4931 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4932 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4933 return;
4934 }
4935
4936 PeerConnectionEnumCounterType srtp_counter_type;
4937 PeerConnectionEnumCounterType ssl_counter_type;
4938 if (stats.transport_name == cricket::CN_AUDIO) {
4939 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4940 ssl_counter_type = kEnumCounterAudioSslCipher;
4941 } else if (stats.transport_name == cricket::CN_VIDEO) {
4942 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4943 ssl_counter_type = kEnumCounterVideoSslCipher;
4944 } else if (stats.transport_name == cricket::CN_DATA) {
4945 srtp_counter_type = kEnumCounterDataSrtpCipher;
4946 ssl_counter_type = kEnumCounterDataSslCipher;
4947 } else {
4948 RTC_NOTREACHED();
4949 return;
4950 }
4951
4952 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4953 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4954 srtp_crypto_suite);
4955 }
4956 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4957 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4958 ssl_cipher_suite);
4959 }
4960}
4961
4962void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4963 RTC_DCHECK(worker_thread()->IsCurrent());
4964 RTC_DCHECK(call_);
4965 call_->OnSentPacket(sent_packet);
4966}
4967
4968const std::string PeerConnection::GetTransportName(
4969 const std::string& content_name) {
4970 cricket::BaseChannel* channel = GetChannel(content_name);
4971 if (!channel) {
4972 if (sctp_transport_) {
4973 RTC_DCHECK(sctp_content_name_);
4974 RTC_DCHECK(sctp_transport_name_);
4975 if (content_name == *sctp_content_name_) {
4976 return *sctp_transport_name_;
4977 }
4978 }
4979 // Return an empty string if failed to retrieve the transport name.
4980 return "";
4981 }
4982 return channel->transport_name();
4983}
4984
4985void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4986 RTC_DCHECK(network_thread()->IsCurrent());
4987 transport_controller_->DestroyDtlsTransport_n(
4988 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4989}
4990
Steve Anton4171afb2017-11-20 10:20:22 -08004991// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004992void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004993 RTC_DCHECK(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004994 RTC_DCHECK(video_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004995 RTC_DCHECK_EQ(GetVideoTransceiver()->internal()->channel(), video_channel);
4996 GetVideoTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004997 const std::string transport_name =
4998 video_channel->rtp_dtls_transport()->transport_name();
4999 const bool need_to_delete_rtcp =
5000 (video_channel->rtcp_dtls_transport() != nullptr);
5001 // The above need to be cached before destroying the video channel so that we
5002 // do not access uninitialized memory.
5003 channel_manager()->DestroyVideoChannel(video_channel);
5004 transport_controller_->DestroyDtlsTransport(
5005 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5006 if (need_to_delete_rtcp) {
5007 transport_controller_->DestroyDtlsTransport(
5008 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5009 }
5010}
5011
Steve Anton4171afb2017-11-20 10:20:22 -08005012// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08005013void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08005014 RTC_DCHECK(voice_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005015 RTC_DCHECK(voice_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08005016 RTC_DCHECK_EQ(GetAudioTransceiver()->internal()->channel(), voice_channel);
5017 GetAudioTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08005018 const std::string transport_name =
5019 voice_channel->rtp_dtls_transport()->transport_name();
5020 const bool need_to_delete_rtcp =
5021 (voice_channel->rtcp_dtls_transport() != nullptr);
5022 // The above need to be cached before destroying the video channel so that we
5023 // do not access uninitialized memory.
5024 channel_manager()->DestroyVoiceChannel(voice_channel);
5025 transport_controller_->DestroyDtlsTransport(
5026 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5027 if (need_to_delete_rtcp) {
5028 transport_controller_->DestroyDtlsTransport(
5029 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5030 }
5031}
5032
5033void PeerConnection::DestroyDataChannel() {
5034 OnDataChannelDestroyed();
5035 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
5036 std::string transport_name;
5037 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
5038 bool need_to_delete_rtcp =
5039 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
5040 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
5041 rtp_data_channel_ = nullptr;
5042 transport_controller_->DestroyDtlsTransport(
5043 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5044 if (need_to_delete_rtcp) {
5045 transport_controller_->DestroyDtlsTransport(
5046 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5047 }
5048}
5049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005050} // namespace webrtc