blob: 6281d57e3db7dc5716100d237dee617fc76b9026 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * 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:369 */
10
Mirko Bonadei92ea95e2017-09-15 04:47:3111#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Steve Antondcc3c022017-12-23 00:02:5414#include <queue>
Steve Anton75737c02017-11-06 18:37:1715#include <set>
kwiberg0eb15ed2015-12-17 11:04:1516#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3618
Mirko Bonadei92ea95e2017-09-15 04:47:3119#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Elad Alon83ccca12017-10-04 11:18:2625#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3126#include "logging/rtc_event_log/rtc_event_log.h"
27#include "media/sctp/sctptransport.h"
28#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1729#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3130#include "pc/channelmanager.h"
31#include "pc/dtmfsender.h"
32#include "pc/mediastream.h"
33#include "pc/mediastreamobserver.h"
34#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 22:30:0935#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3136#include "pc/rtpreceiver.h"
37#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1738#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4139#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3140#include "pc/streamcollection.h"
41#include "pc/videocapturertracksource.h"
42#include "pc/videotrack.h"
43#include "rtc_base/bind.h"
44#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 09:42:2646#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 11:18:2647#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3148#include "rtc_base/stringencode.h"
49#include "rtc_base/stringutils.h"
50#include "rtc_base/trace_event.h"
51#include "system_wrappers/include/clock.h"
52#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:3653
Steve Anton75737c02017-11-06 18:37:1754using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0058using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1759using cricket::TransportInfo;
60
61using cricket::LOCAL_PORT_TYPE;
62using cricket::STUN_PORT_TYPE;
63using cricket::RELAY_PORT_TYPE;
64using cricket::PRFLX_PORT_TYPE;
65
Steve Antonba818672017-11-06 18:21:5766namespace webrtc {
67
Steve Anton75737c02017-11-06 18:37:1768// Error messages
69const char kBundleWithoutRtcpMux[] =
70 "rtcp-mux must be enabled when BUNDLE "
71 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1772const char kInvalidCandidates[] = "Description contains invalid candidates.";
73const char kInvalidSdp[] = "Invalid session description.";
74const char kMlineMismatchInAnswer[] =
75 "The order of m-lines in answer doesn't match order in offer. Rejecting "
76 "answer.";
77const char kMlineMismatchInSubsequentOffer[] =
78 "The order of m-lines in subsequent offer doesn't match order from "
79 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1780const char kSdpWithoutDtlsFingerprint[] =
81 "Called with SDP without DTLS fingerprint.";
82const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
83const char kSdpWithoutIceUfragPwd[] =
84 "Called with SDP without ice-ufrag and ice-pwd.";
85const char kSessionError[] = "Session error code: ";
86const char kSessionErrorDesc[] = "Session error description: ";
87const char kDtlsSrtpSetupFailureRtp[] =
88 "Couldn't set up DTLS-SRTP on RTP channel.";
89const char kDtlsSrtpSetupFailureRtcp[] =
90 "Couldn't set up DTLS-SRTP on RTCP channel.";
91const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:3692
Steve Anton75737c02017-11-06 18:37:1793namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3694
deadbeefab9b2d12015-10-14 18:33:1195static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 18:20:2296static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:1198
zhihuang8f65cdf2016-05-07 01:40:3099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36102enum {
wu@webrtc.org91053e72013-08-10 07:18:04103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 18:33:11105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36106 MSG_GETSTATS,
deadbeefbd292462015-12-15 02:15:29107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 18:33:11120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36136};
137
deadbeefab9b2d12015-10-14 18:33:11138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
144 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 10:09:25145 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
146 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 19:49:08152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 18:33:11162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 21:10:50168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 13:50:32174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 22:45:38184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 21:10:50185 }
186 }
zhihuanga77e6bb2017-08-15 01:17:48187 }
zhihuang1c378ed2017-08-17 21:10:50188}
olka3c747662017-08-17 13:50:32189
zhihuang1c378ed2017-08-17 21:10:50190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 18:33:11198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 18:33:11207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 15:15:11211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 13:56:46223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 20:28:30228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 22:59:59236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 18:21:57243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 18:38:28262
Steve Anton75737c02017-11-06 18:37:17263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
320// Verify that the order of media sections in |new_desc| matches
321// |existing_desc|. The number of m= sections in |new_desc| should be no less
322// than |existing_desc|.
323bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
324 const SessionDescription* new_desc) {
325 if (!existing_desc || !new_desc) {
326 return false;
327 }
328
329 if (existing_desc->contents().size() > new_desc->contents().size()) {
330 return false;
331 }
332
333 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-23 00:02:54334 if (existing_desc->contents()[i].rejected) {
335 // If the media section can be recycled, it's valid for the MID and media
336 // type to change.
337 continue;
338 }
Steve Anton75737c02017-11-06 18:37:17339 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
340 return false;
341 }
342 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 23:14:30343 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 18:37:17344 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 23:14:30345 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 18:37:17346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 23:25:56367RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17368 const cricket::ContentGroup* bundle =
369 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56370 for (const cricket::ContentInfo& content_info : desc->contents()) {
371 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17372 continue;
373 }
Steve Anton8a006912017-12-04 23:25:56374 const std::string& mid = content_info.name;
375 if (bundle && bundle->HasContentName(mid) &&
376 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17377 // This isn't the first media section in the BUNDLE group, so it's not
378 // required to have crypto attributes, since only the crypto attributes
379 // from the first section actually get used.
380 continue;
381 }
382
383 // If the content isn't rejected or bundled into another m= section, crypto
384 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30385 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56386 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17387 if (!media || !tinfo) {
388 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17390 }
391 if (dtls_enabled) {
392 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25393 RTC_LOG(LS_WARNING)
394 << "Session description must have DTLS fingerprint if "
395 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56396 return RTCError(RTCErrorType::INVALID_PARAMETER,
397 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17398 }
399 } else {
400 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25401 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17402 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56403 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17404 }
405 }
406 }
Steve Anton8a006912017-12-04 23:25:56407 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17408}
409
410// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
411// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
412// media section/description in the BUNDLE group) needs a ufrag and pwd.
413bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
414 const cricket::ContentGroup* bundle =
415 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56416 for (const cricket::ContentInfo& content_info : desc->contents()) {
417 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17418 continue;
419 }
Steve Anton8a006912017-12-04 23:25:56420 const std::string& mid = content_info.name;
421 if (bundle && bundle->HasContentName(mid) &&
422 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17423 // This isn't the first media section in the BUNDLE group, so it's not
424 // required to have ufrag/password, since only the ufrag/password from
425 // the first section actually get used.
426 continue;
427 }
428
429 // If the content isn't rejected or bundled into another m= section,
430 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56431 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17432 if (!tinfo) {
433 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25434 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17435 return false;
436 }
437 if (tinfo->description.ice_ufrag.empty() ||
438 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25439 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17440 return false;
441 }
442 }
443 return true;
444}
445
446bool GetTrackIdBySsrc(const SessionDescription* session_description,
447 uint32_t ssrc,
448 std::string* track_id) {
449 RTC_DCHECK(track_id != NULL);
450
Steve Antonb1c1de12017-12-21 23:14:30451 const cricket::AudioContentDescription* audio_desc =
452 cricket::GetFirstAudioContentDescription(session_description);
453 if (audio_desc) {
454 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
Steve Antonb1c1de12017-12-21 23:14:30461 const cricket::VideoContentDescription* video_desc =
462 cricket::GetFirstVideoContentDescription(session_description);
463 if (video_desc) {
464 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470 return false;
471}
472
473// Get the SCTP port out of a SessionDescription.
474// Return -1 if not found.
475int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30476 const cricket::DataContentDescription* data_desc =
477 GetFirstDataContentDescription(session_description);
478 RTC_DCHECK(data_desc);
479 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17480 return -1;
481 }
Steve Anton75737c02017-11-06 18:37:17482 std::string value;
483 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
484 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30485 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17486 if (!codec.Matches(match_pattern)) {
487 continue;
488 }
489 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
490 return rtc::FromString<int>(value);
491 }
492 }
493 return -1;
494}
495
Steve Anton75737c02017-11-06 18:37:17496// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
497bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
498 const SessionDescriptionInterface* new_desc,
499 const std::string& content_name) {
500 if (!old_desc) {
501 return false;
502 }
503 const SessionDescription* new_sd = new_desc->description();
504 const SessionDescription* old_sd = old_desc->description();
505 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
506 if (!cinfo || cinfo->rejected) {
507 return false;
508 }
509 // If the content isn't rejected, check if ufrag and password has changed.
510 const cricket::TransportDescription* new_transport_desc =
511 new_sd->GetTransportDescriptionByName(content_name);
512 const cricket::TransportDescription* old_transport_desc =
513 old_sd->GetTransportDescriptionByName(content_name);
514 if (!new_transport_desc || !old_transport_desc) {
515 // No transport description exists. This is not an ICE restart.
516 return false;
517 }
518 if (cricket::IceCredentialsChanged(
519 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
520 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25521 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
522 << ".";
Steve Anton75737c02017-11-06 18:37:17523 return true;
524 }
525 return false;
526}
527
528} // namespace
529
Henrik Boström31638672017-11-23 16:48:32530// Upon completion, posts a task to execute the callback of the
531// SetSessionDescriptionObserver asynchronously on the same thread. At this
532// point, the state of the peer connection might no longer reflect the effects
533// of the SetRemoteDescription operation, as the peer connection could have been
534// modified during the post.
535// TODO(hbos): Remove this class once we remove the version of
536// PeerConnectionInterface::SetRemoteDescription() that takes a
537// SetSessionDescriptionObserver as an argument.
538class PeerConnection::SetRemoteDescriptionObserverAdapter
539 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
540 public:
541 SetRemoteDescriptionObserverAdapter(
542 rtc::scoped_refptr<PeerConnection> pc,
543 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
544 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
545
546 // SetRemoteDescriptionObserverInterface implementation.
547 void OnSetRemoteDescriptionComplete(RTCError error) override {
548 if (error.ok())
549 pc_->PostSetSessionDescriptionSuccess(wrapper_);
550 else
551 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
552 }
553
554 private:
555 rtc::scoped_refptr<PeerConnection> pc_;
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
557};
558
deadbeef293e9262017-01-11 20:28:30559bool PeerConnectionInterface::RTCConfiguration::operator==(
560 const PeerConnectionInterface::RTCConfiguration& o) const {
561 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10562 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30563 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56564 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10565 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30566 BundlePolicy bundle_policy;
567 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10568 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
569 int ice_candidate_pool_size;
570 bool disable_ipv6;
571 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11572 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 17:13:10573 bool enable_rtp_data_channel;
574 rtc::Optional<int> screencast_min_bitrate;
575 rtc::Optional<bool> combined_audio_video_bwe;
576 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30577 TcpCandidatePolicy tcp_candidate_policy;
578 CandidateNetworkPolicy candidate_network_policy;
579 int audio_jitter_buffer_max_packets;
580 bool audio_jitter_buffer_fast_accelerate;
581 int ice_connection_receiving_timeout;
582 int ice_backup_candidate_pair_ping_interval;
583 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30584 bool prioritize_most_likely_ice_candidate_pairs;
585 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30586 bool prune_turn_ports;
587 bool presume_writable_when_fully_relayed;
588 bool enable_ice_renomination;
589 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 19:50:14590 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 17:13:10591 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40592 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56593 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 20:28:30594 };
595 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
596 "Did you add something to RTCConfiguration and forget to "
597 "update operator==?");
598 return type == o.type && servers == o.servers &&
599 bundle_policy == o.bundle_policy &&
600 rtcp_mux_policy == o.rtcp_mux_policy &&
601 tcp_candidate_policy == o.tcp_candidate_policy &&
602 candidate_network_policy == o.candidate_network_policy &&
603 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
604 audio_jitter_buffer_fast_accelerate ==
605 o.audio_jitter_buffer_fast_accelerate &&
606 ice_connection_receiving_timeout ==
607 o.ice_connection_receiving_timeout &&
608 ice_backup_candidate_pair_ping_interval ==
609 o.ice_backup_candidate_pair_ping_interval &&
610 continual_gathering_policy == o.continual_gathering_policy &&
611 certificates == o.certificates &&
612 prioritize_most_likely_ice_candidate_pairs ==
613 o.prioritize_most_likely_ice_candidate_pairs &&
614 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51615 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11616 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 20:28:30617 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30618 screencast_min_bitrate == o.screencast_min_bitrate &&
619 combined_audio_video_bwe == o.combined_audio_video_bwe &&
620 enable_dtls_srtp == o.enable_dtls_srtp &&
621 ice_candidate_pool_size == o.ice_candidate_pool_size &&
622 prune_turn_ports == o.prune_turn_ports &&
623 presume_writable_when_fully_relayed ==
624 o.presume_writable_when_fully_relayed &&
625 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14626 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 17:13:10627 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40628 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56629 turn_customizer == o.turn_customizer &&
630 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 20:28:30631}
632
633bool PeerConnectionInterface::RTCConfiguration::operator!=(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26636}
637
zhihuang8f65cdf2016-05-07 01:40:30638// Generate a RTCP CNAME when a PeerConnection is created.
639std::string GenerateRtcpCname() {
640 std::string cname;
641 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25642 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27643 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30644 }
645 return cname;
646}
647
zhihuang1c378ed2017-08-17 21:10:50648bool ValidateOfferAnswerOptions(
649 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
650 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
651 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32652}
653
zhihuang1c378ed2017-08-17 21:10:50654// From |rtc_options|, fill parts of |session_options| shared by all generated
655// m= sections (in other words, nothing that involves a map/array).
656void ExtractSharedMediaSessionOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
658 cricket::MediaSessionOptions* session_options) {
659 session_options->vad_enabled = rtc_options.voice_activity_detection;
660 session_options->bundle_enabled = rtc_options.use_rtp_mux;
661}
zhihuanga77e6bb2017-08-15 01:17:48662
zhihuang1c378ed2017-08-17 21:10:50663bool ConvertConstraintsToOfferAnswerOptions(
664 const MediaConstraintsInterface* constraints,
665 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 13:50:32666 if (!constraints) {
667 return true;
668 }
zhihuang1c378ed2017-08-17 21:10:50669
670 bool value = false;
671 size_t mandatory_constraints_satisfied = 0;
672
673 if (FindConstraint(constraints,
674 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
675 &mandatory_constraints_satisfied)) {
676 offer_answer_options->offer_to_receive_audio =
677 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
678 kOfferToReceiveMediaTrue
679 : 0;
680 }
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_video =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kVoiceActivityDetection, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->voice_activity_detection = value;
694 }
695 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->use_rtp_mux = value;
698 }
699 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
700 &value, &mandatory_constraints_satisfied)) {
701 offer_answer_options->ice_restart = value;
702 }
703
deadbeefab9b2d12015-10-14 18:33:11704 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
705}
706
zhihuang38ede132017-06-15 19:52:32707PeerConnection::PeerConnection(PeerConnectionFactory* factory,
708 std::unique_ptr<RtcEventLog> event_log,
709 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36710 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32711 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30712 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11713 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32714 remote_streams_(StreamCollection::Create()),
715 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36716
717PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17718 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22719 RTC_DCHECK_RUN_ON(signaling_thread());
720
Steve Anton8af21862017-12-15 19:20:13721 // Need to stop transceivers before destroying the stats collector because
722 // AudioRtpSender has a reference to the StatsCollector it will update when
723 // stopping.
724 for (auto transceiver : transceivers_) {
725 transceiver->Stop();
726 }
Steve Anton4171afb2017-11-20 18:20:22727
Taylor Brandstettera1c30352016-05-13 15:15:11728 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57729 if (stats_collector_) {
730 stats_collector_->WaitForPendingRequest();
731 stats_collector_ = nullptr;
732 }
Steve Anton75737c02017-11-06 18:37:17733
Steve Anton8af21862017-12-15 19:20:13734 // Don't destroy BaseChannels until after stats has been cleaned up so that
735 // the last stats request can still read from the channels.
736 DestroyAllChannels();
737
Mirko Bonadei675513b2017-11-09 10:09:25738 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17739
740 webrtc_session_desc_factory_.reset();
741 sctp_invoker_.reset();
742 sctp_factory_.reset();
743 transport_controller_.reset();
744
deadbeef91dd5672016-05-18 23:55:30745 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27746 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02747 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15748 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02749 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15750 call_.reset();
751 event_log_.reset();
752 });
henrike@webrtc.org28e20752013-07-10 00:45:36753}
754
Steve Anton8af21862017-12-15 19:20:13755void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08756 // Destroy video channels first since they may have a pointer to a voice
757 // channel.
758 for (auto transceiver : transceivers_) {
759 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
760 DestroyTransceiverChannel(transceiver);
761 }
762 }
763 for (auto transceiver : transceivers_) {
764 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
765 DestroyTransceiverChannel(transceiver);
766 }
767 }
768 DestroyDataChannel();
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36771bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45772 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 13:47:29773 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 09:44:18774 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 20:55:10775 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:17776 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59777
778 RTCError config_error = ValidateConfiguration(configuration);
779 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25780 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59781 return false;
782 }
783
deadbeef293e9262017-01-11 20:28:30784 if (!allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25785 RTC_LOG(LS_ERROR)
786 << "PeerConnection initialized without a PortAllocator? "
787 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30788 return false;
789 }
Jonas Orelandbdcee282017-10-10 12:01:40790
deadbeef653b8e02015-11-11 20:55:10791 if (!observer) {
deadbeef293e9262017-01-11 20:28:30792 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25793 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
794 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10795 return false;
796 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09797 observer_ = observer;
kwiberg0eb15ed2015-12-17 11:04:15798 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 20:55:10799
deadbeef91dd5672016-05-18 23:55:30800 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11801 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27802 if (!network_thread()->Invoke<bool>(
803 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
804 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36805 return false;
806 }
henrike@webrtc.org28e20752013-07-10 00:45:36807
Steve Anton75737c02017-11-06 18:37:17808 // RFC 3264: The numeric value of the session id and version in the
809 // o line MUST be representable with a "64 bit signed integer".
810 // Due to this constraint session id |session_id_| is max limited to
811 // LLONG_MAX.
812 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
813 transport_controller_.reset(factory_->CreateTransportController(
814 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
815 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
816 transport_controller_->SignalConnectionState.connect(
817 this, &PeerConnection::OnTransportControllerConnectionState);
818 transport_controller_->SignalGatheringState.connect(
819 this, &PeerConnection::OnTransportControllerGatheringState);
820 transport_controller_->SignalCandidatesGathered.connect(
821 this, &PeerConnection::OnTransportControllerCandidatesGathered);
822 transport_controller_->SignalCandidatesRemoved.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
824 transport_controller_->SignalDtlsHandshakeError.connect(
825 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
826
827 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25828
deadbeefab9b2d12015-10-14 18:33:11829 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01830 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36831
Steve Antonba818672017-11-06 18:21:57832 configuration_ = configuration;
833
Steve Anton75737c02017-11-06 18:37:17834 const PeerConnectionFactoryInterface::Options& options = factory_->options();
835
836 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
837
838 // Obtain a certificate from RTCConfiguration if any were provided (optional).
839 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
840 if (!configuration.certificates.empty()) {
841 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
842 // just picking the first one. The decision should be made based on the DTLS
843 // handshake. The DTLS negotiations need to know about all certificates.
844 certificate = configuration.certificates[0];
845 }
846
Steve Antond25da372017-11-06 22:50:29847 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:17848
849 if (options.disable_encryption) {
850 dtls_enabled_ = false;
851 } else {
852 // Enable DTLS by default if we have an identity store or a certificate.
853 dtls_enabled_ = (cert_generator || certificate);
854 // |configuration| can override the default |dtls_enabled_| value.
855 if (configuration.enable_dtls_srtp) {
856 dtls_enabled_ = *(configuration.enable_dtls_srtp);
857 }
858 }
859
860 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
861 // It takes precendence over the disable_sctp_data_channels
862 // PeerConnectionFactoryInterface::Options.
863 if (configuration.enable_rtp_data_channel) {
864 data_channel_type_ = cricket::DCT_RTP;
865 } else {
866 // DTLS has to be enabled to use SCTP.
867 if (!options.disable_sctp_data_channels && dtls_enabled_) {
868 data_channel_type_ = cricket::DCT_SCTP;
869 }
870 }
871
872 video_options_.screencast_min_bitrate_kbps =
873 configuration.screencast_min_bitrate;
874 audio_options_.combined_audio_video_bwe =
875 configuration.combined_audio_video_bwe;
876
877 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:30878 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:17879
880 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:30881 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:17882
883 // Whether the certificate generator/certificate is null or not determines
884 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
885 // the right instructions by clearing the variables if needed.
886 if (!dtls_enabled_) {
887 cert_generator.reset();
888 certificate = nullptr;
889 } else if (certificate) {
890 // Favor generated certificate over the certificate generator.
891 cert_generator.reset();
892 }
893
894 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
895 signaling_thread(), channel_manager(), this, session_id(),
896 std::move(cert_generator), certificate));
897 webrtc_session_desc_factory_->SignalCertificateReady.connect(
898 this, &PeerConnection::OnCertificateReady);
899
900 if (options.disable_encryption) {
901 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
902 }
903
904 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
905 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36906
Steve Anton4171afb2017-11-20 18:20:22907 // Add default audio/video transceivers for Plan B SDP.
908 if (!IsUnifiedPlan()) {
909 transceivers_.push_back(
910 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
911 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
912 transceivers_.push_back(
913 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
914 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
915 }
916
henrike@webrtc.org28e20752013-07-10 00:45:36917 return true;
918}
919
Steve Anton038834f2017-07-14 22:59:59920RTCError PeerConnection::ValidateConfiguration(
921 const RTCConfiguration& config) const {
922 if (config.ice_regather_interval_range &&
923 config.continual_gathering_policy == GATHER_ONCE) {
924 return RTCError(RTCErrorType::INVALID_PARAMETER,
925 "ice_regather_interval_range specified but continual "
926 "gathering policy is GATHER_ONCE");
927 }
928 return RTCError::OK();
929}
930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52931rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36932PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 18:33:11933 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36934}
935
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52936rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36937PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 18:33:11938 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36939}
940
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29941bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 21:15:17942 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36943 if (IsClosed()) {
944 return false;
945 }
deadbeefab9b2d12015-10-14 18:33:11946 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36947 return false;
948 }
deadbeefab9b2d12015-10-14 18:33:11949
950 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:43951 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
952 observer->SignalAudioTrackAdded.connect(this,
953 &PeerConnection::OnAudioTrackAdded);
954 observer->SignalAudioTrackRemoved.connect(
955 this, &PeerConnection::OnAudioTrackRemoved);
956 observer->SignalVideoTrackAdded.connect(this,
957 &PeerConnection::OnVideoTrackAdded);
958 observer->SignalVideoTrackRemoved.connect(
959 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:29960 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:11961
deadbeefab9b2d12015-10-14 18:33:11962 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:25963 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:11964 }
965 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:25966 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:11967 }
968
tommi@webrtc.org03505bc2014-07-14 20:15:26969 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36970 observer_->OnRenegotiationNeeded();
971 return true;
972}
973
974void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 21:15:17975 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:25976 if (!IsClosed()) {
977 for (const auto& track : local_stream->GetAudioTracks()) {
978 RemoveAudioTrack(track.get(), local_stream);
979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
981 RemoveVideoTrack(track.get(), local_stream);
982 }
deadbeefab9b2d12015-10-14 18:33:11983 }
deadbeefab9b2d12015-10-14 18:33:11984 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:43985 stream_observers_.erase(
986 std::remove_if(
987 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:29988 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-16 03:24:43989 return observer->stream()->label().compare(local_stream->label()) ==
990 0;
991 }),
992 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:11993
henrike@webrtc.org28e20752013-07-10 00:45:36994 if (IsClosed()) {
995 return;
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36997 observer_->OnRenegotiationNeeded();
998}
999
deadbeefe1f9d832016-01-14 23:35:421000rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1001 MediaStreamTrackInterface* track,
1002 std::vector<MediaStreamInterface*> streams) {
1003 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571004 std::vector<std::string> stream_labels;
1005 for (auto* stream : streams) {
1006 if (!stream) {
1007 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1008 return nullptr;
1009 }
1010 stream_labels.push_back(stream->label());
1011 }
Steve Anton2d6c76a2018-01-06 01:10:521012 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 18:23:571013 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 23:35:421014 return nullptr;
1015 }
Steve Antonf9381f02017-12-14 18:23:571016 return sender_or_error.MoveValue();
1017}
1018
Steve Anton2d6c76a2018-01-06 01:10:521019RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571020 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1021 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-06 01:10:521022 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571023 if (!track) {
1024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1025 }
1026 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1027 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1028 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1029 "Track has invalid kind: " + track->kind());
1030 }
1031 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1032 if (stream_labels.size() > 1u) {
1033 LOG_AND_RETURN_ERROR(
1034 RTCErrorType::UNSUPPORTED_OPERATION,
1035 "AddTrack with more than one stream is not currently supported.");
1036 }
1037 if (IsClosed()) {
1038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1039 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421040 }
Steve Anton4171afb2017-11-20 18:20:221041 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571042 LOG_AND_RETURN_ERROR(
1043 RTCErrorType::INVALID_PARAMETER,
1044 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421045 }
Steve Antonf9381f02017-12-14 18:23:571046 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1047 // one stream. AddTrackInternal will return an error if there is more than one
1048 // stream, but if the caller specifies none then we need to generate a random
1049 // stream label.
1050 std::vector<std::string> adjusted_stream_labels = stream_labels;
1051 if (stream_labels.empty()) {
1052 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1053 }
1054 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1055 auto sender_or_error =
1056 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1057 : AddTrackPlanB(track, adjusted_stream_labels));
1058 if (sender_or_error.ok()) {
1059 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171060 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571061 }
1062 return sender_or_error;
1063}
deadbeefe1f9d832016-01-14 23:35:421064
Steve Antonf9381f02017-12-14 18:23:571065RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1066PeerConnection::AddTrackPlanB(
1067 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1068 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-11 00:26:061069 cricket::MediaType media_type =
1070 (track->kind() == MediaStreamTrackInterface::kAudioKind
1071 ? cricket::MEDIA_TYPE_AUDIO
1072 : cricket::MEDIA_TYPE_VIDEO);
1073 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 23:35:421074 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-11 00:26:061075 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 18:49:351076 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221077 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221078 const RtpSenderInfo* sender_info =
1079 FindSenderInfo(local_audio_sender_infos_,
1080 new_sender->internal()->stream_id(), track->id());
1081 if (sender_info) {
1082 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421083 }
Steve Antonf9381f02017-12-14 18:23:571084 } else {
1085 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-11 00:26:061086 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 18:49:351087 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221088 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221089 const RtpSenderInfo* sender_info =
1090 FindSenderInfo(local_video_sender_infos_,
1091 new_sender->internal()->stream_id(), track->id());
1092 if (sender_info) {
1093 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421094 }
deadbeefe1f9d832016-01-14 23:35:421095 }
Steve Anton02ee47c2018-01-11 00:26:061096 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571097}
deadbeefe1f9d832016-01-14 23:35:421098
Steve Antonf9381f02017-12-14 18:23:571099RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1100PeerConnection::AddTrackUnifiedPlan(
1101 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1102 const std::vector<std::string>& stream_labels) {
1103 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1104 if (transceiver) {
1105 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1106 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1107 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1108 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1109 }
Steve Anton02ee47c2018-01-11 00:26:061110 transceiver->sender()->SetTrack(track);
1111 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 18:23:571112 } else {
1113 cricket::MediaType media_type =
1114 (track->kind() == MediaStreamTrackInterface::kAudioKind
1115 ? cricket::MEDIA_TYPE_AUDIO
1116 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-11 00:26:061117 auto sender = CreateSender(media_type, track, stream_labels);
1118 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1119 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571120 transceiver->internal()->set_created_by_addtrack(true);
1121 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1122 }
Steve Antonf9381f02017-12-14 18:23:571123 return transceiver->sender();
1124}
1125
1126rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1127PeerConnection::FindFirstTransceiverForAddedTrack(
1128 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1129 RTC_DCHECK(track);
1130 for (auto transceiver : transceivers_) {
1131 if (!transceiver->sender()->track() &&
1132 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1133 track->kind() &&
1134 !transceiver->internal()->has_ever_been_used_to_send()) {
1135 return transceiver;
1136 }
1137 }
1138 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421139}
1140
1141bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1142 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 18:23:571143 return RemoveTrackInternal(sender).ok();
1144}
1145
1146RTCError PeerConnection::RemoveTrackInternal(
1147 rtc::scoped_refptr<RtpSenderInterface> sender) {
1148 if (!sender) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1150 }
deadbeefe1f9d832016-01-14 23:35:421151 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1153 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421154 }
Steve Antonf9381f02017-12-14 18:23:571155 if (IsUnifiedPlan()) {
1156 auto transceiver = FindTransceiverBySender(sender);
1157 if (!transceiver || !sender->track()) {
1158 return RTCError::OK();
1159 }
1160 sender->SetTrack(nullptr);
1161 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1162 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1163 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1164 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1165 }
Steve Anton4171afb2017-11-20 18:20:221166 } else {
Steve Antonf9381f02017-12-14 18:23:571167 bool removed;
1168 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1169 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1170 } else {
1171 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1172 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1173 }
1174 if (!removed) {
1175 LOG_AND_RETURN_ERROR(
1176 RTCErrorType::INVALID_PARAMETER,
1177 "Couldn't find sender " + sender->id() + " to remove.");
1178 }
Steve Anton4171afb2017-11-20 18:20:221179 }
deadbeefe1f9d832016-01-14 23:35:421180 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571181 return RTCError::OK();
1182}
1183
1184rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1185PeerConnection::FindTransceiverBySender(
1186 rtc::scoped_refptr<RtpSenderInterface> sender) {
1187 for (auto transceiver : transceivers_) {
1188 if (transceiver->sender() == sender) {
1189 return transceiver;
1190 }
1191 }
1192 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421193}
1194
Steve Anton9158ef62017-11-27 21:01:521195RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1196PeerConnection::AddTransceiver(
1197 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1198 return AddTransceiver(track, RtpTransceiverInit());
1199}
1200
1201RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1202PeerConnection::AddTransceiver(
1203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1204 const RtpTransceiverInit& init) {
1205 if (!IsUnifiedPlan()) {
1206 LOG_AND_RETURN_ERROR(
1207 RTCErrorType::INTERNAL_ERROR,
1208 "AddTransceiver only supported when Unified Plan is enabled.");
1209 }
1210 if (!track) {
1211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1212 }
1213 cricket::MediaType media_type;
1214 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1215 media_type = cricket::MEDIA_TYPE_AUDIO;
1216 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1217 media_type = cricket::MEDIA_TYPE_VIDEO;
1218 } else {
1219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1220 "Track kind is not audio or video");
1221 }
1222 return AddTransceiver(media_type, track, init);
1223}
1224
1225RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1226PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1227 return AddTransceiver(media_type, RtpTransceiverInit());
1228}
1229
1230RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1231PeerConnection::AddTransceiver(cricket::MediaType media_type,
1232 const RtpTransceiverInit& init) {
1233 if (!IsUnifiedPlan()) {
1234 LOG_AND_RETURN_ERROR(
1235 RTCErrorType::INTERNAL_ERROR,
1236 "AddTransceiver only supported when Unified Plan is enabled.");
1237 }
1238 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1239 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1241 "media type is not audio or video");
1242 }
1243 return AddTransceiver(media_type, nullptr, init);
1244}
1245
1246RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1247PeerConnection::AddTransceiver(
1248 cricket::MediaType media_type,
1249 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1250 const RtpTransceiverInit& init) {
1251 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1252 media_type == cricket::MEDIA_TYPE_VIDEO));
1253 if (track) {
1254 RTC_DCHECK_EQ(media_type,
1255 (track->kind() == MediaStreamTrackInterface::kAudioKind
1256 ? cricket::MEDIA_TYPE_AUDIO
1257 : cricket::MEDIA_TYPE_VIDEO));
1258 }
1259
1260 // TODO(bugs.webrtc.org/7600): Verify init.
1261
Steve Anton02ee47c2018-01-11 00:26:061262 if (init.stream_labels.size() > 1u) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1264 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 18:23:571265 }
1266
Steve Anton02ee47c2018-01-11 00:26:061267 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1268 ? init.stream_labels[0]
1269 : rtc::CreateRandomUuid()};
1270
1271 auto sender = CreateSender(media_type, track, stream_labels);
1272 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1273 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1274 transceiver->internal()->set_direction(init.direction);
1275
Steve Antonf9381f02017-12-14 18:23:571276 observer_->OnRenegotiationNeeded();
1277
1278 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1279}
1280
Steve Anton02ee47c2018-01-11 00:26:061281rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1282PeerConnection::CreateSender(
1283 cricket::MediaType media_type,
1284 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1285 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 21:01:521286 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061287 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1288 RTC_DCHECK(!track ||
1289 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1290 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1291 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351292 new AudioRtpSender(worker_thread(),
1293 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-11 00:26:061294 stream_labels, stats_.get()));
1295 } else {
1296 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1297 RTC_DCHECK(!track ||
1298 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1299 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1300 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351301 new VideoRtpSender(worker_thread(),
1302 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-11 00:26:061303 stream_labels));
1304 }
1305 sender->internal()->set_stream_ids(stream_labels);
1306 return sender;
1307}
1308
1309rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1310PeerConnection::CreateReceiver(cricket::MediaType media_type,
1311 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521312 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1313 receiver;
Steve Anton9158ef62017-11-27 21:01:521314 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521315 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 19:51:341316 signaling_thread(),
1317 new AudioRtpReceiver(worker_thread(), receiver_id, {}, 0, nullptr));
Steve Anton9158ef62017-11-27 21:01:521318 } else {
Steve Anton02ee47c2018-01-11 00:26:061319 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521320 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1321 signaling_thread(),
Steve Anton60776752018-01-10 19:51:341322 new VideoRtpReceiver(worker_thread(), receiver_id, {}, 0, nullptr));
Steve Anton9158ef62017-11-27 21:01:521323 }
Steve Anton02ee47c2018-01-11 00:26:061324 return receiver;
1325}
1326
1327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1328PeerConnection::CreateAndAddTransceiver(
1329 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1330 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1331 receiver) {
1332 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1333 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521334 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 18:23:571335 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521336}
1337
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521338rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:361339 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 21:15:171340 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 18:07:251341 if (IsClosed()) {
1342 return nullptr;
1343 }
henrike@webrtc.org28e20752013-07-10 00:45:361344 if (!track) {
Mirko Bonadei675513b2017-11-09 10:09:251345 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-02 04:27:001346 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361347 }
Steve Anton4171afb2017-11-20 18:20:221348 auto track_sender = FindSenderForTrack(track);
1349 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 10:09:251350 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-02 04:27:001351 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361352 }
1353
Steve Anton4171afb2017-11-20 18:20:221354 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:361355}
1356
deadbeeffac06552015-11-25 19:26:011357rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441358 const std::string& kind,
1359 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 21:15:171360 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251361 if (IsClosed()) {
1362 return nullptr;
1363 }
Steve Anton4171afb2017-11-20 18:20:221364
Steve Anton02ee47c2018-01-11 00:26:061365 std::vector<std::string> stream_labels;
1366 if (!stream_id.empty()) {
1367 stream_labels.push_back(stream_id);
1368 }
1369
Steve Anton4171afb2017-11-20 18:20:221370 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391371 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011372 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 18:49:351373 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1374 stream_labels, stats_.get());
1375 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391376 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061377 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221378 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011379 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351380 auto* video_sender =
1381 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1382 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391383 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061384 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221385 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011386 } else {
Mirko Bonadei675513b2017-11-09 10:09:251387 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221388 return nullptr;
deadbeeffac06552015-11-25 19:26:011389 }
Steve Anton4171afb2017-11-20 18:20:221390
deadbeefe1f9d832016-01-14 23:35:421391 return new_sender;
deadbeeffac06552015-11-25 19:26:011392}
1393
deadbeef70ab1a12015-09-28 23:53:551394std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1395 const {
deadbeefa601f5c2016-06-06 21:27:391396 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221397 for (auto sender : GetSendersInternal()) {
1398 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391399 }
1400 return ret;
deadbeef70ab1a12015-09-28 23:53:551401}
1402
Steve Anton4171afb2017-11-20 18:20:221403std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1404PeerConnection::GetSendersInternal() const {
1405 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1406 all_senders;
1407 for (auto transceiver : transceivers_) {
1408 auto senders = transceiver->internal()->senders();
1409 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1410 }
1411 return all_senders;
1412}
1413
deadbeef70ab1a12015-09-28 23:53:551414std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1415PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391416 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221417 for (const auto& receiver : GetReceiversInternal()) {
1418 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391419 }
1420 return ret;
deadbeef70ab1a12015-09-28 23:53:551421}
1422
Steve Anton4171afb2017-11-20 18:20:221423std::vector<
1424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1425PeerConnection::GetReceiversInternal() const {
1426 std::vector<
1427 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1428 all_receivers;
1429 for (auto transceiver : transceivers_) {
1430 auto receivers = transceiver->internal()->receivers();
1431 all_receivers.insert(all_receivers.end(), receivers.begin(),
1432 receivers.end());
1433 }
1434 return all_receivers;
1435}
1436
Steve Anton9158ef62017-11-27 21:01:521437std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1438PeerConnection::GetTransceivers() const {
1439 RTC_DCHECK(IsUnifiedPlan());
1440 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1441 for (auto transceiver : transceivers_) {
1442 all_transceivers.push_back(transceiver);
1443 }
1444 return all_transceivers;
1445}
1446
henrike@webrtc.org28e20752013-07-10 00:45:361447bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491448 MediaStreamTrackInterface* track,
1449 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171450 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281451 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561452 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251453 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361454 return false;
1455 }
1456
tommi@webrtc.org03505bc2014-07-14 20:15:261457 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151458 // The StatsCollector is used to tell if a track is valid because it may
1459 // remember tracks that the PeerConnection previously removed.
1460 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251461 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1462 << track->id();
zhihuange9e94c32016-11-04 18:38:151463 return false;
1464 }
Taylor Brandstetter5d97a9a2016-06-10 21:17:271465 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:301466 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361467 return true;
1468}
1469
hbos74e1a4f2016-09-16 06:33:011470void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1471 RTC_DCHECK(stats_collector_);
1472 stats_collector_->GetStatsReport(callback);
1473}
1474
henrike@webrtc.org28e20752013-07-10 00:45:361475PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1476 return signaling_state_;
1477}
1478
henrike@webrtc.org28e20752013-07-10 00:45:361479PeerConnectionInterface::IceConnectionState
1480PeerConnection::ice_connection_state() {
1481 return ice_connection_state_;
1482}
1483
1484PeerConnectionInterface::IceGatheringState
1485PeerConnection::ice_gathering_state() {
1486 return ice_gathering_state_;
1487}
1488
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521489rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361490PeerConnection::CreateDataChannel(
1491 const std::string& label,
1492 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171493 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501494
deadbeefab9b2d12015-10-14 18:33:111495 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111496
kwibergd1fe2812016-04-27 13:47:291497 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581498 if (config) {
1499 internal_config.reset(new InternalDataChannelInit(*config));
1500 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521501 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111502 InternalCreateDataChannel(label, internal_config.get()));
1503 if (!channel.get()) {
1504 return nullptr;
1505 }
henrike@webrtc.org28e20752013-07-10 00:45:361506
jiayl@webrtc.org001fd2d2014-05-29 15:31:111507 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1508 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171509 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:111510 observer_->OnRenegotiationNeeded();
1511 }
wu@webrtc.org91053e72013-08-10 07:18:041512
henrike@webrtc.org28e20752013-07-10 00:45:361513 return DataChannelProxy::Create(signaling_thread(), channel.get());
1514}
1515
1516void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1517 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171518 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511519
zhihuang1c378ed2017-08-17 21:10:501520 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1521 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1522 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1523 // compares the mandatory fields parsed with the mandatory fields added in the
1524 // |constraints| and some downstream applications might create offers with
1525 // mandatory fields which would not be parsed in the helper method. For
1526 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1527 // |constraints| as a mandatory field but it is not parsed.
1528 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161529
zhihuang1c378ed2017-08-17 21:10:501530 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161531}
1532
1533void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1534 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171535 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511536
nisse7ce109a2017-01-31 08:57:561537 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251538 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161539 return;
1540 }
deadbeefab9b2d12015-10-14 18:33:111541
Steve Anton8d3444d2017-10-20 22:30:511542 if (IsClosed()) {
1543 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251544 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 22:30:511545 PostCreateSessionDescriptionFailure(observer, error);
1546 return;
1547 }
1548
zhihuang1c378ed2017-08-17 21:10:501549 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111550 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251551 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 18:33:111552 PostCreateSessionDescriptionFailure(observer, error);
1553 return;
1554 }
1555
zhihuang1c378ed2017-08-17 21:10:501556 cricket::MediaSessionOptions session_options;
1557 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291558 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361559}
1560
1561void PeerConnection::CreateAnswer(
1562 CreateSessionDescriptionObserver* observer,
1563 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171564 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 22:30:511565
nisse7ce109a2017-01-31 08:57:561566 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251567 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361568 return;
1569 }
deadbeefab9b2d12015-10-14 18:33:111570
zhihuang1c378ed2017-08-17 21:10:501571 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1572 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1573 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 18:33:111574 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 10:09:251575 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 18:33:111576 PostCreateSessionDescriptionFailure(observer, error);
1577 return;
1578 }
1579
Steve Anton8d3444d2017-10-20 22:30:511580 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 10:51:391581}
1582
1583void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1584 const RTCOfferAnswerOptions& options) {
1585 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561586 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251587 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391588 return;
1589 }
1590
Steve Anton8d3444d2017-10-20 22:30:511591 if (IsClosed()) {
1592 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251593 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 22:30:511594 PostCreateSessionDescriptionFailure(observer, error);
1595 return;
1596 }
1597
Steve Anton75737c02017-11-06 18:37:171598 if (remote_description() &&
Steve Antona3a92c22017-12-07 18:27:411599 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 22:30:511600 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 10:09:251601 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 22:30:511602 PostCreateSessionDescriptionFailure(observer, error);
1603 return;
1604 }
1605
htaa2a49d92016-03-04 10:51:391606 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501607 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391608
Steve Antond25da372017-11-06 22:50:291609 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361610}
1611
1612void PeerConnection::SetLocalDescription(
1613 SetSessionDescriptionObserver* observer,
1614 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 21:15:171615 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561616
nisse7ce109a2017-01-31 08:57:561617 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251618 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361619 return;
1620 }
Steve Anton8a006912017-12-04 23:25:561621
henrike@webrtc.org28e20752013-07-10 00:45:361622 if (!desc) {
1623 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1624 return;
1625 }
Steve Anton8d3444d2017-10-20 22:30:511626
Steve Antona3a92c22017-12-07 18:27:411627 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 22:30:511628
Steve Anton8a006912017-12-04 23:25:561629 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1630 // |desc| may be destroyed at this point.
1631
1632 if (!error.ok()) {
Steve Antona3a92c22017-12-07 18:27:411633 std::ostringstream oss;
1634 oss << "Failed to set local " << SdpTypeToString(type)
1635 << " sdp: " << error.message();
1636 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 23:25:561637 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1638 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 22:30:511639 return;
1640 }
Steve Anton8a006912017-12-04 23:25:561641 RTC_DCHECK(local_description());
1642
1643 PostSetSessionDescriptionSuccess(observer);
1644
1645 // According to JSEP, after setLocalDescription, changing the candidate pool
1646 // size is not allowed, and changing the set of ICE servers will not result
1647 // in new candidates being gathered.
1648 port_allocator_->FreezeCandidatePool();
1649
1650 // MaybeStartGathering needs to be called after posting
1651 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1652 // before signaling that SetLocalDescription completed.
1653 transport_controller_->MaybeStartGathering();
1654
Steve Antona3a92c22017-12-07 18:27:411655 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561656 // TODO(deadbeef): We already had to hop to the network thread for
1657 // MaybeStartGathering...
1658 network_thread()->Invoke<void>(
1659 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1660 port_allocator_.get()));
1661 }
1662}
1663
1664RTCError PeerConnection::ApplyLocalDescription(
1665 std::unique_ptr<SessionDescriptionInterface> desc) {
1666 RTC_DCHECK_RUN_ON(signaling_thread());
1667 RTC_DCHECK(desc);
1668
1669 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1670 if (!error.ok()) {
1671 return error;
1672 }
Steve Anton8d3444d2017-10-20 22:30:511673
henrike@webrtc.org28e20752013-07-10 00:45:361674 // Update stats here so that we have the most recent stats for tracks and
1675 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:261676 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:561677
1678 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 18:34:511679 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 23:25:561680 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 18:34:511681 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 23:25:561682 if (*initial_offerer_) {
1683 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1684 } else {
1685 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1686 }
henrike@webrtc.org28e20752013-07-10 00:45:361687 }
Steve Anton8a006912017-12-04 23:25:561688
Steve Antondcc3c022017-12-23 00:02:541689 // Take a reference to the old local description since it's used below to
1690 // compare against the new local description. When setting the new local
1691 // description, grab ownership of the replaced session description in case it
1692 // is the same as |old_local_description|, to keep it alive for the duration
1693 // of the method.
1694 const SessionDescriptionInterface* old_local_description =
1695 local_description();
1696 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 18:34:511697 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:541698 replaced_local_description = pending_local_description_
1699 ? std::move(pending_local_description_)
1700 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:561701 current_local_description_ = std::move(desc);
1702 pending_local_description_ = nullptr;
1703 current_remote_description_ = std::move(pending_remote_description_);
1704 } else {
Steve Antondcc3c022017-12-23 00:02:541705 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:561706 pending_local_description_ = std::move(desc);
1707 }
1708 // The session description to apply now must be accessed by
1709 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:441710 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:111711
Steve Antondcc3c022017-12-23 00:02:541712 if (IsUnifiedPlan()) {
1713 RTCError error = UpdateTransceiversAndDataChannels(
1714 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 23:25:561715 if (!error.ok()) {
1716 return error;
1717 }
Steve Antondcc3c022017-12-23 00:02:541718 for (auto transceiver : transceivers_) {
1719 const ContentInfo* content =
1720 FindMediaSectionForTransceiver(transceiver, local_description());
1721 if (!content) {
1722 continue;
1723 }
1724 const MediaContentDescription* media_desc = content->media_description();
1725 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1726 transceiver->internal()->set_current_direction(media_desc->direction());
1727 }
1728 if (content->rejected && !transceiver->stopped()) {
1729 transceiver->Stop();
1730 }
1731 }
1732 } else {
1733 // Transport and Media channels will be created only when offer is set.
1734 if (type == SdpType::kOffer) {
1735 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1736 // description is applied. Restore back to old description.
1737 RTCError error = CreateChannels(*local_description()->description());
1738 if (!error.ok()) {
1739 return error;
1740 }
1741 }
Steve Anton8a006912017-12-04 23:25:561742
Steve Antondcc3c022017-12-23 00:02:541743 // Remove unused channels if MediaContentDescription is rejected.
1744 RemoveUnusedChannels(local_description()->description());
1745 }
Steve Anton8a006912017-12-04 23:25:561746
Steve Anton3828c062017-12-06 18:34:511747 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 23:25:561748 if (!error.ok()) {
1749 return error;
1750 }
Steve Antondcc3c022017-12-23 00:02:541751
Steve Anton8a006912017-12-04 23:25:561752 if (remote_description()) {
1753 // Now that we have a local description, we can push down remote candidates.
1754 UseCandidatesInSessionDescription(remote_description());
1755 }
1756
1757 pending_ice_restarts_.clear();
1758 if (session_error() != SessionError::kNone) {
1759 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1760 }
1761
deadbeefab9b2d12015-10-14 18:33:111762 // If setting the description decided our SSL role, allocate any necessary
1763 // SCTP sids.
1764 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:171765 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:111766 AllocateSctpSids(role);
1767 }
1768
Steve Antondcc3c022017-12-23 00:02:541769 if (!IsUnifiedPlan()) {
1770 // Update state and SSRC of local MediaStreams and DataChannels based on the
1771 // local session description.
1772 const cricket::ContentInfo* audio_content =
1773 GetFirstAudioContent(local_description()->description());
1774 if (audio_content) {
1775 if (audio_content->rejected) {
1776 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1777 } else {
1778 const cricket::AudioContentDescription* audio_desc =
1779 audio_content->media_description()->as_audio();
1780 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1781 }
deadbeeffaac4972015-11-12 23:33:071782 }
deadbeefab9b2d12015-10-14 18:33:111783
Steve Antondcc3c022017-12-23 00:02:541784 const cricket::ContentInfo* video_content =
1785 GetFirstVideoContent(local_description()->description());
1786 if (video_content) {
1787 if (video_content->rejected) {
1788 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1789 } else {
1790 const cricket::VideoContentDescription* video_desc =
1791 video_content->media_description()->as_video();
1792 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1793 }
deadbeeffaac4972015-11-12 23:33:071794 }
deadbeefab9b2d12015-10-14 18:33:111795 }
1796
1797 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:441798 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:111799 if (data_content) {
1800 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:301801 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:111802 if (rtc::starts_with(data_desc->protocol().data(),
1803 cricket::kMediaProtocolRtpPrefix)) {
1804 UpdateLocalRtpDataChannels(data_desc->streams());
1805 }
1806 }
1807
Steve Anton8a006912017-12-04 23:25:561808 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:361809}
1810
1811void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:071812 SetSessionDescriptionObserver* observer,
1813 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:321814 SetRemoteDescription(
1815 std::unique_ptr<SessionDescriptionInterface>(desc),
1816 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1817 new SetRemoteDescriptionObserverAdapter(this, observer)));
1818}
1819
1820void PeerConnection::SetRemoteDescription(
1821 std::unique_ptr<SessionDescriptionInterface> desc,
1822 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:171823 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:561824
nisse7ce109a2017-01-31 08:57:561825 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251826 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361827 return;
1828 }
Steve Anton8a006912017-12-04 23:25:561829
henrike@webrtc.org28e20752013-07-10 00:45:361830 if (!desc) {
Henrik Boström31638672017-11-23 16:48:321831 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:561832 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361833 return;
1834 }
Steve Anton8d3444d2017-10-20 22:30:511835
Steve Antona3a92c22017-12-07 18:27:411836 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 23:25:561837
1838 RTCError error = ApplyRemoteDescription(std::move(desc));
1839 // |desc| may be destroyed at this point.
1840
1841 if (!error.ok()) {
Steve Antona3a92c22017-12-07 18:27:411842 std::ostringstream oss;
1843 oss << "Failed to set remote " << SdpTypeToString(type)
1844 << " sdp: " << error.message();
1845 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 23:25:561846 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 16:48:321847 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 23:25:561848 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511849 return;
1850 }
1851
Steve Antona3a92c22017-12-07 18:27:411852 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561853 // TODO(deadbeef): We already had to hop to the network thread for
1854 // MaybeStartGathering...
1855 network_thread()->Invoke<void>(
1856 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1857 port_allocator_.get()));
1858 }
1859
1860 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1861}
1862
1863RTCError PeerConnection::ApplyRemoteDescription(
1864 std::unique_ptr<SessionDescriptionInterface> desc) {
1865 RTC_DCHECK_RUN_ON(signaling_thread());
1866 RTC_DCHECK(desc);
1867
1868 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1869 if (!error.ok()) {
1870 return error;
1871 }
1872
henrike@webrtc.org28e20752013-07-10 00:45:361873 // Update stats here so that we have the most recent stats for tracks and
1874 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:261875 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:561876
Steve Antondcc3c022017-12-23 00:02:541877 // Take a reference to the old remote description since it's used below to
1878 // compare against the new remote description. When setting the new remote
1879 // description, grab ownership of the replaced session description in case it
1880 // is the same as |old_remote_description|, to keep it alive for the duration
1881 // of the method.
Steve Anton8a006912017-12-04 23:25:561882 const SessionDescriptionInterface* old_remote_description =
1883 remote_description();
Steve Anton8a006912017-12-04 23:25:561884 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:511885 SdpType type = desc->GetType();
1886 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561887 replaced_remote_description = pending_remote_description_
1888 ? std::move(pending_remote_description_)
1889 : std::move(current_remote_description_);
1890 current_remote_description_ = std::move(desc);
1891 pending_remote_description_ = nullptr;
1892 current_local_description_ = std::move(pending_local_description_);
1893 } else {
1894 replaced_remote_description = std::move(pending_remote_description_);
1895 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:361896 }
Steve Anton8a006912017-12-04 23:25:561897 // The session description to apply now must be accessed by
1898 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:441899 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:361900
Steve Anton8a006912017-12-04 23:25:561901 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:541902 if (IsUnifiedPlan()) {
1903 RTCError error = UpdateTransceiversAndDataChannels(
1904 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 23:25:561905 if (!error.ok()) {
1906 return error;
1907 }
Steve Antondcc3c022017-12-23 00:02:541908 } else {
1909 if (type == SdpType::kOffer) {
1910 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1911 // description is applied. Restore back to old description.
1912 RTCError error = CreateChannels(*remote_description()->description());
1913 if (!error.ok()) {
1914 return error;
1915 }
1916 }
Steve Anton8a006912017-12-04 23:25:561917
Steve Antondcc3c022017-12-23 00:02:541918 // Remove unused channels if MediaContentDescription is rejected.
1919 RemoveUnusedChannels(remote_description()->description());
1920 }
Steve Anton8a006912017-12-04 23:25:561921
1922 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1923 // is called.
Steve Anton3828c062017-12-06 18:34:511924 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 23:25:561925 if (!error.ok()) {
1926 return error;
1927 }
1928
1929 if (local_description() &&
1930 !UseCandidatesInSessionDescription(remote_description())) {
1931 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1932 }
1933
1934 if (old_remote_description) {
1935 for (const cricket::ContentInfo& content :
1936 old_remote_description->description()->contents()) {
1937 // Check if this new SessionDescription contains new ICE ufrag and
1938 // password that indicates the remote peer requests an ICE restart.
1939 // TODO(deadbeef): When we start storing both the current and pending
1940 // remote description, this should reset pending_ice_restarts and compare
1941 // against the current description.
1942 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1943 content.name)) {
Steve Anton3828c062017-12-06 18:34:511944 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:561945 pending_ice_restarts_.insert(content.name);
1946 }
1947 } else {
1948 // We retain all received candidates only if ICE is not restarted.
1949 // When ICE is restarted, all previous candidates belong to an old
1950 // generation and should not be kept.
1951 // TODO(deadbeef): This goes against the W3C spec which says the remote
1952 // description should only contain candidates from the last set remote
1953 // description plus any candidates added since then. We should remove
1954 // this once we're sure it won't break anything.
1955 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1956 old_remote_description, content.name, mutable_remote_description());
1957 }
1958 }
1959 }
1960
1961 if (session_error() != SessionError::kNone) {
1962 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1963 }
1964
1965 // Set the the ICE connection state to connecting since the connection may
1966 // become writable with peer reflexive candidates before any remote candidate
1967 // is signaled.
1968 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1969 // is to have a new signal the indicates a change in checking state from the
1970 // transport and expose a new checking() member from transport that can be
1971 // read to determine the current checking state. The existing SignalConnecting
1972 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:411973 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 23:25:561974 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1975 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1976 }
1977
deadbeefab9b2d12015-10-14 18:33:111978 // If setting the description decided our SSL role, allocate any necessary
1979 // SCTP sids.
1980 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:171981 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:111982 AllocateSctpSids(role);
1983 }
1984
Steve Antondcc3c022017-12-23 00:02:541985 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-11 01:15:201986 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-23 00:02:541987 for (auto transceiver : transceivers_) {
1988 const ContentInfo* content =
1989 FindMediaSectionForTransceiver(transceiver, remote_description());
1990 if (!content) {
1991 continue;
1992 }
1993 const MediaContentDescription* media_desc = content->media_description();
1994 RtpTransceiverDirection local_direction =
1995 RtpTransceiverDirectionReversed(media_desc->direction());
1996 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
1997 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
1998 // transceiver's current direction is neither sendrecv nor recvonly,
1999 // process the addition of a remote track for the media description.
2000 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2001 (!transceiver->current_direction() ||
2002 !RtpTransceiverDirectionHasRecv(
2003 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-11 01:15:202004 const std::string& sync_label = media_desc->streams()[0].sync_label;
2005 rtc::scoped_refptr<MediaStreamInterface> stream =
2006 remote_streams_->find(sync_label);
2007 if (!stream) {
2008 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2009 MediaStream::Create(sync_label));
2010 remote_streams_->AddStream(stream);
2011 }
2012 transceiver->internal()->receiver_internal()->SetStreams({stream});
2013 TrackEvent track_event;
2014 track_event.receiver = transceiver->receiver();
2015 track_event.streams = transceiver->receiver()->streams();
2016 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-23 00:02:542017 }
2018 // If direction is sendonly or inactive, and transceiver's current
2019 // direction is neither sendonly nor inactive, process the removal of a
2020 // remote track for the media description.
2021 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-11 01:15:202022 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-23 00:02:542023 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-11 01:15:202024 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-23 00:02:542025 }
2026 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2027 transceiver->internal()->set_current_direction(local_direction);
2028 }
2029 if (content->rejected && !transceiver->stopped()) {
2030 transceiver->Stop();
2031 }
2032 }
Steve Antonef65ef12018-01-11 01:15:202033 for (auto event : track_events) {
2034 observer_->OnAddTrack(event.receiver, event.streams);
2035 }
Steve Antondcc3c022017-12-23 00:02:542036 }
2037
Henrik Boströmfdb92012017-11-09 18:55:442038 const cricket::ContentInfo* audio_content =
2039 GetFirstAudioContent(remote_description()->description());
2040 const cricket::ContentInfo* video_content =
2041 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402042 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442043 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402044 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442045 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402046 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442047 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402048
2049 // Check if the descriptions include streams, just in case the peer supports
2050 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442051 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402052 (audio_desc && !audio_desc->streams().empty()) ||
2053 (video_desc && !video_desc->streams().empty())) {
2054 remote_peer_supports_msid_ = true;
2055 }
deadbeefab9b2d12015-10-14 18:33:112056
2057 // We wait to signal new streams until we finish processing the description,
2058 // since only at that point will new streams have all their tracks.
2059 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2060
Steve Antondcc3c022017-12-23 00:02:542061 if (!IsUnifiedPlan()) {
2062 // TODO(steveanton): When removing RTP senders/receivers in response to a
2063 // rejected media section, there is some cleanup logic that expects the
2064 // voice/ video channel to still be set. But in this method the voice/video
2065 // channel would have been destroyed by the SetRemoteDescription caller
2066 // above so the cleanup that relies on them fails to run. The RemoveSenders
2067 // calls should be moved to right before the DestroyChannel calls to fix
2068 // this.
Steve Anton8d3444d2017-10-20 22:30:512069
Steve Antondcc3c022017-12-23 00:02:542070 // Find all audio rtp streams and create corresponding remote AudioTracks
2071 // and MediaStreams.
2072 if (audio_content) {
2073 if (audio_content->rejected) {
2074 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2075 } else {
2076 bool default_audio_track_needed =
2077 !remote_peer_supports_msid_ &&
2078 RtpTransceiverDirectionHasSend(audio_desc->direction());
2079 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2080 default_audio_track_needed, audio_desc->type(),
2081 new_streams);
2082 }
deadbeeffaac4972015-11-12 23:33:072083 }
deadbeefab9b2d12015-10-14 18:33:112084
Steve Antondcc3c022017-12-23 00:02:542085 // Find all video rtp streams and create corresponding remote VideoTracks
2086 // and MediaStreams.
2087 if (video_content) {
2088 if (video_content->rejected) {
2089 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2090 } else {
2091 bool default_video_track_needed =
2092 !remote_peer_supports_msid_ &&
2093 RtpTransceiverDirectionHasSend(video_desc->direction());
2094 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2095 default_video_track_needed, video_desc->type(),
2096 new_streams);
2097 }
deadbeeffaac4972015-11-12 23:33:072098 }
deadbeefab9b2d12015-10-14 18:33:112099
Steve Antondcc3c022017-12-23 00:02:542100 // Update the DataChannels with the information from the remote peer.
2101 if (data_desc) {
2102 if (rtc::starts_with(data_desc->protocol().data(),
2103 cricket::kMediaProtocolRtpPrefix)) {
2104 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2105 }
deadbeefab9b2d12015-10-14 18:33:112106 }
deadbeefab9b2d12015-10-14 18:33:112107
Steve Antondcc3c022017-12-23 00:02:542108 // Iterate new_streams and notify the observer about new MediaStreams.
2109 for (size_t i = 0; i < new_streams->count(); ++i) {
2110 MediaStreamInterface* new_stream = new_streams->at(i);
2111 stats_->AddStream(new_stream);
2112 observer_->OnAddStream(
2113 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2114 }
deadbeefab9b2d12015-10-14 18:33:112115
Steve Antondcc3c022017-12-23 00:02:542116 UpdateEndedRemoteMediaStreams();
2117 }
deadbeefab9b2d12015-10-14 18:33:112118
Steve Anton8a006912017-12-04 23:25:562119 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332120}
2121
Steve Antondcc3c022017-12-23 00:02:542122RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2123 cricket::ContentSource source,
2124 const SessionDescriptionInterface* old_session,
2125 const SessionDescriptionInterface& new_session) {
2126 RTC_DCHECK(IsUnifiedPlan());
2127
2128 auto bundle_group_or_error = GetEarlyBundleGroup(*new_session.description());
2129 if (!bundle_group_or_error.ok()) {
2130 return bundle_group_or_error.MoveError();
2131 }
2132 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
2133
2134 const ContentInfos& old_contents =
2135 (old_session ? old_session->description()->contents() : ContentInfos());
2136 const ContentInfos& new_contents = new_session.description()->contents();
2137
2138 for (size_t i = 0; i < new_contents.size(); ++i) {
2139 const cricket::ContentInfo& new_content = new_contents[i];
2140 const cricket::ContentInfo* old_content =
2141 (i < old_contents.size() ? &old_contents[i] : nullptr);
2142 cricket::MediaType media_type = new_content.media_description()->type();
2143 seen_mids_.insert(new_content.name);
2144 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2145 media_type == cricket::MEDIA_TYPE_VIDEO) {
2146 auto transceiver_or_error =
2147 AssociateTransceiver(source, i, new_content, old_content);
2148 if (!transceiver_or_error.ok()) {
2149 return transceiver_or_error.MoveError();
2150 }
2151 auto transceiver = transceiver_or_error.MoveValue();
2152 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2153 continue;
2154 }
2155 RTCError error =
2156 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2157 if (!error.ok()) {
2158 return error;
2159 }
2160 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232161 if (GetDataMid() && new_content.name != *GetDataMid()) {
2162 // Ignore all but the first data section.
2163 continue;
2164 }
2165 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2166 if (!error.ok()) {
2167 return error;
2168 }
Steve Antondcc3c022017-12-23 00:02:542169 } else {
2170 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2171 "Unknown section type.");
2172 }
2173 }
2174
2175 return RTCError::OK();
2176}
2177
2178RTCError PeerConnection::UpdateTransceiverChannel(
2179 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2180 transceiver,
2181 const cricket::ContentInfo& content,
2182 const cricket::ContentGroup* bundle_group) {
2183 RTC_DCHECK(IsUnifiedPlan());
2184 RTC_DCHECK(transceiver);
2185 cricket::BaseChannel* channel = transceiver->internal()->channel();
2186 if (content.rejected) {
2187 if (channel) {
2188 transceiver->internal()->SetChannel(nullptr);
2189 DestroyBaseChannel(channel);
2190 }
2191 } else {
2192 if (!channel) {
2193 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2194 channel = CreateVoiceChannel(
2195 content.name,
2196 GetTransportNameForMediaSection(content.name, bundle_group));
2197 } else {
2198 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2199 transceiver->internal()->media_type());
2200 channel = CreateVideoChannel(
2201 content.name,
2202 GetTransportNameForMediaSection(content.name, bundle_group));
2203 }
2204 if (!channel) {
2205 LOG_AND_RETURN_ERROR(
2206 RTCErrorType::INTERNAL_ERROR,
2207 "Failed to create channel for mid=" + content.name);
2208 }
2209 transceiver->internal()->SetChannel(channel);
2210 }
2211 }
2212 return RTCError::OK();
2213}
2214
Steve Antonfa2260d2017-12-29 00:38:232215RTCError PeerConnection::UpdateDataChannel(
2216 cricket::ContentSource source,
2217 const cricket::ContentInfo& content,
2218 const cricket::ContentGroup* bundle_group) {
2219 if (data_channel_type_ == cricket::DCT_NONE) {
2220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2221 "Data channels are not supported.");
2222 }
2223 if (content.rejected) {
2224 DestroyDataChannel();
2225 } else {
2226 if (!rtp_data_channel_ && !sctp_transport_) {
2227 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2228 content.name, bundle_group))) {
2229 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2230 "Failed to create data channel.");
2231 }
2232 }
2233 if (source == cricket::CS_REMOTE) {
2234 const MediaContentDescription* data_desc = content.media_description();
2235 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2236 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2237 }
2238 }
2239 }
2240 return RTCError::OK();
2241}
2242
Steve Antondcc3c022017-12-23 00:02:542243RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2244PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2245 size_t mline_index,
2246 const ContentInfo& content,
2247 const ContentInfo* old_content) {
2248 RTC_DCHECK(IsUnifiedPlan());
2249 // If the m= section is being recycled (rejected in previous remote
2250 // description, not rejected in current description), dissociate the currently
2251 // associated RtpTransceiver by setting its mid property to null, and discard
2252 // the mapping between the transceiver and its m= section index.
2253 if (old_content && old_content->rejected && !content.rejected) {
2254 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2255 if (old_transceiver) {
2256 old_transceiver->internal()->set_mid(rtc::nullopt);
2257 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2258 }
2259 }
2260 const MediaContentDescription* media_desc = content.media_description();
2261 auto transceiver = GetAssociatedTransceiver(content.name);
2262 if (source == cricket::CS_LOCAL) {
2263 // Find the RtpTransceiver that corresponds to this m= section, using the
2264 // mapping between transceivers and m= section indices established when
2265 // creating the offer.
2266 if (!transceiver) {
2267 transceiver = GetTransceiverByMLineIndex(mline_index);
2268 }
2269 if (!transceiver) {
2270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2271 "Unknown transceiver");
2272 }
2273 } else {
2274 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2275 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2276 // of the same type...
2277 if (!transceiver &&
2278 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2279 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2280 }
2281 // If no RtpTransceiver was found in the previous step, create one with a
2282 // recvonly direction.
2283 if (!transceiver) {
Steve Anton02ee47c2018-01-11 00:26:062284 auto sender =
2285 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2286 auto receiver =
2287 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2288 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542289 transceiver->internal()->set_direction(
2290 RtpTransceiverDirection::kRecvOnly);
2291 }
2292 }
2293 RTC_DCHECK(transceiver);
2294 if (transceiver->internal()->media_type() != media_desc->type()) {
2295 LOG_AND_RETURN_ERROR(
2296 RTCErrorType::INVALID_PARAMETER,
2297 "Transceiver type does not match media description type.");
2298 }
2299 // Associate the found or created RtpTransceiver with the m= section by
2300 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2301 // section, and establish a mapping between the transceiver and the index of
2302 // the m= section.
2303 transceiver->internal()->set_mid(content.name);
2304 transceiver->internal()->set_mline_index(mline_index);
2305 return std::move(transceiver);
2306}
2307
2308rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2309PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2310 RTC_DCHECK(IsUnifiedPlan());
2311 for (auto transceiver : transceivers_) {
2312 if (transceiver->mid() == mid) {
2313 return transceiver;
2314 }
2315 }
2316 return nullptr;
2317}
2318
2319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2320PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2321 RTC_DCHECK(IsUnifiedPlan());
2322 for (auto transceiver : transceivers_) {
2323 if (transceiver->internal()->mline_index() == mline_index) {
2324 return transceiver;
2325 }
2326 }
2327 return nullptr;
2328}
2329
2330rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2331PeerConnection::FindAvailableTransceiverToReceive(
2332 cricket::MediaType media_type) const {
2333 RTC_DCHECK(IsUnifiedPlan());
2334 // From JSEP section 5.10 (Applying a Remote Description):
2335 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2336 // the same type that were added to the PeerConnection by addTrack and are not
2337 // associated with any m= section and are not stopped, find the first such
2338 // RtpTransceiver.
2339 for (auto transceiver : transceivers_) {
2340 if (transceiver->internal()->media_type() == media_type &&
2341 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2342 !transceiver->stopped()) {
2343 return transceiver;
2344 }
2345 }
2346 return nullptr;
2347}
2348
Steve Antoned10bd92017-12-05 18:52:592349const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2350 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2351 transceiver,
2352 const SessionDescriptionInterface* sdesc) const {
2353 RTC_DCHECK(transceiver);
2354 RTC_DCHECK(sdesc);
2355 if (IsUnifiedPlan()) {
2356 if (!transceiver->internal()->mid()) {
2357 // This transceiver is not associated with a media section yet.
2358 return nullptr;
2359 }
2360 return sdesc->description()->GetContentByName(
2361 *transceiver->internal()->mid());
2362 } else {
2363 // Plan B only allows at most one audio and one video section, so use the
2364 // first media section of that type.
2365 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2366 transceiver->internal()->media_type());
2367 }
2368}
2369
deadbeef46c73892016-11-17 03:42:042370PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2371 return configuration_;
2372}
2373
deadbeef293e9262017-01-11 20:28:302374bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2375 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172376 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-13 02:49:322377
Steve Anton75737c02017-11-06 18:37:172378 if (local_description() && configuration.ice_candidate_pool_size !=
2379 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252380 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2381 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302382 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452383 }
Taylor Brandstettera1c30352016-05-13 15:15:112384
deadbeef293e9262017-01-11 20:28:302385 // The simplest (and most future-compatible) way to tell if the config was
2386 // modified in an invalid way is to copy each property we do support
2387 // modifying, then use operator==. There are far more properties we don't
2388 // support modifying than those we do, and more could be added.
2389 RTCConfiguration modified_config = configuration_;
2390 modified_config.servers = configuration.servers;
2391 modified_config.type = configuration.type;
2392 modified_config.ice_candidate_pool_size =
2393 configuration.ice_candidate_pool_size;
2394 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052395 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 12:01:402396 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 20:28:302397 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252398 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302399 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2400 }
2401
Steve Anton038834f2017-07-14 22:59:592402 // Validate the modified configuration.
2403 RTCError validate_error = ValidateConfiguration(modified_config);
2404 if (!validate_error.ok()) {
2405 return SafeSetError(std::move(validate_error), error);
2406 }
2407
deadbeef293e9262017-01-11 20:28:302408 // Note that this isn't possible through chromium, since it's an unsigned
2409 // short in WebIDL.
2410 if (configuration.ice_candidate_pool_size < 0 ||
2411 configuration.ice_candidate_pool_size > UINT16_MAX) {
2412 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2413 }
2414
2415 // Parse ICE servers before hopping to network thread.
2416 cricket::ServerAddresses stun_servers;
2417 std::vector<cricket::RelayServerConfig> turn_servers;
2418 RTCErrorType parse_error =
2419 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2420 if (parse_error != RTCErrorType::NONE) {
2421 return SafeSetError(parse_error, error);
2422 }
2423
2424 // In theory this shouldn't fail.
2425 if (!network_thread()->Invoke<bool>(
2426 RTC_FROM_HERE,
2427 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2428 stun_servers, turn_servers, modified_config.type,
2429 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402430 modified_config.prune_turn_ports,
2431 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 10:09:252432 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302433 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2434 }
Honghai Zhang4cedf2b2016-08-31 15:18:112435
deadbeefd1a38b52016-12-10 21:15:332436 // As described in JSEP, calling setConfiguration with new ICE servers or
2437 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2438 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302439 if (modified_config.servers != configuration_.servers ||
2440 modified_config.type != configuration_.type ||
2441 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292442 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332443 }
skvladd1f5fda2017-02-04 00:54:052444
2445 if (modified_config.ice_check_min_interval !=
2446 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 22:50:292447 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:052448 }
2449
deadbeef293e9262017-01-11 20:28:302450 configuration_ = modified_config;
2451 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452452}
2453
henrike@webrtc.org28e20752013-07-10 00:45:362454bool PeerConnection::AddIceCandidate(
2455 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:172456 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:252457 if (IsClosed()) {
2458 return false;
2459 }
Steve Antond25da372017-11-06 22:50:292460
2461 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252462 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2463 << "without any remote session description.";
Steve Antond25da372017-11-06 22:50:292464 return false;
2465 }
2466
2467 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 10:09:252468 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 22:50:292469 return false;
2470 }
2471
2472 bool valid = false;
2473 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2474 if (!valid) {
2475 return false;
2476 }
2477
2478 // Add this candidate to the remote session description.
2479 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 10:09:252480 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 22:50:292481 return false;
2482 }
2483
2484 if (ready) {
2485 return UseCandidate(ice_candidate);
2486 } else {
Mirko Bonadei675513b2017-11-09 10:09:252487 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 22:50:292488 return true;
2489 }
henrike@webrtc.org28e20752013-07-10 00:45:362490}
2491
Honghai Zhang7fb69db2016-03-14 18:59:182492bool PeerConnection::RemoveIceCandidates(
2493 const std::vector<cricket::Candidate>& candidates) {
2494 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 22:50:292495 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252496 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2497 << "removed without any remote session description.";
Steve Antond25da372017-11-06 22:50:292498 return false;
2499 }
2500
2501 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:252502 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:292503 return false;
2504 }
2505
2506 size_t number_removed =
2507 mutable_remote_description()->RemoveCandidates(candidates);
2508 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:252509 RTC_LOG(LS_ERROR)
2510 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2511 << "Requested " << candidates.size() << " but only " << number_removed
2512 << " are removed.";
Steve Antond25da372017-11-06 22:50:292513 }
2514
2515 // Remove the candidates from the transport controller.
2516 std::string error;
2517 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2518 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:252519 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 22:50:292520 }
2521 return true;
Honghai Zhang7fb69db2016-03-14 18:59:182522}
2523
buildbot@webrtc.org1567b8c2014-05-08 19:54:162524void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:172525 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:162526 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:292527
Steve Anton75737c02017-11-06 18:37:172528 if (transport_controller()) {
2529 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:292530 }
2531
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:182532 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 20:28:302533 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 18:47:222534 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:182535 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-04 00:12:072536 uma_observer_->IncrementEnumCounter(
2537 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2538 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:372539 } else {
Guo-wei Shiehdfbe6792015-09-04 00:12:072540 uma_observer_->IncrementEnumCounter(
2541 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2542 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:182543 }
2544 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:162545}
2546
zstein4b979802017-06-02 21:37:372547RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 19:15:022548 if (!worker_thread()->IsCurrent()) {
2549 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 21:37:372550 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2551 }
2552
2553 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2554 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2555 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2556 if (has_min && *bitrate.min_bitrate_bps < 0) {
2557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2558 "min_bitrate_bps <= 0");
2559 }
2560 if (has_current) {
2561 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2563 "current_bitrate_bps < min_bitrate_bps");
2564 } else if (*bitrate.current_bitrate_bps < 0) {
2565 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2566 "curent_bitrate_bps < 0");
2567 }
2568 }
2569 if (has_max) {
2570 if (has_current &&
2571 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2572 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2573 "max_bitrate_bps < current_bitrate_bps");
2574 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2576 "max_bitrate_bps < min_bitrate_bps");
2577 } else if (*bitrate.max_bitrate_bps < 0) {
2578 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2579 "max_bitrate_bps < 0");
2580 }
2581 }
2582
2583 Call::Config::BitrateConfigMask mask;
2584 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2585 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2586 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2587
2588 RTC_DCHECK(call_.get());
2589 call_->SetBitrateConfigMask(mask);
2590
2591 return RTCError::OK();
2592}
2593
Alex Narest78609d52017-10-20 08:37:472594void PeerConnection::SetBitrateAllocationStrategy(
2595 std::unique_ptr<rtc::BitrateAllocationStrategy>
2596 bitrate_allocation_strategy) {
2597 rtc::Thread* worker_thread = factory_->worker_thread();
2598 if (!worker_thread->IsCurrent()) {
2599 rtc::BitrateAllocationStrategy* strategy_raw =
2600 bitrate_allocation_strategy.release();
2601 auto functor = [this, strategy_raw]() {
2602 call_->SetBitrateAllocationStrategy(
2603 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2604 };
2605 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2606 return;
2607 }
2608 RTC_DCHECK(call_.get());
2609 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2610}
2611
henrika5f6bf242017-11-01 10:06:562612void PeerConnection::SetAudioPlayout(bool playout) {
2613 if (!worker_thread()->IsCurrent()) {
2614 worker_thread()->Invoke<void>(
2615 RTC_FROM_HERE,
2616 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2617 return;
2618 }
2619 auto audio_state =
2620 factory_->channel_manager()->media_engine()->GetAudioState();
2621 audio_state->SetPlayout(playout);
2622}
2623
2624void PeerConnection::SetAudioRecording(bool recording) {
2625 if (!worker_thread()->IsCurrent()) {
2626 worker_thread()->Invoke<void>(
2627 RTC_FROM_HERE,
2628 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2629 return;
2630 }
2631 auto audio_state =
2632 factory_->channel_manager()->media_engine()->GetAudioState();
2633 audio_state->SetRecording(recording);
2634}
2635
Steve Anton8c0f7a72017-10-03 17:03:102636std::unique_ptr<rtc::SSLCertificate>
2637PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 18:37:172638 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 17:03:102639 return nullptr;
2640 }
Steve Anton75737c02017-11-06 18:37:172641 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 17:03:102642}
2643
ivoc14d5dbe2016-07-04 14:06:552644bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2645 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:402646 // TODO(eladalon): It would be better to not allow negative values into PC.
2647 const size_t max_size = (max_size_bytes < 0)
2648 ? RtcEventLog::kUnlimitedOutput
2649 : rtc::saturated_cast<size_t>(max_size_bytes);
2650 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 16:38:142651 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2652 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:402653}
2654
Bjorn Tereliusde939432017-11-20 16:38:142655bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2656 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:062657 // TODO(eladalon): In C++14, this can be done with a lambda.
2658 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:142659 bool operator()() {
2660 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2661 }
Karl Wibergd6b48192017-10-16 21:01:062662 PeerConnection* const pc;
2663 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:142664 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:402665 };
Bjorn Tereliusde939432017-11-20 16:38:142666 return worker_thread()->Invoke<bool>(
2667 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:552668}
2669
2670void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:022671 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:552672 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2673}
2674
henrike@webrtc.org28e20752013-07-10 00:45:362675const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:172676 return pending_local_description_ ? pending_local_description_.get()
2677 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:362678}
2679
2680const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:172681 return pending_remote_description_ ? pending_remote_description_.get()
2682 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:362683}
2684
deadbeeffe4a8a42016-12-21 01:56:172685const SessionDescriptionInterface* PeerConnection::current_local_description()
2686 const {
Steve Anton75737c02017-11-06 18:37:172687 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:172688}
2689
2690const SessionDescriptionInterface* PeerConnection::current_remote_description()
2691 const {
Steve Anton75737c02017-11-06 18:37:172692 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:172693}
2694
2695const SessionDescriptionInterface* PeerConnection::pending_local_description()
2696 const {
Steve Anton75737c02017-11-06 18:37:172697 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:172698}
2699
2700const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2701 const {
Steve Anton75737c02017-11-06 18:37:172702 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:172703}
2704
henrike@webrtc.org28e20752013-07-10 00:45:362705void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:172706 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:362707 // Update stats here so that we have the most recent stats for tracks and
2708 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:262709 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:362710
Steve Anton75737c02017-11-06 18:37:172711 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 18:20:082712
Steve Anton8af21862017-12-15 19:20:132713 for (auto transceiver : transceivers_) {
2714 transceiver->Stop();
2715 }
2716 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:172717
deadbeef42a42632017-03-10 23:18:002718 network_thread()->Invoke<void>(
2719 RTC_FROM_HERE,
2720 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2721 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:022722
Steve Anton978b8762017-09-29 19:15:022723 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:152724 call_.reset();
2725 // The event log must outlive call (and any other object that uses it).
2726 event_log_.reset();
2727 });
henrike@webrtc.org28e20752013-07-10 00:45:362728}
2729
buildbot@webrtc.orgd4e598d2014-07-29 17:36:522730void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:362731 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:362732 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2733 SetSessionDescriptionMsg* param =
2734 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2735 param->observer->OnSuccess();
2736 delete param;
2737 break;
2738 }
2739 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2740 SetSessionDescriptionMsg* param =
2741 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2742 param->observer->OnFailure(param->error);
2743 delete param;
2744 break;
2745 }
deadbeefab9b2d12015-10-14 18:33:112746 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2747 CreateSessionDescriptionMsg* param =
2748 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2749 param->observer->OnFailure(param->error);
2750 delete param;
2751 break;
2752 }
henrike@webrtc.org28e20752013-07-10 00:45:362753 case MSG_GETSTATS: {
2754 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 13:00:342755 StatsReports reports;
2756 stats_->GetStats(param->track, &reports);
2757 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:362758 delete param;
2759 break;
2760 }
deadbeefbd292462015-12-15 02:15:292761 case MSG_FREE_DATACHANNELS: {
2762 sctp_data_channels_to_free_.clear();
2763 break;
2764 }
henrike@webrtc.org28e20752013-07-10 00:45:362765 default:
nisseeb4ca4e2017-01-12 10:24:272766 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:362767 break;
2768 }
2769}
2770
Steve Anton4171afb2017-11-20 18:20:222771void PeerConnection::CreateAudioReceiver(
2772 MediaStreamInterface* stream,
2773 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:512774 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2775 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 20:06:242776 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2777 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-26 02:15:092778 signaling_thread(),
Steve Anton60776752018-01-10 19:51:342779 new AudioRtpReceiver(worker_thread(), remote_sender_info.sender_id,
2780 streams, remote_sender_info.first_ssrc,
2781 voice_media_channel()));
Steve Anton4171afb2017-11-20 18:20:222782 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:512783 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:362784}
2785
Steve Anton4171afb2017-11-20 18:20:222786void PeerConnection::CreateVideoReceiver(
2787 MediaStreamInterface* stream,
2788 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:512789 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2790 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 20:06:242791 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2792 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 18:20:222793 signaling_thread(),
Steve Anton60776752018-01-10 19:51:342794 new VideoRtpReceiver(worker_thread(), remote_sender_info.sender_id,
2795 streams, remote_sender_info.first_ssrc,
2796 video_media_channel()));
Steve Anton4171afb2017-11-20 18:20:222797 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:512798 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:362799}
2800
deadbeef70ab1a12015-09-28 23:53:552801// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2802// description.
Henrik Boström933d8b02017-10-10 17:05:162803rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:222804 const RtpSenderInfo& remote_sender_info) {
2805 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2806 if (!receiver) {
2807 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2808 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:162809 return nullptr;
deadbeef70ab1a12015-09-28 23:53:552810 }
Steve Anton4171afb2017-11-20 18:20:222811 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2812 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2813 } else {
2814 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2815 }
Henrik Boström933d8b02017-10-10 17:05:162816 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:362817}
2818
korniltsev.anatolyec390b52017-07-25 00:00:252819void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2820 MediaStreamInterface* stream) {
2821 RTC_DCHECK(!IsClosed());
2822 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:222823 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:252824 // We already have a sender for this track, so just change the stream_id
2825 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 18:20:222826 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-25 00:00:252827 return;
2828 }
2829
2830 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:062831 auto new_sender =
2832 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2833 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 18:49:352834 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:222835 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:252836 // If the sender has already been configured in SDP, we call SetSsrc,
2837 // which will connect the sender to the underlying transport. This can
2838 // occur if a local session description that contains the ID of the sender
2839 // is set before AddStream is called. It can also occur if the local
2840 // session description is not changed and RemoveStream is called, and
2841 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:222842 const RtpSenderInfo* sender_info =
2843 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2844 if (sender_info) {
2845 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:252846 }
2847}
2848
2849// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2850// indefinitely, when we have unified plan SDP.
2851void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2852 MediaStreamInterface* stream) {
2853 RTC_DCHECK(!IsClosed());
2854 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:222855 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:252856 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2857 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:252858 return;
2859 }
Steve Anton4171afb2017-11-20 18:20:222860 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:252861}
2862
2863void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2864 MediaStreamInterface* stream) {
2865 RTC_DCHECK(!IsClosed());
2866 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:222867 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:252868 // We already have a sender for this track, so just change the stream_id
2869 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 18:20:222870 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-25 00:00:252871 return;
2872 }
2873
2874 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:062875 auto new_sender =
2876 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2877 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 18:49:352878 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:222879 GetVideoTransceiver()->internal()->AddSender(new_sender);
2880 const RtpSenderInfo* sender_info =
2881 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2882 if (sender_info) {
2883 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:252884 }
2885}
2886
2887void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2888 MediaStreamInterface* stream) {
2889 RTC_DCHECK(!IsClosed());
2890 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:222891 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:252892 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2893 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:252894 return;
2895 }
Steve Anton4171afb2017-11-20 18:20:222896 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:252897}
2898
Steve Antonba818672017-11-06 18:21:572899void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:282900 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:572901 if (ice_connection_state_ == new_state) {
2902 return;
2903 }
2904
deadbeefcbecd352015-09-23 18:50:272905 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:572906 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:112907 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:272908 return;
2909 }
Steve Antonba818672017-11-06 18:21:572910
Mirko Bonadei675513b2017-11-09 10:09:252911 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2912 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:572913 RTC_DCHECK(ice_connection_state_ !=
2914 PeerConnectionInterface::kIceConnectionClosed);
2915
henrike@webrtc.org28e20752013-07-10 00:45:362916 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:522917 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:362918}
2919
2920void PeerConnection::OnIceGatheringChange(
2921 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:282922 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:362923 if (IsClosed()) {
2924 return;
2925 }
2926 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:522927 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:362928}
2929
jbauch81bf7b02017-03-25 15:31:122930void PeerConnection::OnIceCandidate(
2931 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:282932 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:252933 if (IsClosed()) {
2934 return;
2935 }
jbauch81bf7b02017-03-25 15:31:122936 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:362937}
2938
Honghai Zhang7fb69db2016-03-14 18:59:182939void PeerConnection::OnIceCandidatesRemoved(
2940 const std::vector<cricket::Candidate>& candidates) {
2941 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:252942 if (IsClosed()) {
2943 return;
2944 }
Honghai Zhang7fb69db2016-03-14 18:59:182945 observer_->OnIceCandidatesRemoved(candidates);
2946}
2947
henrike@webrtc.org28e20752013-07-10 00:45:362948void PeerConnection::ChangeSignalingState(
2949 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:572950 RTC_DCHECK(signaling_thread()->IsCurrent());
2951 if (signaling_state_ == signaling_state) {
2952 return;
2953 }
Mirko Bonadei675513b2017-11-09 10:09:252954 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2955 << GetSignalingStateString(signaling_state_)
2956 << " New state: "
2957 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:362958 signaling_state_ = signaling_state;
2959 if (signaling_state == kClosed) {
2960 ice_connection_state_ = kIceConnectionClosed;
2961 observer_->OnIceConnectionChange(ice_connection_state_);
2962 if (ice_gathering_state_ != kIceGatheringComplete) {
2963 ice_gathering_state_ = kIceGatheringComplete;
2964 observer_->OnIceGatheringChange(ice_gathering_state_);
2965 }
2966 }
2967 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:362968}
2969
deadbeefeb459812015-12-16 03:24:432970void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2971 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:252972 if (IsClosed()) {
2973 return;
2974 }
korniltsev.anatolyec390b52017-07-25 00:00:252975 AddAudioTrack(track, stream);
2976 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:432977}
2978
deadbeefeb459812015-12-16 03:24:432979void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2980 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:252981 if (IsClosed()) {
2982 return;
2983 }
korniltsev.anatolyec390b52017-07-25 00:00:252984 RemoveAudioTrack(track, stream);
2985 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:432986}
2987
2988void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2989 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:252990 if (IsClosed()) {
2991 return;
2992 }
korniltsev.anatolyec390b52017-07-25 00:00:252993 AddVideoTrack(track, stream);
2994 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:432995}
2996
2997void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2998 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:252999 if (IsClosed()) {
3000 return;
3001 }
korniltsev.anatolyec390b52017-07-25 00:00:253002 RemoveVideoTrack(track, stream);
3003 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433004}
3005
Henrik Boström31638672017-11-23 16:48:323006void PeerConnection::PostSetSessionDescriptionSuccess(
3007 SetSessionDescriptionObserver* observer) {
3008 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3009 signaling_thread()->Post(RTC_FROM_HERE, this,
3010 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3011}
3012
deadbeefab9b2d12015-10-14 18:33:113013void PeerConnection::PostSetSessionDescriptionFailure(
3014 SetSessionDescriptionObserver* observer,
3015 const std::string& error) {
3016 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3017 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 21:17:273018 signaling_thread()->Post(RTC_FROM_HERE, this,
3019 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113020}
3021
3022void PeerConnection::PostCreateSessionDescriptionFailure(
3023 CreateSessionDescriptionObserver* observer,
3024 const std::string& error) {
3025 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3026 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 21:17:273027 signaling_thread()->Post(RTC_FROM_HERE, this,
3028 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113029}
3030
zhihuang1c378ed2017-08-17 21:10:503031void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543032 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113033 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543034 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503035
Steve Antondcc3c022017-12-23 00:02:543036 if (IsUnifiedPlan()) {
3037 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3038 } else {
3039 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3040 }
3041
Steve Antonfa2260d2017-12-29 00:38:233042 // Intentionally unset the data channel type for RTP data channel with the
3043 // second condition. Otherwise the RTP data channels would be successfully
3044 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3045 // when building with chromium. We want to leave RTP data channels broken, so
3046 // people won't try to use them.
3047 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3048 session_options->data_channel_type = data_channel_type();
3049 }
3050
Steve Antondcc3c022017-12-23 00:02:543051 // Apply ICE restart flag and renomination flag.
3052 for (auto& options : session_options->media_description_options) {
3053 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3054 options.transport_options.enable_ice_renomination =
3055 configuration_.enable_ice_renomination;
3056 }
3057
3058 session_options->rtcp_cname = rtcp_cname_;
3059 session_options->crypto_options = factory_->options().crypto_options;
3060}
3061
3062void PeerConnection::GetOptionsForPlanBOffer(
3063 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3064 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503065 // Figure out transceiver directional preferences.
3066 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3067 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3068
3069 // By default, generate sendrecv/recvonly m= sections.
3070 bool recv_audio = true;
3071 bool recv_video = true;
3072
3073 // By default, only offer a new m= section if we have media to send with it.
3074 bool offer_new_audio_description = send_audio;
3075 bool offer_new_video_description = send_video;
3076 bool offer_new_data_description = HasDataChannels();
3077
3078 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543079 if (offer_answer_options.offer_to_receive_audio !=
3080 RTCOfferAnswerOptions::kUndefined) {
3081 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503082 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543083 offer_new_audio_description ||
3084 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503085 }
Steve Antondcc3c022017-12-23 00:02:543086 if (offer_answer_options.offer_to_receive_video !=
3087 RTCOfferAnswerOptions::kUndefined) {
3088 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503089 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543090 offer_new_video_description ||
3091 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503092 }
3093
3094 rtc::Optional<size_t> audio_index;
3095 rtc::Optional<size_t> video_index;
3096 rtc::Optional<size_t> data_index;
3097 // If a current description exists, generate m= sections in the same order,
3098 // using the first audio/video/data section that appears and rejecting
3099 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173100 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503101 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173102 local_description(),
Steve Anton1d03a752017-11-27 22:30:093103 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3104 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3105 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113106 }
3107
zhihuang1c378ed2017-08-17 21:10:503108 // Add audio/video/data m= sections to the end if needed.
3109 if (!audio_index && offer_new_audio_description) {
3110 session_options->media_description_options.push_back(
3111 cricket::MediaDescriptionOptions(
3112 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093113 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3114 false));
Oskar Sundbom9b28a032017-11-16 09:53:303115 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453116 }
zhihuang1c378ed2017-08-17 21:10:503117 if (!video_index && offer_new_video_description) {
3118 session_options->media_description_options.push_back(
3119 cricket::MediaDescriptionOptions(
3120 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093121 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3122 false));
Oskar Sundbom9b28a032017-11-16 09:53:303123 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453124 }
zhihuang1c378ed2017-08-17 21:10:503125 if (!data_index && offer_new_data_description) {
3126 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233127 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303128 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503129 }
3130
3131 cricket::MediaDescriptionOptions* audio_media_description_options =
3132 !audio_index ? nullptr
3133 : &session_options->media_description_options[*audio_index];
3134 cricket::MediaDescriptionOptions* video_media_description_options =
3135 !video_index ? nullptr
3136 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503137
Steve Anton4171afb2017-11-20 18:20:223138 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503139 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543140}
3141
3142// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3143// and return a reference to it.
3144// Generated MIDs should be no more than 3 bytes long to take up less space in
3145// the RTP packet.
3146static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3147 RTC_DCHECK(used_mids);
3148 // We're boring: just generate MIDs 0, 1, 2, ...
3149 size_t i = 0;
3150 std::set<std::string>::iterator it;
3151 bool inserted;
3152 do {
3153 std::string mid = rtc::ToString(i++);
3154 auto insert_result = used_mids->insert(mid);
3155 it = insert_result.first;
3156 inserted = insert_result.second;
3157 } while (!inserted);
3158 return *it;
3159}
3160
3161static cricket::MediaDescriptionOptions
3162GetMediaDescriptionOptionsForTransceiver(
3163 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3164 transceiver,
3165 const std::string& mid) {
3166 cricket::MediaDescriptionOptions media_description_options(
3167 transceiver->internal()->media_type(), mid, transceiver->direction(),
3168 transceiver->stopped());
3169 cricket::SenderOptions sender_options;
3170 sender_options.track_id = transceiver->sender()->id();
3171 sender_options.stream_ids = transceiver->sender()->stream_ids();
3172 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3173 // set in the RTP parameters when the transceiver was added.
3174 sender_options.num_sim_layers = 1;
3175 media_description_options.sender_options.push_back(sender_options);
3176 return media_description_options;
3177}
3178
3179void PeerConnection::GetOptionsForUnifiedPlanOffer(
3180 const RTCOfferAnswerOptions& offer_answer_options,
3181 cricket::MediaSessionOptions* session_options) {
3182 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3183 // Offers) and 5.2.2 (Subsequent Offers).
3184 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3185 const ContentInfos& local_contents =
3186 (local_description() ? local_description()->description()->contents()
3187 : ContentInfos());
3188 const ContentInfos& remote_contents =
3189 (remote_description() ? remote_description()->description()->contents()
3190 : ContentInfos());
3191 // The mline indices that can be recycled. New transceivers should reuse these
3192 // slots first.
3193 std::queue<size_t> recycleable_mline_indices;
3194 // Track the MIDs used in previous offer/answer exchanges and the current
3195 // offer so that new, unique MIDs are generated.
3196 std::set<std::string> used_mids = seen_mids_;
3197 // First, go through each media section that exists in either the local or
3198 // remote description and generate a media section in this offer for the
3199 // associated transceiver. If a media section can be recycled, generate a
3200 // default, rejected media section here that can be later overwritten.
3201 for (size_t i = 0;
3202 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3203 // Either |local_content| or |remote_content| is non-null.
3204 const ContentInfo* local_content =
3205 (i < local_contents.size() ? &local_contents[i] : nullptr);
3206 const ContentInfo* remote_content =
3207 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3208 bool had_been_rejected = (local_content && local_content->rejected) ||
3209 (remote_content && remote_content->rejected);
3210 const std::string& mid =
3211 (local_content ? local_content->name : remote_content->name);
3212 cricket::MediaType media_type =
3213 (local_content ? local_content->media_description()->type()
3214 : remote_content->media_description()->type());
3215 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3216 media_type == cricket::MEDIA_TYPE_VIDEO) {
3217 auto transceiver = GetAssociatedTransceiver(mid);
3218 RTC_CHECK(transceiver);
3219 // A media section is considered eligible for recycling if it is marked as
3220 // rejected in either the local or remote description.
3221 if (had_been_rejected) {
3222 session_options->media_description_options.push_back(
3223 cricket::MediaDescriptionOptions(
3224 transceiver->internal()->media_type(), mid,
3225 RtpTransceiverDirection::kInactive,
3226 /*stopped=*/true));
3227 recycleable_mline_indices.push(i);
3228 } else {
3229 session_options->media_description_options.push_back(
3230 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3231 // CreateOffer shouldn't really cause any state changes in
3232 // PeerConnection, but we need a way to match new transceivers to new
3233 // media sections in SetLocalDescription and JSEP specifies this is done
3234 // by recording the index of the media section generated for the
3235 // transceiver in the offer.
3236 transceiver->internal()->set_mline_index(i);
3237 }
3238 } else {
3239 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233240 RTC_CHECK(GetDataMid());
3241 if (had_been_rejected || mid != *GetDataMid()) {
3242 session_options->media_description_options.push_back(
3243 GetMediaDescriptionOptionsForRejectedData(mid));
3244 } else {
3245 session_options->media_description_options.push_back(
3246 GetMediaDescriptionOptionsForActiveData(mid));
3247 }
Steve Antondcc3c022017-12-23 00:02:543248 }
3249 }
3250 // Next, look for transceivers that are newly added (that is, are not stopped
3251 // and not associated). Reuse media sections marked as recyclable first,
3252 // otherwise append to the end of the offer. New media sections should be
3253 // added in the order they were added to the PeerConnection.
3254 for (auto transceiver : transceivers_) {
3255 if (transceiver->mid() || transceiver->stopped()) {
3256 continue;
3257 }
3258 size_t mline_index;
3259 if (!recycleable_mline_indices.empty()) {
3260 mline_index = recycleable_mline_indices.front();
3261 recycleable_mline_indices.pop();
3262 session_options->media_description_options[mline_index] =
3263 GetMediaDescriptionOptionsForTransceiver(transceiver,
3264 AllocateMid(&used_mids));
3265 } else {
3266 mline_index = session_options->media_description_options.size();
3267 session_options->media_description_options.push_back(
3268 GetMediaDescriptionOptionsForTransceiver(transceiver,
3269 AllocateMid(&used_mids)));
3270 }
3271 // See comment above for why CreateOffer changes the transceiver's state.
3272 transceiver->internal()->set_mline_index(mline_index);
3273 }
Steve Antonfa2260d2017-12-29 00:38:233274 // Lastly, add a m-section if we have local data channels and an m section
3275 // does not already exist.
3276 if (!GetDataMid() && HasDataChannels()) {
3277 session_options->media_description_options.push_back(
3278 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3279 }
Steve Antondcc3c022017-12-23 00:02:543280}
3281
3282void PeerConnection::GetOptionsForAnswer(
3283 const RTCOfferAnswerOptions& offer_answer_options,
3284 cricket::MediaSessionOptions* session_options) {
3285 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3286
3287 if (IsUnifiedPlan()) {
3288 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3289 } else {
3290 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3291 }
3292
Steve Antonfa2260d2017-12-29 00:38:233293 // Intentionally unset the data channel type for RTP data channel. Otherwise
3294 // the RTP data channels would be successfully negotiated by default and the
3295 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3296 // We want to leave RTP data channels broken, so people won't try to use them.
3297 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3298 session_options->data_channel_type = data_channel_type();
3299 }
3300
Steve Antondcc3c022017-12-23 00:02:543301 // Apply ICE renomination flag.
3302 for (auto& options : session_options->media_description_options) {
3303 options.transport_options.enable_ice_renomination =
3304 configuration_.enable_ice_renomination;
3305 }
zhihuang8f65cdf2016-05-07 01:40:303306
3307 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323308 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 18:33:113309}
3310
Steve Antondcc3c022017-12-23 00:02:543311void PeerConnection::GetOptionsForPlanBAnswer(
3312 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113313 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503314 // Figure out transceiver directional preferences.
3315 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3316 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3317
3318 // By default, generate sendrecv/recvonly m= sections. The direction is also
3319 // restricted by the direction in the offer.
3320 bool recv_audio = true;
3321 bool recv_video = true;
3322
3323 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543324 if (offer_answer_options.offer_to_receive_audio !=
3325 RTCOfferAnswerOptions::kUndefined) {
3326 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523327 }
Steve Antondcc3c022017-12-23 00:02:543328 if (offer_answer_options.offer_to_receive_video !=
3329 RTCOfferAnswerOptions::kUndefined) {
3330 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503331 }
3332
3333 rtc::Optional<size_t> audio_index;
3334 rtc::Optional<size_t> video_index;
3335 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 18:37:173336 if (remote_description()) {
zhihuang141aacb2017-08-29 20:23:533337 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 18:27:413338 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 20:23:533339 // Generate m= sections that match those in the offer.
3340 // Note that mediasession.cc will handle intersection our preferred
3341 // direction with the offered direction.
3342 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173343 remote_description(),
Steve Anton1d03a752017-11-27 22:30:093344 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3345 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3346 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 20:23:533347 }
zhihuang1c378ed2017-08-17 21:10:503348
3349 cricket::MediaDescriptionOptions* audio_media_description_options =
3350 !audio_index ? nullptr
3351 : &session_options->media_description_options[*audio_index];
3352 cricket::MediaDescriptionOptions* video_media_description_options =
3353 !video_index ? nullptr
3354 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503355
Steve Anton4171afb2017-11-20 18:20:223356 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503357 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543358}
zhihuangaf388472016-11-02 23:49:483359
Steve Antondcc3c022017-12-23 00:02:543360void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3361 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3362 cricket::MediaSessionOptions* session_options) {
3363 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3364 // Answers) and 5.3.2 (Subsequent Answers).
3365 RTC_DCHECK(remote_description());
3366 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3367 for (const ContentInfo& content :
3368 remote_description()->description()->contents()) {
3369 cricket::MediaType media_type = content.media_description()->type();
3370 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3371 media_type == cricket::MEDIA_TYPE_VIDEO) {
3372 auto transceiver = GetAssociatedTransceiver(content.name);
3373 RTC_CHECK(transceiver);
3374 session_options->media_description_options.push_back(
3375 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3376 } else {
3377 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233378 RTC_CHECK(GetDataMid());
3379 // Always reject a data section if it has already been rejected.
3380 // Additionally, reject all data sections except for the first one.
3381 if (content.rejected || content.name != *GetDataMid()) {
3382 session_options->media_description_options.push_back(
3383 GetMediaDescriptionOptionsForRejectedData(content.name));
3384 } else {
3385 session_options->media_description_options.push_back(
3386 GetMediaDescriptionOptionsForActiveData(content.name));
3387 }
Steve Antondcc3c022017-12-23 00:02:543388 }
3389 }
htaa2a49d92016-03-04 10:51:393390}
3391
zhihuang1c378ed2017-08-17 21:10:503392void PeerConnection::GenerateMediaDescriptionOptions(
3393 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:093394 RtpTransceiverDirection audio_direction,
3395 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 21:10:503396 rtc::Optional<size_t>* audio_index,
3397 rtc::Optional<size_t>* video_index,
3398 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:393399 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503400 for (const cricket::ContentInfo& content :
3401 session_desc->description()->contents()) {
3402 if (IsAudioContent(&content)) {
3403 // If we already have an audio m= section, reject this extra one.
3404 if (*audio_index) {
3405 session_options->media_description_options.push_back(
3406 cricket::MediaDescriptionOptions(
3407 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:093408 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503409 } else {
3410 session_options->media_description_options.push_back(
3411 cricket::MediaDescriptionOptions(
3412 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:093413 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303414 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503415 }
3416 } else if (IsVideoContent(&content)) {
3417 // If we already have an video m= section, reject this extra one.
3418 if (*video_index) {
3419 session_options->media_description_options.push_back(
3420 cricket::MediaDescriptionOptions(
3421 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:093422 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503423 } else {
3424 session_options->media_description_options.push_back(
3425 cricket::MediaDescriptionOptions(
3426 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:093427 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303428 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503429 }
3430 } else {
3431 RTC_DCHECK(IsDataContent(&content));
3432 // If we already have an data m= section, reject this extra one.
3433 if (*data_index) {
3434 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233435 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:503436 } else {
3437 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233438 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:303439 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503440 }
3441 }
htaa2a49d92016-03-04 10:51:393442 }
deadbeefab9b2d12015-10-14 18:33:113443}
3444
Steve Antonfa2260d2017-12-29 00:38:233445cricket::MediaDescriptionOptions
3446PeerConnection::GetMediaDescriptionOptionsForActiveData(
3447 const std::string& mid) const {
3448 // Direction for data sections is meaningless, but legacy endpoints might
3449 // expect sendrecv.
3450 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3451 RtpTransceiverDirection::kSendRecv,
3452 /*stopped=*/false);
3453 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3454 return options;
3455}
3456
3457cricket::MediaDescriptionOptions
3458PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3459 const std::string& mid) const {
3460 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3461 RtpTransceiverDirection::kInactive,
3462 /*stopped=*/true);
3463 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3464 return options;
3465}
3466
3467rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3468 switch (data_channel_type_) {
3469 case cricket::DCT_RTP:
3470 if (!rtp_data_channel_) {
3471 return rtc::nullopt;
3472 }
3473 return rtp_data_channel_->content_name();
3474 case cricket::DCT_SCTP:
3475 return sctp_content_name_;
3476 default:
3477 return rtc::nullopt;
3478 }
3479}
3480
Steve Anton4171afb2017-11-20 18:20:223481void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3482 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3483 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:403484 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:073485}
3486
Steve Anton4171afb2017-11-20 18:20:223487void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:113488 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:223489 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:113490 cricket::MediaType media_type,
3491 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 18:20:223492 std::vector<RtpSenderInfo>* current_senders =
3493 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:113494
Steve Anton4171afb2017-11-20 18:20:223495 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:013496 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:223497 for (auto sender_it = current_senders->begin();
3498 sender_it != current_senders->end();
3499 /* incremented manually */) {
3500 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:113501 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:223502 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3503 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-09 01:13:403504 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 18:20:223505 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3506 sender_exists) {
3507 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:403508 } else {
Steve Anton4171afb2017-11-20 18:20:223509 OnRemoteSenderRemoved(info, media_type);
3510 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:113511 }
3512 }
3513
Steve Anton4171afb2017-11-20 18:20:223514 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:113515 for (const cricket::StreamParams& params : streams) {
3516 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:223517 // sender id.
deadbeefab9b2d12015-10-14 18:33:113518 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 18:20:223519 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:113520 uint32_t ssrc = params.first_ssrc();
3521
3522 rtc::scoped_refptr<MediaStreamInterface> stream =
3523 remote_streams_->find(stream_label);
3524 if (!stream) {
3525 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:193526 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3527 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 18:33:113528 remote_streams_->AddStream(stream);
3529 new_streams->AddStream(stream);
3530 }
3531
Steve Anton4171afb2017-11-20 18:20:223532 const RtpSenderInfo* sender_info =
3533 FindSenderInfo(*current_senders, stream_label, sender_id);
3534 if (!sender_info) {
3535 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3536 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:113537 }
3538 }
deadbeefbda7e0b2015-12-09 01:13:403539
Steve Anton4171afb2017-11-20 18:20:223540 // Add default sender if necessary.
3541 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:403542 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3543 remote_streams_->find(kDefaultStreamLabel);
3544 if (!default_stream) {
3545 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:193546 default_stream = MediaStreamProxy::Create(
3547 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-09 01:13:403548 remote_streams_->AddStream(default_stream);
3549 new_streams->AddStream(default_stream);
3550 }
Steve Anton4171afb2017-11-20 18:20:223551 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3552 ? kDefaultAudioSenderId
3553 : kDefaultVideoSenderId;
3554 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3555 *current_senders, kDefaultStreamLabel, default_sender_id);
3556 if (!default_sender_info) {
3557 current_senders->push_back(
3558 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3559 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:403560 }
3561 }
deadbeefab9b2d12015-10-14 18:33:113562}
3563
Steve Anton4171afb2017-11-20 18:20:223564void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3565 cricket::MediaType media_type) {
3566 MediaStreamInterface* stream =
3567 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 18:33:113568
3569 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:223570 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:113571 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:223572 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:113573 } else {
nisseeb4ca4e2017-01-12 10:24:273574 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:113575 }
3576}
3577
Steve Anton4171afb2017-11-20 18:20:223578void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3579 cricket::MediaType media_type) {
3580 MediaStreamInterface* stream =
3581 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 18:33:113582
Henrik Boström933d8b02017-10-10 17:05:163583 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:113584 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:193585 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3586 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:223587 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:113588 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:223589 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:113590 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:113591 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:113592 }
3593 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:193594 // Stopping or destroying a VideoRtpReceiver will end the
3595 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:223596 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:113597 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:223598 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:113599 if (video_track) {
perkjd61bf802016-03-24 10:16:193600 // There's no guarantee the track is still available, e.g. the track may
3601 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:113602 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:113603 }
3604 } else {
nisseede5da42017-01-12 13:15:363605 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:113606 }
Henrik Boström933d8b02017-10-10 17:05:163607 if (receiver) {
3608 observer_->OnRemoveTrack(receiver);
3609 }
deadbeefab9b2d12015-10-14 18:33:113610}
3611
3612void PeerConnection::UpdateEndedRemoteMediaStreams() {
3613 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3614 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3615 MediaStreamInterface* stream = remote_streams_->at(i);
3616 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3617 streams_to_remove.push_back(stream);
3618 }
3619 }
3620
Taylor Brandstetter98cde262016-05-31 20:02:213621 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:113622 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 20:02:213623 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:113624 }
3625}
3626
Steve Anton4171afb2017-11-20 18:20:223627void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:113628 const std::vector<cricket::StreamParams>& streams,
3629 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:223630 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:113631
3632 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3633 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:223634 for (auto sender_it = current_senders->begin();
3635 sender_it != current_senders->end();
3636 /* incremented manually */) {
3637 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:113638 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:223639 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3640 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 18:33:113641 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 18:20:223642 OnLocalSenderRemoved(info, media_type);
3643 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:113644 } else {
Steve Anton4171afb2017-11-20 18:20:223645 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:113646 }
3647 }
3648
Steve Anton4171afb2017-11-20 18:20:223649 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:113650 for (const cricket::StreamParams& params : streams) {
3651 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:223652 // sender id.
deadbeefab9b2d12015-10-14 18:33:113653 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 18:20:223654 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:113655 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:223656 const RtpSenderInfo* sender_info =
3657 FindSenderInfo(*current_senders, stream_label, sender_id);
3658 if (!sender_info) {
3659 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3660 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:113661 }
3662 }
3663}
3664
Steve Anton4171afb2017-11-20 18:20:223665void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3666 cricket::MediaType media_type) {
3667 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:013668 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:223669 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3670 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:253671 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:113672 return;
3673 }
3674
deadbeeffac06552015-11-25 19:26:013675 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:253676 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3677 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:013678 return;
deadbeefab9b2d12015-10-14 18:33:113679 }
deadbeeffac06552015-11-25 19:26:013680
Steve Anton4171afb2017-11-20 18:20:223681 sender->internal()->set_stream_id(sender_info.stream_label);
3682 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:113683}
3684
Steve Anton4171afb2017-11-20 18:20:223685void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3686 cricket::MediaType media_type) {
3687 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:013688 if (!sender) {
3689 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:113690 // SessionDescriptions has been renegotiated.
3691 return;
3692 }
deadbeeffac06552015-11-25 19:26:013693
3694 // A sender has been removed from the SessionDescription but it's still
3695 // associated with the PeerConnection. This only occurs if the SDP doesn't
3696 // match with the calls to CreateSender, AddStream and RemoveStream.
3697 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:253698 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3699 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:013700 return;
deadbeefab9b2d12015-10-14 18:33:113701 }
deadbeeffac06552015-11-25 19:26:013702
Steve Anton4171afb2017-11-20 18:20:223703 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:113704}
3705
3706void PeerConnection::UpdateLocalRtpDataChannels(
3707 const cricket::StreamParamsVec& streams) {
3708 std::vector<std::string> existing_channels;
3709
3710 // Find new and active data channels.
3711 for (const cricket::StreamParams& params : streams) {
3712 // |it->sync_label| is actually the data channel label. The reason is that
3713 // we use the same naming of data channels as we do for
3714 // MediaStreams and Tracks.
3715 // For MediaStreams, the sync_label is the MediaStream label and the
3716 // track label is the same as |streamid|.
3717 const std::string& channel_label = params.sync_label;
3718 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:563719 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:253720 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:113721 continue;
3722 }
3723 // Set the SSRC the data channel should use for sending.
3724 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3725 existing_channels.push_back(data_channel_it->first);
3726 }
3727
3728 UpdateClosingRtpDataChannels(existing_channels, true);
3729}
3730
3731void PeerConnection::UpdateRemoteRtpDataChannels(
3732 const cricket::StreamParamsVec& streams) {
3733 std::vector<std::string> existing_channels;
3734
3735 // Find new and active data channels.
3736 for (const cricket::StreamParams& params : streams) {
3737 // The data channel label is either the mslabel or the SSRC if the mslabel
3738 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3739 std::string label = params.sync_label.empty()
3740 ? rtc::ToString(params.first_ssrc())
3741 : params.sync_label;
3742 auto data_channel_it = rtp_data_channels_.find(label);
3743 if (data_channel_it == rtp_data_channels_.end()) {
3744 // This is a new data channel.
3745 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3746 } else {
3747 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3748 }
3749 existing_channels.push_back(label);
3750 }
3751
3752 UpdateClosingRtpDataChannels(existing_channels, false);
3753}
3754
3755void PeerConnection::UpdateClosingRtpDataChannels(
3756 const std::vector<std::string>& active_channels,
3757 bool is_local_update) {
3758 auto it = rtp_data_channels_.begin();
3759 while (it != rtp_data_channels_.end()) {
3760 DataChannel* data_channel = it->second;
3761 if (std::find(active_channels.begin(), active_channels.end(),
3762 data_channel->label()) != active_channels.end()) {
3763 ++it;
3764 continue;
3765 }
3766
3767 if (is_local_update) {
3768 data_channel->SetSendSsrc(0);
3769 } else {
3770 data_channel->RemotePeerRequestClose();
3771 }
3772
3773 if (data_channel->state() == DataChannel::kClosed) {
3774 rtp_data_channels_.erase(it);
3775 it = rtp_data_channels_.begin();
3776 } else {
3777 ++it;
3778 }
3779 }
3780}
3781
3782void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3783 uint32_t remote_ssrc) {
3784 rtc::scoped_refptr<DataChannel> channel(
3785 InternalCreateDataChannel(label, nullptr));
3786 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:253787 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3788 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:113789 return;
3790 }
3791 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:393792 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3793 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:213794 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:113795}
3796
3797rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3798 const std::string& label,
3799 const InternalDataChannelInit* config) {
3800 if (IsClosed()) {
3801 return nullptr;
3802 }
Steve Anton75737c02017-11-06 18:37:173803 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:253804 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:113805 << "InternalCreateDataChannel: Data is not supported in this call.";
3806 return nullptr;
3807 }
3808 InternalDataChannelInit new_config =
3809 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:173810 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:113811 if (new_config.id < 0) {
3812 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:173813 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:113814 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:253815 RTC_LOG(LS_ERROR)
3816 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:113817 return nullptr;
3818 }
3819 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:253820 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3821 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:113822 return nullptr;
3823 }
3824 }
3825
Steve Anton75737c02017-11-06 18:37:173826 rtc::scoped_refptr<DataChannel> channel(
3827 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:113828 if (!channel) {
3829 sid_allocator_.ReleaseSid(new_config.id);
3830 return nullptr;
3831 }
3832
3833 if (channel->data_channel_type() == cricket::DCT_RTP) {
3834 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:253835 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3836 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:113837 return nullptr;
3838 }
3839 rtp_data_channels_[channel->label()] = channel;
3840 } else {
3841 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3842 sctp_data_channels_.push_back(channel);
3843 channel->SignalClosed.connect(this,
3844 &PeerConnection::OnSctpDataChannelClosed);
3845 }
3846
hbos82ebe022016-11-14 09:41:093847 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 18:33:113848 return channel;
3849}
3850
3851bool PeerConnection::HasDataChannels() const {
3852 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3853}
3854
3855void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3856 for (const auto& channel : sctp_data_channels_) {
3857 if (channel->id() < 0) {
3858 int sid;
3859 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:253860 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:113861 continue;
3862 }
3863 channel->SetSctpSid(sid);
3864 }
3865 }
3866}
3867
3868void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:293869 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:113870 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3871 ++it) {
3872 if (it->get() == channel) {
3873 if (channel->id() >= 0) {
3874 sid_allocator_.ReleaseSid(channel->id());
3875 }
deadbeefbd292462015-12-15 02:15:293876 // Since this method is triggered by a signal from the DataChannel,
3877 // we can't free it directly here; we need to free it asynchronously.
3878 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:113879 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273880 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3881 nullptr);
deadbeefab9b2d12015-10-14 18:33:113882 return;
3883 }
3884 }
3885}
3886
deadbeefab9b2d12015-10-14 18:33:113887void PeerConnection::OnDataChannelDestroyed() {
3888 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3889 // DataChannel may callback to us and try to modify the list.
3890 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3891 temp_rtp_dcs.swap(rtp_data_channels_);
3892 for (const auto& kv : temp_rtp_dcs) {
3893 kv.second->OnTransportChannelDestroyed();
3894 }
3895
3896 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3897 temp_sctp_dcs.swap(sctp_data_channels_);
3898 for (const auto& channel : temp_sctp_dcs) {
3899 channel->OnTransportChannelDestroyed();
3900 }
3901}
3902
3903void PeerConnection::OnDataChannelOpenMessage(
3904 const std::string& label,
3905 const InternalDataChannelInit& config) {
3906 rtc::scoped_refptr<DataChannel> channel(
3907 InternalCreateDataChannel(label, &config));
3908 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:253909 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:113910 return;
3911 }
3912
deadbeefa601f5c2016-06-06 21:27:393913 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3914 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:213915 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:113916}
3917
Steve Anton4171afb2017-11-20 18:20:223918rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3919PeerConnection::GetAudioTransceiver() const {
3920 // This method only works with Plan B SDP, where there is a single
3921 // audio/video transceiver.
3922 RTC_DCHECK(!IsUnifiedPlan());
3923 for (auto transceiver : transceivers_) {
3924 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3925 return transceiver;
3926 }
3927 }
3928 RTC_NOTREACHED();
3929 return nullptr;
3930}
3931
3932rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3933PeerConnection::GetVideoTransceiver() const {
3934 // This method only works with Plan B SDP, where there is a single
3935 // audio/video transceiver.
3936 RTC_DCHECK(!IsUnifiedPlan());
3937 for (auto transceiver : transceivers_) {
3938 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3939 return transceiver;
3940 }
3941 }
3942 RTC_NOTREACHED();
3943 return nullptr;
3944}
3945
3946// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3947// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:503948bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:223949 switch (type) {
3950 case cricket::MEDIA_TYPE_AUDIO:
3951 return !GetAudioTransceiver()->internal()->senders().empty();
3952 case cricket::MEDIA_TYPE_VIDEO:
3953 return !GetVideoTransceiver()->internal()->senders().empty();
3954 case cricket::MEDIA_TYPE_DATA:
3955 return false;
3956 }
3957 RTC_NOTREACHED();
3958 return false;
zhihuang1c378ed2017-08-17 21:10:503959}
3960
Steve Anton4171afb2017-11-20 18:20:223961rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3962PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3963 for (auto transceiver : transceivers_) {
3964 for (auto sender : transceiver->internal()->senders()) {
3965 if (sender->track() == track) {
3966 return sender;
3967 }
3968 }
3969 }
3970 return nullptr;
deadbeeffac06552015-11-25 19:26:013971}
3972
Steve Anton4171afb2017-11-20 18:20:223973rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3974PeerConnection::FindSenderById(const std::string& sender_id) const {
3975 for (auto transceiver : transceivers_) {
3976 for (auto sender : transceiver->internal()->senders()) {
3977 if (sender->id() == sender_id) {
3978 return sender;
3979 }
3980 }
3981 }
3982 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553983}
3984
Steve Anton4171afb2017-11-20 18:20:223985rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3986PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3987 for (auto transceiver : transceivers_) {
3988 for (auto receiver : transceiver->internal()->receivers()) {
3989 if (receiver->id() == receiver_id) {
3990 return receiver;
3991 }
3992 }
3993 }
3994 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553995}
3996
Steve Anton4171afb2017-11-20 18:20:223997std::vector<PeerConnection::RtpSenderInfo>*
3998PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3999 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4000 media_type == cricket::MEDIA_TYPE_VIDEO);
4001 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4002 ? &remote_audio_sender_infos_
4003 : &remote_video_sender_infos_;
4004}
4005
4006std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114007 cricket::MediaType media_type) {
4008 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4009 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224010 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4011 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114012}
4013
Steve Anton4171afb2017-11-20 18:20:224014const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4015 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 18:33:114016 const std::string& stream_label,
Steve Anton4171afb2017-11-20 18:20:224017 const std::string sender_id) const {
4018 for (const RtpSenderInfo& sender_info : infos) {
4019 if (sender_info.stream_label == stream_label &&
4020 sender_info.sender_id == sender_id) {
4021 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114022 }
4023 }
4024 return nullptr;
4025}
4026
4027DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4028 for (const auto& channel : sctp_data_channels_) {
4029 if (channel->id() == sid) {
4030 return channel;
4031 }
4032 }
4033 return nullptr;
4034}
4035
deadbeef91dd5672016-05-18 23:55:304036bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 15:15:114037 const RTCConfiguration& configuration) {
4038 cricket::ServerAddresses stun_servers;
4039 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 20:28:304040 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4041 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 15:15:114042 return false;
4043 }
4044
Taylor Brandstetterf8e65772016-06-28 00:20:154045 port_allocator_->Initialize();
4046
Taylor Brandstettera1c30352016-05-13 15:15:114047 // To handle both internal and externally created port allocator, we will
4048 // enable BUNDLE here.
4049 int portallocator_flags = port_allocator_->flags();
4050 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 22:40:514051 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4052 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114053 // If the disable-IPv6 flag was specified, we'll not override it
4054 // by experiment.
4055 if (configuration.disable_ipv6) {
4056 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474057 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4058 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 15:15:114059 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4060 }
4061
zhihuangb09b3f92017-03-07 22:40:514062 if (configuration.disable_ipv6_on_wifi) {
4063 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254064 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514065 }
4066
Taylor Brandstettera1c30352016-05-13 15:15:114067 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4068 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254069 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114070 }
4071
honghaiz60347052016-06-01 01:29:124072 if (configuration.candidate_network_policy ==
4073 kCandidateNetworkPolicyLowCost) {
4074 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254075 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124076 }
4077
Taylor Brandstettera1c30352016-05-13 15:15:114078 port_allocator_->set_flags(portallocator_flags);
4079 // No step delay is used while allocating ports.
4080 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4081 port_allocator_->set_candidate_filter(
4082 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114083 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114084
4085 // Call this last since it may create pooled allocator sessions using the
4086 // properties set above.
4087 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-07-01 03:52:024088 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404089 configuration.prune_turn_ports,
4090 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 15:15:114091 return true;
4092}
4093
deadbeef91dd5672016-05-18 23:55:304094bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304095 const cricket::ServerAddresses& stun_servers,
4096 const std::vector<cricket::RelayServerConfig>& turn_servers,
4097 IceTransportsType type,
4098 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404099 bool prune_turn_ports,
4100 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 15:15:114101 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304102 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 15:15:114103 // Call this last since it may create pooled allocator sessions using the
4104 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324105 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 12:01:404106 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4107 turn_customizer);
Taylor Brandstettera1c30352016-05-13 15:15:114108}
4109
Steve Antonba818672017-11-06 18:21:574110cricket::ChannelManager* PeerConnection::channel_manager() const {
4111 return factory_->channel_manager();
4112}
4113
4114MetricsObserverInterface* PeerConnection::metrics_observer() const {
4115 return uma_observer_;
4116}
4117
Elad Alon99c3fe52017-10-13 14:29:404118bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144119 std::unique_ptr<RtcEventLogOutput> output,
4120 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164121 if (!event_log_) {
4122 return false;
4123 }
Bjorn Tereliusde939432017-11-20 16:38:144124 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554125}
4126
4127void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164128 if (event_log_) {
4129 event_log_->StopLogging();
4130 }
ivoc14d5dbe2016-07-04 14:06:554131}
nisseeaabdf62017-05-05 09:23:024132
Steve Anton75737c02017-11-06 18:37:174133cricket::BaseChannel* PeerConnection::GetChannel(
4134 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544135 for (auto transceiver : transceivers_) {
4136 cricket::BaseChannel* channel = transceiver->internal()->channel();
4137 if (channel && channel->content_name() == content_name) {
4138 return channel;
4139 }
Steve Anton75737c02017-11-06 18:37:174140 }
4141 if (rtp_data_channel() &&
4142 rtp_data_channel()->content_name() == content_name) {
4143 return rtp_data_channel();
4144 }
4145 return nullptr;
4146}
4147
4148bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4149 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254150 RTC_LOG(LS_INFO)
4151 << "Local and Remote descriptions must be applied to get the "
4152 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174153 return false;
4154 }
4155 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254156 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4157 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174158 return false;
4159 }
4160
4161 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4162}
4163
4164bool PeerConnection::GetSslRole(const std::string& content_name,
4165 rtc::SSLRole* role) {
4166 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254167 RTC_LOG(LS_INFO)
4168 << "Local and Remote descriptions must be applied to get the "
4169 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174170 return false;
4171 }
4172
4173 return transport_controller_->GetSslRole(GetTransportName(content_name),
4174 role);
4175}
4176
Steve Anton75737c02017-11-06 18:37:174177// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4178// vector of BaseChannel pointers instead of separate voice and video channel
4179// vectors. At that point, this will become a simple getter.
4180std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4181 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 18:20:224182 if (voice_channel()) {
4183 channels.push_back(voice_channel());
4184 }
4185 if (video_channel()) {
4186 channels.push_back(video_channel());
4187 }
Steve Anton75737c02017-11-06 18:37:174188 if (rtp_data_channel_) {
4189 channels.push_back(rtp_data_channel_);
4190 }
4191 return channels;
4192}
4193
Steve Antonf8470812017-12-04 18:46:214194void PeerConnection::SetSessionError(SessionError error,
4195 const std::string& error_desc) {
4196 RTC_DCHECK_RUN_ON(signaling_thread());
4197 if (error != session_error_) {
4198 session_error_ = error;
4199 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174200 }
4201}
4202
Steve Anton3828c062017-12-06 18:34:514203RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 23:25:564204 cricket::ContentSource source) {
4205 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174206
4207 // If there's already a pending error then no state transition should happen.
4208 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214209 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474210
4211 // If this is an answer then we know whether to BUNDLE or not. If both the
4212 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 18:34:514213 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 18:37:174214 const cricket::ContentGroup* local_bundle =
4215 local_description()->description()->GetGroupByName(
4216 cricket::GROUP_TYPE_BUNDLE);
4217 const cricket::ContentGroup* remote_bundle =
4218 remote_description()->description()->GetGroupByName(
4219 cricket::GROUP_TYPE_BUNDLE);
4220 if (local_bundle && remote_bundle) {
4221 // The answerer decides the transport to bundle on.
4222 const cricket::ContentGroup* answer_bundle =
4223 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4224 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 23:25:564225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4226 kEnableBundleFailed);
Steve Anton75737c02017-11-06 18:37:174227 }
4228 }
Steve Anton75737c02017-11-06 18:37:174229 }
Steve Anton6d6a2ae2017-12-05 01:19:474230
4231 // Only push down the transport description after potentially enabling BUNDLE;
4232 // we don't want to push down a description on a transport about to be
4233 // destroyed.
Steve Anton3828c062017-12-06 18:34:514234 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-05 01:19:474235 if (!error.ok()) {
4236 return error;
4237 }
4238
4239 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514240 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594241 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474242 }
4243
4244 // Update the signaling state according to the specified state machine (see
4245 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514246 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474247 ChangeSignalingState(source == cricket::CS_LOCAL
4248 ? PeerConnectionInterface::kHaveLocalOffer
4249 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514250 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474251 ChangeSignalingState(source == cricket::CS_LOCAL
4252 ? PeerConnectionInterface::kHaveLocalPrAnswer
4253 : PeerConnectionInterface::kHaveRemotePrAnswer);
4254 } else {
Steve Anton3828c062017-12-06 18:34:514255 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474256 ChangeSignalingState(PeerConnectionInterface::kStable);
4257 }
4258
4259 // Update internal objects according to the session description's media
4260 // descriptions.
Steve Anton3828c062017-12-06 18:34:514261 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474262 if (!error.ok()) {
4263 SetSessionError(SessionError::kContent, error.message());
4264 }
4265 if (session_error() != SessionError::kNone) {
4266 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4267 }
4268
Steve Anton8a006912017-12-04 23:25:564269 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174270}
4271
Steve Anton8a006912017-12-04 23:25:564272RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514273 SdpType type,
Steve Anton8a006912017-12-04 23:25:564274 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594275 const SessionDescriptionInterface* sdesc =
4276 (source == cricket::CS_LOCAL ? local_description()
4277 : remote_description());
Steve Anton75737c02017-11-06 18:37:174278 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594279
4280 // Push down the new SDP media section for each audio/video transceiver.
4281 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174282 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594283 FindMediaSectionForTransceiver(transceiver, sdesc);
4284 cricket::BaseChannel* channel = transceiver->internal()->channel();
4285 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174286 continue;
4287 }
4288 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304289 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594290 if (!content_desc) {
4291 continue;
4292 }
4293 std::string error;
4294 bool success =
4295 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514296 ? channel->SetLocalContent(content_desc, type, &error)
4297 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594298 if (!success) {
4299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4300 }
4301 }
4302
4303 // If using the RtpDataChannel, push down the new SDP section for it too.
4304 if (rtp_data_channel_) {
4305 const ContentInfo* data_content =
4306 cricket::GetFirstDataContent(sdesc->description());
4307 if (data_content && !data_content->rejected) {
4308 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304309 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594310 if (data_desc) {
4311 std::string error;
4312 bool success =
4313 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514314 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4315 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 18:52:594316 &error);
4317 if (!success) {
4318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4319 std::move(error));
4320 }
Steve Anton75737c02017-11-06 18:37:174321 }
4322 }
4323 }
Steve Antoned10bd92017-12-05 18:52:594324
Steve Anton75737c02017-11-06 18:37:174325 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4326 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4327 if (sctp_transport_ && local_description() && remote_description() &&
4328 cricket::GetFirstDataContent(local_description()->description()) &&
4329 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564330 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174331 RTC_FROM_HERE,
4332 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564333 if (!success) {
4334 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4335 "Failed to push down SCTP parameters.");
4336 }
Steve Anton75737c02017-11-06 18:37:174337 }
Steve Antoned10bd92017-12-05 18:52:594338
Steve Anton8a006912017-12-04 23:25:564339 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174340}
4341
4342bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4343 RTC_DCHECK(network_thread()->IsCurrent());
4344 RTC_DCHECK(local_description());
4345 RTC_DCHECK(remote_description());
4346 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4347 // When we support "max-message-size", that would also be pushed down here.
4348 return sctp_transport_->Start(
4349 GetSctpPort(local_description()->description()),
4350 GetSctpPort(remote_description()->description()));
4351}
4352
Steve Anton8a006912017-12-04 23:25:564353RTCError PeerConnection::PushdownTransportDescription(
4354 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514355 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564356 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174357
Steve Anton8a006912017-12-04 23:25:564358 const SessionDescriptionInterface* sdesc =
4359 (source == cricket::CS_LOCAL ? local_description()
4360 : remote_description());
4361 RTC_DCHECK(sdesc);
4362 for (const cricket::TransportInfo& tinfo :
4363 sdesc->description()->transport_infos()) {
4364 std::string error;
4365 bool success;
4366 if (source == cricket::CS_LOCAL) {
4367 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 18:34:514368 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 23:25:564369 } else {
4370 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 18:34:514371 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 23:25:564372 }
4373 if (!success) {
Steve Antondcc3c022017-12-23 00:02:544374 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4375 "Failed to push down transport description for " +
4376 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 18:37:174377 }
4378 }
4379
Steve Anton8a006912017-12-04 23:25:564380 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174381}
4382
4383bool PeerConnection::GetTransportDescription(
4384 const SessionDescription* description,
4385 const std::string& content_name,
4386 cricket::TransportDescription* tdesc) {
4387 if (!description || !tdesc) {
4388 return false;
4389 }
4390 const TransportInfo* transport_info =
4391 description->GetTransportInfoByName(content_name);
4392 if (!transport_info) {
4393 return false;
4394 }
4395 *tdesc = transport_info->description;
4396 return true;
4397}
4398
4399bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4400 const std::string* first_content_name = bundle.FirstContentName();
4401 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 10:09:254402 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 18:37:174403 return false;
4404 }
4405 const std::string& transport_name = *first_content_name;
4406
4407 auto maybe_set_transport = [this, bundle,
4408 transport_name](cricket::BaseChannel* ch) {
4409 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 18:52:594410 return;
Steve Anton75737c02017-11-06 18:37:174411 }
4412
4413 std::string old_transport_name = ch->transport_name();
4414 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 10:09:254415 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4416 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 18:52:594417 return;
Steve Anton75737c02017-11-06 18:37:174418 }
4419
4420 cricket::DtlsTransportInternal* rtp_dtls_transport =
4421 transport_controller_->CreateDtlsTransport(
4422 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4423 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4424 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4425 if (need_rtcp) {
4426 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4428 }
4429
4430 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 10:09:254431 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4432 << transport_name << ".";
Steve Anton75737c02017-11-06 18:37:174433 transport_controller_->DestroyDtlsTransport(
4434 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4435 // If the channel needs rtcp, it means that the channel used to have a
4436 // rtcp transport which needs to be deleted now.
4437 if (need_rtcp) {
4438 transport_controller_->DestroyDtlsTransport(
4439 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4440 }
Steve Anton75737c02017-11-06 18:37:174441 };
4442
Steve Antoned10bd92017-12-05 18:52:594443 for (auto transceiver : transceivers_) {
4444 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 18:37:174445 }
Steve Antoned10bd92017-12-05 18:52:594446 maybe_set_transport(rtp_data_channel_);
4447
Steve Anton75737c02017-11-06 18:37:174448 // For SCTP, transport creation/deletion happens here instead of in the
4449 // object itself.
4450 if (sctp_transport_) {
4451 RTC_DCHECK(sctp_transport_name_);
4452 RTC_DCHECK(sctp_content_name_);
4453 if (transport_name != *sctp_transport_name_ &&
4454 bundle.HasContentName(*sctp_content_name_)) {
4455 network_thread()->Invoke<void>(
4456 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4457 transport_name));
4458 }
4459 }
4460
4461 return true;
4462}
4463
Steve Anton75737c02017-11-06 18:37:174464cricket::IceConfig PeerConnection::ParseIceConfig(
4465 const PeerConnectionInterface::RTCConfiguration& config) const {
4466 cricket::ContinualGatheringPolicy gathering_policy;
4467 // TODO(honghaiz): Add the third continual gathering policy in
4468 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4469 switch (config.continual_gathering_policy) {
4470 case PeerConnectionInterface::GATHER_ONCE:
4471 gathering_policy = cricket::GATHER_ONCE;
4472 break;
4473 case PeerConnectionInterface::GATHER_CONTINUALLY:
4474 gathering_policy = cricket::GATHER_CONTINUALLY;
4475 break;
4476 default:
4477 RTC_NOTREACHED();
4478 gathering_policy = cricket::GATHER_ONCE;
4479 }
4480 cricket::IceConfig ice_config;
4481 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4482 ice_config.prioritize_most_likely_candidate_pairs =
4483 config.prioritize_most_likely_ice_candidate_pairs;
4484 ice_config.backup_connection_ping_interval =
4485 config.ice_backup_candidate_pair_ping_interval;
4486 ice_config.continual_gathering_policy = gathering_policy;
4487 ice_config.presume_writable_when_fully_relayed =
4488 config.presume_writable_when_fully_relayed;
4489 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4490 ice_config.regather_all_networks_interval_range =
4491 config.ice_regather_interval_range;
4492 return ice_config;
4493}
4494
Steve Anton75737c02017-11-06 18:37:174495bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4496 std::string* track_id) {
4497 if (!local_description()) {
4498 return false;
4499 }
4500 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4501 track_id);
4502}
4503
4504bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4505 std::string* track_id) {
4506 if (!remote_description()) {
4507 return false;
4508 }
4509 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4510 track_id);
4511}
4512
4513bool PeerConnection::SendData(const cricket::SendDataParams& params,
4514 const rtc::CopyOnWriteBuffer& payload,
4515 cricket::SendDataResult* result) {
4516 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254517 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4518 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:174519 return false;
4520 }
4521 return rtp_data_channel_
4522 ? rtp_data_channel_->SendData(params, payload, result)
4523 : network_thread()->Invoke<bool>(
4524 RTC_FROM_HERE,
4525 Bind(&cricket::SctpTransportInternal::SendData,
4526 sctp_transport_.get(), params, payload, result));
4527}
4528
4529bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4530 if (!rtp_data_channel_ && !sctp_transport_) {
4531 // Don't log an error here, because DataChannels are expected to call
4532 // ConnectDataChannel in this state. It's the only way to initially tell
4533 // whether or not the underlying transport is ready.
4534 return false;
4535 }
4536 if (rtp_data_channel_) {
4537 rtp_data_channel_->SignalReadyToSendData.connect(
4538 webrtc_data_channel, &DataChannel::OnChannelReady);
4539 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4540 &DataChannel::OnDataReceived);
4541 } else {
4542 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4543 &DataChannel::OnChannelReady);
4544 SignalSctpDataReceived.connect(webrtc_data_channel,
4545 &DataChannel::OnDataReceived);
4546 SignalSctpStreamClosedRemotely.connect(
4547 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4548 }
4549 return true;
4550}
4551
4552void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4553 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254554 RTC_LOG(LS_ERROR)
4555 << "DisconnectDataChannel called when rtp_data_channel_ and "
4556 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:174557 return;
4558 }
4559 if (rtp_data_channel_) {
4560 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4561 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4562 } else {
4563 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4564 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4565 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4566 }
4567}
4568
4569void PeerConnection::AddSctpDataStream(int sid) {
4570 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254571 RTC_LOG(LS_ERROR)
4572 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:174573 return;
4574 }
4575 network_thread()->Invoke<void>(
4576 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4577 sctp_transport_.get(), sid));
4578}
4579
4580void PeerConnection::RemoveSctpDataStream(int sid) {
4581 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254582 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4583 << "NULL.";
Steve Anton75737c02017-11-06 18:37:174584 return;
4585 }
4586 network_thread()->Invoke<void>(
4587 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4588 sctp_transport_.get(), sid));
4589}
4590
4591bool PeerConnection::ReadyToSendData() const {
4592 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4593 sctp_ready_to_send_data_;
4594}
4595
4596std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4597 RTC_DCHECK(signaling_thread()->IsCurrent());
4598 ChannelNamePairs channel_name_pairs;
4599 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 09:53:304600 channel_name_pairs.voice = ChannelNamePair(
4601 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 18:37:174602 }
4603 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 09:53:304604 channel_name_pairs.video = ChannelNamePair(
4605 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 18:37:174606 }
4607 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 09:53:304608 channel_name_pairs.data =
Steve Anton75737c02017-11-06 18:37:174609 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 09:53:304610 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 18:37:174611 }
4612 if (sctp_transport_) {
4613 RTC_DCHECK(sctp_content_name_);
4614 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 09:53:304615 channel_name_pairs.data =
4616 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 18:37:174617 }
4618 return GetSessionStats(channel_name_pairs);
4619}
4620
4621std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4622 const ChannelNamePairs& channel_name_pairs) {
4623 if (network_thread()->IsCurrent()) {
4624 return GetSessionStats_n(channel_name_pairs);
4625 }
4626 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4627 RTC_FROM_HERE,
4628 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4629}
4630
4631bool PeerConnection::GetLocalCertificate(
4632 const std::string& transport_name,
4633 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4634 return transport_controller_->GetLocalCertificate(transport_name,
4635 certificate);
4636}
4637
4638std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4639 const std::string& transport_name) {
4640 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4641}
4642
4643cricket::DataChannelType PeerConnection::data_channel_type() const {
4644 return data_channel_type_;
4645}
4646
4647bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4648 return pending_ice_restarts_.find(content_name) !=
4649 pending_ice_restarts_.end();
4650}
4651
Steve Anton75737c02017-11-06 18:37:174652bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4653 return transport_controller_->NeedsIceRestart(content_name);
4654}
4655
4656void PeerConnection::OnCertificateReady(
4657 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4658 transport_controller_->SetLocalCertificate(certificate);
4659}
4660
4661void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:214662 SetSessionError(SessionError::kTransport,
4663 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:174664}
4665
4666void PeerConnection::OnTransportControllerConnectionState(
4667 cricket::IceConnectionState state) {
4668 switch (state) {
4669 case cricket::kIceConnectionConnecting:
4670 // If the current state is Connected or Completed, then there were
4671 // writable channels but now there are not, so the next state must
4672 // be Disconnected.
4673 // kIceConnectionConnecting is currently used as the default,
4674 // un-connected state by the TransportController, so its only use is
4675 // detecting disconnections.
4676 if (ice_connection_state_ ==
4677 PeerConnectionInterface::kIceConnectionConnected ||
4678 ice_connection_state_ ==
4679 PeerConnectionInterface::kIceConnectionCompleted) {
4680 SetIceConnectionState(
4681 PeerConnectionInterface::kIceConnectionDisconnected);
4682 }
4683 break;
4684 case cricket::kIceConnectionFailed:
4685 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4686 break;
4687 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:254688 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4689 << "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:174690 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4691 break;
4692 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:254693 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4694 << "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:174695 if (ice_connection_state_ !=
4696 PeerConnectionInterface::kIceConnectionConnected) {
4697 // If jumping directly from "checking" to "connected",
4698 // signal "connected" first.
4699 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4700 }
4701 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4702 if (metrics_observer()) {
4703 ReportTransportStats();
4704 }
4705 break;
4706 default:
4707 RTC_NOTREACHED();
4708 }
4709}
4710
4711void PeerConnection::OnTransportControllerCandidatesGathered(
4712 const std::string& transport_name,
4713 const cricket::Candidates& candidates) {
4714 RTC_DCHECK(signaling_thread()->IsCurrent());
4715 int sdp_mline_index;
4716 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:254717 RTC_LOG(LS_ERROR)
4718 << "OnTransportControllerCandidatesGathered: content name "
4719 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:174720 return;
4721 }
4722
4723 for (cricket::Candidates::const_iterator citer = candidates.begin();
4724 citer != candidates.end(); ++citer) {
4725 // Use transport_name as the candidate media id.
4726 std::unique_ptr<JsepIceCandidate> candidate(
4727 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4728 if (local_description()) {
4729 mutable_local_description()->AddCandidate(candidate.get());
4730 }
4731 OnIceCandidate(std::move(candidate));
4732 }
4733}
4734
4735void PeerConnection::OnTransportControllerCandidatesRemoved(
4736 const std::vector<cricket::Candidate>& candidates) {
4737 RTC_DCHECK(signaling_thread()->IsCurrent());
4738 // Sanity check.
4739 for (const cricket::Candidate& candidate : candidates) {
4740 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:254741 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4742 << "empty content name in candidate "
4743 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:174744 return;
4745 }
4746 }
4747
4748 if (local_description()) {
4749 mutable_local_description()->RemoveCandidates(candidates);
4750 }
4751 OnIceCandidatesRemoved(candidates);
4752}
4753
4754void PeerConnection::OnTransportControllerDtlsHandshakeError(
4755 rtc::SSLHandshakeError error) {
4756 if (metrics_observer()) {
4757 metrics_observer()->IncrementEnumCounter(
4758 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4759 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4760 }
4761}
4762
Steve Antoned10bd92017-12-05 18:52:594763void PeerConnection::EnableSending() {
4764 for (auto transceiver : transceivers_) {
4765 cricket::BaseChannel* channel = transceiver->internal()->channel();
4766 if (channel && !channel->enabled()) {
4767 channel->Enable(true);
4768 }
Steve Anton75737c02017-11-06 18:37:174769 }
4770
Steve Anton4171afb2017-11-20 18:20:224771 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:174772 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:224773 }
Steve Anton75737c02017-11-06 18:37:174774}
4775
4776// Returns the media index for a local ice candidate given the content name.
4777bool PeerConnection::GetLocalCandidateMediaIndex(
4778 const std::string& content_name,
4779 int* sdp_mline_index) {
4780 if (!local_description() || !sdp_mline_index) {
4781 return false;
4782 }
4783
4784 bool content_found = false;
4785 const ContentInfos& contents = local_description()->description()->contents();
4786 for (size_t index = 0; index < contents.size(); ++index) {
4787 if (contents[index].name == content_name) {
4788 *sdp_mline_index = static_cast<int>(index);
4789 content_found = true;
4790 break;
4791 }
4792 }
4793 return content_found;
4794}
4795
4796bool PeerConnection::UseCandidatesInSessionDescription(
4797 const SessionDescriptionInterface* remote_desc) {
4798 if (!remote_desc) {
4799 return true;
4800 }
4801 bool ret = true;
4802
4803 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4804 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4805 for (size_t n = 0; n < candidates->count(); ++n) {
4806 const IceCandidateInterface* candidate = candidates->at(n);
4807 bool valid = false;
4808 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4809 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:254810 RTC_LOG(LS_INFO)
4811 << "UseCandidatesInSessionDescription: Not ready to use "
4812 << "candidate.";
Steve Anton75737c02017-11-06 18:37:174813 }
4814 continue;
4815 }
4816 ret = UseCandidate(candidate);
4817 if (!ret) {
4818 break;
4819 }
4820 }
4821 }
4822 return ret;
4823}
4824
4825bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4826 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4827 size_t remote_content_size =
4828 remote_description()->description()->contents().size();
4829 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:254830 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:174831 return false;
4832 }
4833
4834 cricket::ContentInfo content =
4835 remote_description()->description()->contents()[mediacontent_index];
4836 std::vector<cricket::Candidate> candidates;
4837 candidates.push_back(candidate->candidate());
4838 // Invoking BaseSession method to handle remote candidates.
4839 std::string error;
4840 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4841 &error)) {
4842 // Candidates successfully submitted for checking.
4843 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4844 ice_connection_state_ ==
4845 PeerConnectionInterface::kIceConnectionDisconnected) {
4846 // If state is New, then the session has just gotten its first remote ICE
4847 // candidates, so go to Checking.
4848 // If state is Disconnected, the session is re-using old candidates or
4849 // receiving additional ones, so go to Checking.
4850 // If state is Connected, stay Connected.
4851 // TODO(bemasc): If state is Connected, and the new candidates are for a
4852 // newly added transport, then the state actually _should_ move to
4853 // checking. Add a way to distinguish that case.
4854 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4855 }
4856 // TODO(bemasc): If state is Completed, go back to Connected.
4857 } else {
4858 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:254859 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 18:37:174860 }
4861 }
4862 return true;
4863}
4864
4865void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:174866 // Destroy video channel first since it may have a pointer to the
4867 // voice channel.
4868 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:294869 if (!video_info || video_info->rejected) {
4870 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:174871 }
4872
Steve Anton6fec8802017-12-04 18:37:294873 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4874 if (!audio_info || audio_info->rejected) {
4875 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:174876 }
4877
4878 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4879 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:294880 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:174881 }
4882}
4883
Steve Antoneda6ccd2017-12-04 18:21:554884std::string PeerConnection::GetTransportNameForMediaSection(
4885 const std::string& mid,
4886 const cricket::ContentGroup* bundle_group) const {
4887 if (!bundle_group) {
4888 return mid;
Steve Anton75737c02017-11-06 18:37:174889 }
Steve Antoneda6ccd2017-12-04 18:21:554890 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 18:37:174891 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 10:09:254892 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 18:21:554893 return mid;
Steve Anton75737c02017-11-06 18:37:174894 }
Steve Antoneda6ccd2017-12-04 18:21:554895 if (!bundle_group->HasContentName(mid)) {
4896 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4897 return mid;
Steve Anton75737c02017-11-06 18:37:174898 }
Steve Antoneda6ccd2017-12-04 18:21:554899 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4900 return *first_content_name;
Steve Anton75737c02017-11-06 18:37:174901}
4902
Steve Antondcc3c022017-12-23 00:02:544903RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4904 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:174905 const cricket::ContentGroup* bundle_group = nullptr;
4906 if (configuration_.bundle_policy ==
4907 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:544908 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:174909 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:564910 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4911 "max-bundle configured but session description "
4912 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:174913 }
4914 }
Steve Antondcc3c022017-12-23 00:02:544915 return std::move(bundle_group);
4916}
4917
4918RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4919 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4920 if (!bundle_group_or_error.ok()) {
4921 return bundle_group_or_error.MoveError();
4922 }
4923 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 18:37:174924
Steve Antoneda6ccd2017-12-04 18:21:554925 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-23 00:02:544926 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:554927 if (voice && !voice->rejected &&
4928 !GetAudioTransceiver()->internal()->channel()) {
4929 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4930 voice->name,
4931 GetTransportNameForMediaSection(voice->name, bundle_group));
4932 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:564933 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4934 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:554935 }
4936 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4937 }
4938
Steve Antondcc3c022017-12-23 00:02:544939 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:554940 if (video && !video->rejected &&
4941 !GetVideoTransceiver()->internal()->channel()) {
4942 cricket::VideoChannel* video_channel = CreateVideoChannel(
4943 video->name,
4944 GetTransportNameForMediaSection(video->name, bundle_group));
4945 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:564946 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4947 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:174948 }
Steve Antoneda6ccd2017-12-04 18:21:554949 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:174950 }
4951
Steve Antondcc3c022017-12-23 00:02:544952 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:174953 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4954 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 18:21:554955 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4956 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 23:25:564957 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4958 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:174959 }
4960 }
4961
Steve Anton8a006912017-12-04 23:25:564962 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174963}
4964
Steve Anton4171afb2017-11-20 18:20:224965// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:554966cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4967 const std::string& mid,
4968 const std::string& transport_name) {
Steve Anton75737c02017-11-06 18:37:174969 cricket::DtlsTransportInternal* rtp_dtls_transport =
4970 transport_controller_->CreateDtlsTransport(
4971 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4972 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4973 if (configuration_.rtcp_mux_policy !=
4974 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4975 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4976 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4977 }
4978
4979 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4980 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 18:21:554981 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4982 audio_options_);
Steve Anton75737c02017-11-06 18:37:174983 if (!voice_channel) {
4984 transport_controller_->DestroyDtlsTransport(
4985 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4986 if (rtcp_dtls_transport) {
4987 transport_controller_->DestroyDtlsTransport(
4988 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4989 }
Steve Antoneda6ccd2017-12-04 18:21:554990 return nullptr;
Steve Anton75737c02017-11-06 18:37:174991 }
Steve Anton75737c02017-11-06 18:37:174992 voice_channel->SignalRtcpMuxFullyActive.connect(
4993 this, &PeerConnection::DestroyRtcpTransport_n);
4994 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4995 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:174996 voice_channel->SignalSentPacket.connect(this,
4997 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 18:20:224998
Steve Antoneda6ccd2017-12-04 18:21:554999 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175000}
5001
Steve Anton4171afb2017-11-20 18:20:225002// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555003cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5004 const std::string& mid,
5005 const std::string& transport_name) {
Steve Anton75737c02017-11-06 18:37:175006 cricket::DtlsTransportInternal* rtp_dtls_transport =
5007 transport_controller_->CreateDtlsTransport(
5008 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5009 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5010 if (configuration_.rtcp_mux_policy !=
5011 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5012 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5013 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5014 }
5015
5016 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5017 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 18:21:555018 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5019 video_options_);
Steve Anton75737c02017-11-06 18:37:175020
5021 if (!video_channel) {
5022 transport_controller_->DestroyDtlsTransport(
5023 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5024 if (rtcp_dtls_transport) {
5025 transport_controller_->DestroyDtlsTransport(
5026 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5027 }
Steve Antoneda6ccd2017-12-04 18:21:555028 return nullptr;
Steve Anton75737c02017-11-06 18:37:175029 }
Steve Anton75737c02017-11-06 18:37:175030 video_channel->SignalRtcpMuxFullyActive.connect(
5031 this, &PeerConnection::DestroyRtcpTransport_n);
5032 video_channel->SignalDtlsSrtpSetupFailure.connect(
5033 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175034 video_channel->SignalSentPacket.connect(this,
5035 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 18:20:225036
Steve Antoneda6ccd2017-12-04 18:21:555037 return video_channel;
Steve Anton75737c02017-11-06 18:37:175038}
5039
Steve Antoneda6ccd2017-12-04 18:21:555040bool PeerConnection::CreateDataChannel(const std::string& mid,
5041 const std::string& transport_name) {
Steve Anton75737c02017-11-06 18:37:175042 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5043 if (sctp) {
5044 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255045 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175046 << "Trying to create SCTP transport, but didn't compile with "
5047 "SCTP support (HAVE_SCTP)";
5048 return false;
5049 }
5050 if (!network_thread()->Invoke<bool>(
5051 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 18:21:555052 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 18:37:175053 return false;
5054 }
Steve Antoneda6ccd2017-12-04 18:21:555055 for (const auto& channel : sctp_data_channels_) {
5056 channel->OnTransportChannelCreated();
5057 }
Steve Anton75737c02017-11-06 18:37:175058 } else {
Steve Anton75737c02017-11-06 18:37:175059 cricket::DtlsTransportInternal* rtp_dtls_transport =
5060 transport_controller_->CreateDtlsTransport(
5061 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5062 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5063 if (configuration_.rtcp_mux_policy !=
5064 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5065 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5066 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5067 }
5068
5069 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5070 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 18:21:555071 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 18:37:175072
5073 if (!rtp_data_channel_) {
5074 transport_controller_->DestroyDtlsTransport(
5075 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5076 if (rtcp_dtls_transport) {
5077 transport_controller_->DestroyDtlsTransport(
5078 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5079 }
5080 return false;
5081 }
5082
5083 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5084 this, &PeerConnection::DestroyRtcpTransport_n);
5085 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5086 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5087 rtp_data_channel_->SignalSentPacket.connect(
5088 this, &PeerConnection::OnSentPacket_w);
5089 }
5090
Steve Anton75737c02017-11-06 18:37:175091 return true;
5092}
5093
5094Call::Stats PeerConnection::GetCallStats() {
5095 if (!worker_thread()->IsCurrent()) {
5096 return worker_thread()->Invoke<Call::Stats>(
5097 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5098 }
5099 if (call_) {
5100 return call_->GetStats();
5101 } else {
5102 return Call::Stats();
5103 }
5104}
5105
5106std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5107 const ChannelNamePairs& channel_name_pairs) {
5108 RTC_DCHECK(network_thread()->IsCurrent());
5109 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5110 for (const auto channel_name_pair :
5111 {&channel_name_pairs.voice, &channel_name_pairs.video,
5112 &channel_name_pairs.data}) {
5113 if (*channel_name_pair) {
5114 cricket::TransportStats transport_stats;
5115 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5116 &transport_stats)) {
5117 return nullptr;
5118 }
Steve Anton75737c02017-11-06 18:37:175119 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5120 std::move(transport_stats);
5121 }
5122 }
5123 return session_stats;
5124}
5125
5126bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5127 const std::string& transport_name) {
5128 RTC_DCHECK(network_thread()->IsCurrent());
5129 RTC_DCHECK(sctp_factory_);
5130 cricket::DtlsTransportInternal* tc =
5131 transport_controller_->CreateDtlsTransport_n(
5132 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5133 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5134 RTC_DCHECK(sctp_transport_);
5135 sctp_invoker_.reset(new rtc::AsyncInvoker());
5136 sctp_transport_->SignalReadyToSendData.connect(
5137 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5138 sctp_transport_->SignalDataReceived.connect(
5139 this, &PeerConnection::OnSctpTransportDataReceived_n);
5140 sctp_transport_->SignalStreamClosedRemotely.connect(
5141 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 09:53:305142 sctp_transport_name_ = transport_name;
5143 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 18:37:175144 return true;
5145}
5146
5147void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5148 RTC_DCHECK(network_thread()->IsCurrent());
5149 RTC_DCHECK(sctp_transport_);
5150 RTC_DCHECK(sctp_transport_name_);
5151 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 09:53:305152 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 18:37:175153 cricket::DtlsTransportInternal* tc =
5154 transport_controller_->CreateDtlsTransport_n(
5155 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5156 sctp_transport_->SetTransportChannel(tc);
5157 transport_controller_->DestroyDtlsTransport_n(
5158 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5159}
5160
5161void PeerConnection::DestroySctpTransport_n() {
5162 RTC_DCHECK(network_thread()->IsCurrent());
5163 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-04 00:26:065164 transport_controller_->DestroyDtlsTransport_n(
5165 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 18:37:175166 sctp_content_name_.reset();
5167 sctp_transport_name_.reset();
5168 sctp_invoker_.reset(nullptr);
5169 sctp_ready_to_send_data_ = false;
5170}
5171
5172void PeerConnection::OnSctpTransportReadyToSendData_n() {
5173 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5174 RTC_DCHECK(network_thread()->IsCurrent());
5175 // Note: Cannot use rtc::Bind here because it will grab a reference to
5176 // PeerConnection and potentially cause PeerConnection to live longer than
5177 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5178 // be destroyed before PeerConnection is destroyed, and at that point all
5179 // pending tasks will be cleared.
5180 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5181 OnSctpTransportReadyToSendData_s(true);
5182 });
5183}
5184
5185void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5186 RTC_DCHECK(signaling_thread()->IsCurrent());
5187 sctp_ready_to_send_data_ = ready;
5188 SignalSctpReadyToSendData(ready);
5189}
5190
5191void PeerConnection::OnSctpTransportDataReceived_n(
5192 const cricket::ReceiveDataParams& params,
5193 const rtc::CopyOnWriteBuffer& payload) {
5194 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5195 RTC_DCHECK(network_thread()->IsCurrent());
5196 // Note: Cannot use rtc::Bind here because it will grab a reference to
5197 // PeerConnection and potentially cause PeerConnection to live longer than
5198 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5199 // be destroyed before PeerConnection is destroyed, and at that point all
5200 // pending tasks will be cleared.
5201 sctp_invoker_->AsyncInvoke<void>(
5202 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5203 OnSctpTransportDataReceived_s(params, payload);
5204 });
5205}
5206
5207void PeerConnection::OnSctpTransportDataReceived_s(
5208 const cricket::ReceiveDataParams& params,
5209 const rtc::CopyOnWriteBuffer& payload) {
5210 RTC_DCHECK(signaling_thread()->IsCurrent());
5211 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5212 // Received OPEN message; parse and signal that a new data channel should
5213 // be created.
5214 std::string label;
5215 InternalDataChannelInit config;
5216 config.id = params.ssrc;
5217 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255218 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5219 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175220 return;
5221 }
5222 config.open_handshake_role = InternalDataChannelInit::kAcker;
5223 OnDataChannelOpenMessage(label, config);
5224 } else {
5225 // Otherwise just forward the signal.
5226 SignalSctpDataReceived(params, payload);
5227 }
5228}
5229
5230void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5231 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5232 RTC_DCHECK(network_thread()->IsCurrent());
5233 sctp_invoker_->AsyncInvoke<void>(
5234 RTC_FROM_HERE, signaling_thread(),
5235 rtc::Bind(&sigslot::signal1<int>::operator(),
5236 &SignalSctpStreamClosedRemotely, sid));
5237}
5238
5239// Returns false if bundle is enabled and rtcp_mux is disabled.
5240bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5241 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5242 if (!bundle_enabled)
5243 return true;
5244
5245 const cricket::ContentGroup* bundle_group =
5246 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5247 RTC_DCHECK(bundle_group != NULL);
5248
5249 const cricket::ContentInfos& contents = desc->contents();
5250 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5251 citer != contents.end(); ++citer) {
5252 const cricket::ContentInfo* content = (&*citer);
5253 RTC_DCHECK(content != NULL);
5254 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005255 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175256 if (!HasRtcpMuxEnabled(content))
5257 return false;
5258 }
5259 }
5260 // RTCP-MUX is enabled in all the contents.
5261 return true;
5262}
5263
5264bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305265 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175266}
5267
Steve Anton8a006912017-12-04 23:25:565268RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175269 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565270 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215271 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565272 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175273 }
5274
5275 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175277 }
5278
Steve Anton3828c062017-12-06 18:34:515279 SdpType type = sdesc->GetType();
5280 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5281 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565282 LOG_AND_RETURN_ERROR(
5283 RTCErrorType::INVALID_PARAMETER,
5284 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175285 }
5286
5287 // Verify crypto settings.
5288 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565289 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5290 dtls_enabled_) {
5291 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
5292 if (!crypto_error.ok()) {
5293 return crypto_error;
5294 }
Steve Anton75737c02017-11-06 18:37:175295 }
5296
5297 // Verify ice-ufrag and ice-pwd.
5298 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5300 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175301 }
5302
5303 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5305 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175306 }
5307
5308 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5309 // m-lines that do not rtcp-mux enabled.
5310
5311 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515312 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 18:37:175313 const cricket::SessionDescription* offer_desc =
5314 (source == cricket::CS_LOCAL) ? remote_description()->description()
5315 : local_description()->description();
5316 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5317 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5319 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175320 }
5321 } else {
5322 const cricket::SessionDescription* current_desc = nullptr;
5323 if (source == cricket::CS_LOCAL && local_description()) {
5324 current_desc = local_description()->description();
5325 } else if (source == cricket::CS_REMOTE && remote_description()) {
5326 current_desc = remote_description()->description();
5327 }
5328 // The re-offers should respect the order of m= sections in current
5329 // description. See RFC3264 Section 8 paragraph 4 for more details.
5330 if (current_desc &&
5331 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5333 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175334 }
5335 }
5336
Steve Anton02ee47c2018-01-11 00:26:065337 // Unified Plan SDP should have exactly one stream per m= section for audio
5338 // and video.
5339 if (IsUnifiedPlan()) {
5340 for (const ContentInfo& content : sdesc->description()->contents()) {
5341 if (content.rejected) {
5342 continue;
5343 }
5344 if (content.media_description()) {
5345 cricket::MediaType media_type = content.media_description()->type();
5346 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
5347 media_type == cricket::MEDIA_TYPE_VIDEO)) {
5348 continue;
5349 }
5350 const cricket::StreamParamsVec& streams =
5351 content.media_description()->streams();
5352 if (streams.size() != 1u) {
5353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5354 "Unified Plan SDP should have exactly one "
5355 "track per media section for audio and video.");
5356 }
5357 }
5358 }
5359 }
5360
Steve Anton8a006912017-12-04 23:25:565361 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175362}
5363
Steve Anton3828c062017-12-06 18:34:515364bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175365 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515366 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175367 return (state == PeerConnectionInterface::kStable) ||
5368 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525369 } else {
Steve Anton3828c062017-12-06 18:34:515370 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175371 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5372 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5373 }
5374}
5375
Steve Anton3828c062017-12-06 18:34:515376bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175377 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515378 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175379 return (state == PeerConnectionInterface::kStable) ||
5380 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525381 } else {
Steve Anton3828c062017-12-06 18:34:515382 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175383 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5384 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5385 }
5386}
5387
Steve Antonf8470812017-12-04 18:46:215388const char* PeerConnection::SessionErrorToString(SessionError error) const {
5389 switch (error) {
5390 case SessionError::kNone:
5391 return "ERROR_NONE";
5392 case SessionError::kContent:
5393 return "ERROR_CONTENT";
5394 case SessionError::kTransport:
5395 return "ERROR_TRANSPORT";
5396 }
5397 RTC_NOTREACHED();
5398 return "";
5399}
5400
Steve Anton75737c02017-11-06 18:37:175401std::string PeerConnection::GetSessionErrorMsg() {
5402 std::ostringstream desc;
Steve Antonf8470812017-12-04 18:46:215403 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5404 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 18:37:175405 return desc.str();
5406}
5407
5408// We need to check the local/remote description for the Transport instead of
5409// the session, because a new Transport added during renegotiation may have
5410// them unset while the session has them set from the previous negotiation.
5411// Not doing so may trigger the auto generation of transport description and
5412// mess up DTLS identity information, ICE credential, etc.
5413bool PeerConnection::ReadyToUseRemoteCandidate(
5414 const IceCandidateInterface* candidate,
5415 const SessionDescriptionInterface* remote_desc,
5416 bool* valid) {
5417 *valid = true;
5418
5419 const SessionDescriptionInterface* current_remote_desc =
5420 remote_desc ? remote_desc : remote_description();
5421
5422 if (!current_remote_desc) {
5423 return false;
5424 }
5425
5426 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5427 size_t remote_content_size =
5428 current_remote_desc->description()->contents().size();
5429 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255430 RTC_LOG(LS_ERROR)
5431 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5432 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:175433
5434 *valid = false;
5435 return false;
5436 }
5437
5438 cricket::ContentInfo content =
5439 current_remote_desc->description()->contents()[mediacontent_index];
5440
5441 const std::string transport_name = GetTransportName(content.name);
5442 if (transport_name.empty()) {
5443 return false;
5444 }
5445 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5446}
5447
5448bool PeerConnection::SrtpRequired() const {
5449 return dtls_enabled_ ||
5450 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5451}
5452
5453void PeerConnection::OnTransportControllerGatheringState(
5454 cricket::IceGatheringState state) {
5455 RTC_DCHECK(signaling_thread()->IsCurrent());
5456 if (state == cricket::kIceGatheringGathering) {
5457 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5458 } else if (state == cricket::kIceGatheringComplete) {
5459 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5460 }
5461}
5462
5463void PeerConnection::ReportTransportStats() {
5464 // Use a set so we don't report the same stats twice if two channels share
5465 // a transport.
5466 std::set<std::string> transport_names;
5467 if (voice_channel()) {
5468 transport_names.insert(voice_channel()->transport_name());
5469 }
5470 if (video_channel()) {
5471 transport_names.insert(video_channel()->transport_name());
5472 }
5473 if (rtp_data_channel()) {
5474 transport_names.insert(rtp_data_channel()->transport_name());
5475 }
5476 if (sctp_transport_name_) {
5477 transport_names.insert(*sctp_transport_name_);
5478 }
5479 for (const auto& name : transport_names) {
5480 cricket::TransportStats stats;
5481 if (transport_controller_->GetStats(name, &stats)) {
5482 ReportBestConnectionState(stats);
5483 ReportNegotiatedCiphers(stats);
5484 }
5485 }
5486}
5487// Walk through the ConnectionInfos to gather best connection usage
5488// for IPv4 and IPv6.
5489void PeerConnection::ReportBestConnectionState(
5490 const cricket::TransportStats& stats) {
5491 RTC_DCHECK(metrics_observer());
5492 for (cricket::TransportChannelStatsList::const_iterator it =
5493 stats.channel_stats.begin();
5494 it != stats.channel_stats.end(); ++it) {
5495 for (cricket::ConnectionInfos::const_iterator it_info =
5496 it->connection_infos.begin();
5497 it_info != it->connection_infos.end(); ++it_info) {
5498 if (!it_info->best_connection) {
5499 continue;
5500 }
5501
5502 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5503 const cricket::Candidate& local = it_info->local_candidate;
5504 const cricket::Candidate& remote = it_info->remote_candidate;
5505
5506 // Increment the counter for IceCandidatePairType.
5507 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5508 (local.type() == RELAY_PORT_TYPE &&
5509 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5510 type = kEnumCounterIceCandidatePairTypeTcp;
5511 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5512 type = kEnumCounterIceCandidatePairTypeUdp;
5513 } else {
5514 RTC_CHECK(0);
5515 }
5516 metrics_observer()->IncrementEnumCounter(
5517 type, GetIceCandidatePairCounter(local, remote),
5518 kIceCandidatePairMax);
5519
5520 // Increment the counter for IP type.
5521 if (local.address().family() == AF_INET) {
5522 metrics_observer()->IncrementEnumCounter(
5523 kEnumCounterAddressFamily, kBestConnections_IPv4,
5524 kPeerConnectionAddressFamilyCounter_Max);
5525
5526 } else if (local.address().family() == AF_INET6) {
5527 metrics_observer()->IncrementEnumCounter(
5528 kEnumCounterAddressFamily, kBestConnections_IPv6,
5529 kPeerConnectionAddressFamilyCounter_Max);
5530 } else {
5531 RTC_CHECK(0);
5532 }
5533
5534 return;
5535 }
5536 }
5537}
5538
5539void PeerConnection::ReportNegotiatedCiphers(
5540 const cricket::TransportStats& stats) {
5541 RTC_DCHECK(metrics_observer());
5542 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5543 return;
5544 }
5545
5546 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5547 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5548 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5549 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5550 return;
5551 }
5552
5553 PeerConnectionEnumCounterType srtp_counter_type;
5554 PeerConnectionEnumCounterType ssl_counter_type;
5555 if (stats.transport_name == cricket::CN_AUDIO) {
5556 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5557 ssl_counter_type = kEnumCounterAudioSslCipher;
5558 } else if (stats.transport_name == cricket::CN_VIDEO) {
5559 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5560 ssl_counter_type = kEnumCounterVideoSslCipher;
5561 } else if (stats.transport_name == cricket::CN_DATA) {
5562 srtp_counter_type = kEnumCounterDataSrtpCipher;
5563 ssl_counter_type = kEnumCounterDataSslCipher;
5564 } else {
5565 RTC_NOTREACHED();
5566 return;
5567 }
5568
5569 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5570 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5571 srtp_crypto_suite);
5572 }
5573 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5574 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5575 ssl_cipher_suite);
5576 }
5577}
5578
5579void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5580 RTC_DCHECK(worker_thread()->IsCurrent());
5581 RTC_DCHECK(call_);
5582 call_->OnSentPacket(sent_packet);
5583}
5584
5585const std::string PeerConnection::GetTransportName(
5586 const std::string& content_name) {
5587 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:295588 if (channel) {
5589 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:175590 }
Steve Anton6fec8802017-12-04 18:37:295591 if (sctp_transport_) {
5592 RTC_DCHECK(sctp_content_name_);
5593 RTC_DCHECK(sctp_transport_name_);
5594 if (content_name == *sctp_content_name_) {
5595 return *sctp_transport_name_;
5596 }
5597 }
5598 // Return an empty string if failed to retrieve the transport name.
5599 return "";
Steve Anton75737c02017-11-06 18:37:175600}
5601
5602void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5603 RTC_DCHECK(network_thread()->IsCurrent());
5604 transport_controller_->DestroyDtlsTransport_n(
5605 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5606}
5607
Steve Anton6fec8802017-12-04 18:37:295608void PeerConnection::DestroyTransceiverChannel(
5609 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5610 transceiver) {
5611 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:175612
Steve Anton6fec8802017-12-04 18:37:295613 cricket::BaseChannel* channel = transceiver->internal()->channel();
5614 if (channel) {
5615 transceiver->internal()->SetChannel(nullptr);
5616 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:175617 }
5618}
5619
5620void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:295621 if (rtp_data_channel_) {
5622 OnDataChannelDestroyed();
5623 DestroyBaseChannel(rtp_data_channel_);
5624 rtp_data_channel_ = nullptr;
5625 }
5626
5627 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5628 // grab a reference to this PeerConnection. If this is called from the
5629 // PeerConnection destructor, the RefCountedObject vtable will have already
5630 // been destroyed (since it is a subclass of PeerConnection) and using
5631 // rtc::Bind will cause "Pure virtual function called" error to appear.
5632
5633 if (sctp_transport_) {
5634 OnDataChannelDestroyed();
5635 network_thread()->Invoke<void>(RTC_FROM_HERE,
5636 [this] { DestroySctpTransport_n(); });
5637 }
5638}
5639
5640void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5641 RTC_DCHECK(channel);
5642 RTC_DCHECK(channel->rtp_dtls_transport());
5643
5644 // Need to cache these before destroying the base channel so that we do not
5645 // access uninitialized memory.
5646 const std::string transport_name =
5647 channel->rtp_dtls_transport()->transport_name();
5648 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5649
5650 switch (channel->media_type()) {
5651 case cricket::MEDIA_TYPE_AUDIO:
5652 channel_manager()->DestroyVoiceChannel(
5653 static_cast<cricket::VoiceChannel*>(channel));
5654 break;
5655 case cricket::MEDIA_TYPE_VIDEO:
5656 channel_manager()->DestroyVideoChannel(
5657 static_cast<cricket::VideoChannel*>(channel));
5658 break;
5659 case cricket::MEDIA_TYPE_DATA:
5660 channel_manager()->DestroyRtpDataChannel(
5661 static_cast<cricket::RtpDataChannel*>(channel));
5662 break;
5663 default:
5664 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5665 break;
5666 }
5667
5668 // |channel| can no longer be used.
5669
Steve Anton75737c02017-11-06 18:37:175670 transport_controller_->DestroyDtlsTransport(
5671 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5672 if (need_to_delete_rtcp) {
5673 transport_controller_->DestroyDtlsTransport(
5674 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5675 }
5676}
5677
Harald Alvestrand89061872018-01-02 13:08:345678void PeerConnection::ClearStatsCache() {
5679 if (stats_collector_) {
5680 stats_collector_->ClearCachedStatsReport();
5681 }
5682}
5683
henrike@webrtc.org28e20752013-07-10 00:45:365684} // namespace webrtc