blob: 1bdd64056f0b1203851c34dada02d9cf6b8d6811 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#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"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
deadbeefab9b2d12015-10-14 11:33:11 -070096static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
127 std::string error;
128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
145 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
321// Verify that the order of media sections in |new_desc| matches
322// |existing_desc|. The number of m= sections in |new_desc| should be no less
323// than |existing_desc|.
324bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
325 const SessionDescription* new_desc) {
326 if (!existing_desc || !new_desc) {
327 return false;
328 }
329
330 if (existing_desc->contents().size() > new_desc->contents().size()) {
331 return false;
332 }
333
334 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-22 16:02:54 -0800335 if (existing_desc->contents()[i].rejected) {
336 // If the media section can be recycled, it's valid for the MID and media
337 // type to change.
338 continue;
339 }
Steve Anton75737c02017-11-06 10:37:17 -0800340 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
341 return false;
342 }
343 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800344 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800345 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800346 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800347 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
348 return false;
349 }
350 }
351 return true;
352}
353
354bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
355 const SessionDescription* desc2) {
356 if (!desc1 || !desc2) {
357 return false;
358 }
359 return desc1->contents().size() == desc2->contents().size();
360}
361
362// Checks that each non-rejected content has SDES crypto keys or a DTLS
363// fingerprint, unless it's in a BUNDLE group, in which case only the
364// BUNDLE-tag section (first media section/description in the BUNDLE group)
365// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
366// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
367// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100368RTCError VerifyCrypto(const SessionDescription* desc,
369 bool dtls_enabled,
370 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800371 const cricket::ContentGroup* bundle =
372 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800373 for (const cricket::ContentInfo& content_info : desc->contents()) {
374 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800375 continue;
376 }
Steve Anton8a006912017-12-04 15:25:56 -0800377 const std::string& mid = content_info.name;
378 if (bundle && bundle->HasContentName(mid) &&
379 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 // This isn't the first media section in the BUNDLE group, so it's not
381 // required to have crypto attributes, since only the crypto attributes
382 // from the first section actually get used.
383 continue;
384 }
385
386 // If the content isn't rejected or bundled into another m= section, crypto
387 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800388 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800389 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800390 if (!media || !tinfo) {
391 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800393 }
394 if (dtls_enabled) {
395 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100396 RTC_LOG(LS_WARNING)
397 << "Session description must have DTLS fingerprint if "
398 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800399 return RTCError(RTCErrorType::INVALID_PARAMETER,
400 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800401 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100402 if (uma_observer) {
403 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
404 webrtc::kEnumCounterKeyProtocolDtls,
405 webrtc::kEnumCounterKeyProtocolMax);
406 }
Steve Anton75737c02017-11-06 10:37:17 -0800407 } else {
408 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100409 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800410 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800411 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800412 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100413 if (uma_observer) {
414 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
415 webrtc::kEnumCounterKeyProtocolSdes,
416 webrtc::kEnumCounterKeyProtocolMax);
417 }
Steve Anton75737c02017-11-06 10:37:17 -0800418 }
419 }
Steve Anton8a006912017-12-04 15:25:56 -0800420 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800421}
422
423// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
424// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
425// media section/description in the BUNDLE group) needs a ufrag and pwd.
426bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Steve Anton8a006912017-12-04 15:25:56 -0800433 const std::string& mid = content_info.name;
434 if (bundle && bundle->HasContentName(mid) &&
435 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800436 // This isn't the first media section in the BUNDLE group, so it's not
437 // required to have ufrag/password, since only the ufrag/password from
438 // the first section actually get used.
439 continue;
440 }
441
442 // If the content isn't rejected or bundled into another m= section,
443 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800444 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800445 if (!tinfo) {
446 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800448 return false;
449 }
450 if (tinfo->description.ice_ufrag.empty() ||
451 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800453 return false;
454 }
455 }
456 return true;
457}
458
459bool GetTrackIdBySsrc(const SessionDescription* session_description,
460 uint32_t ssrc,
461 std::string* track_id) {
462 RTC_DCHECK(track_id != NULL);
463
Steve Antonb1c1de12017-12-21 15:14:30 -0800464 const cricket::AudioContentDescription* audio_desc =
465 cricket::GetFirstAudioContentDescription(session_description);
466 if (audio_desc) {
467 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800468 if (found) {
469 *track_id = found->id;
470 return true;
471 }
472 }
473
Steve Antonb1c1de12017-12-21 15:14:30 -0800474 const cricket::VideoContentDescription* video_desc =
475 cricket::GetFirstVideoContentDescription(session_description);
476 if (video_desc) {
477 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800478 if (found) {
479 *track_id = found->id;
480 return true;
481 }
482 }
483 return false;
484}
485
486// Get the SCTP port out of a SessionDescription.
487// Return -1 if not found.
488int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800489 const cricket::DataContentDescription* data_desc =
490 GetFirstDataContentDescription(session_description);
491 RTC_DCHECK(data_desc);
492 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 return -1;
494 }
Steve Anton75737c02017-11-06 10:37:17 -0800495 std::string value;
496 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
497 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800498 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800499 if (!codec.Matches(match_pattern)) {
500 continue;
501 }
502 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
503 return rtc::FromString<int>(value);
504 }
505 }
506 return -1;
507}
508
Steve Anton75737c02017-11-06 10:37:17 -0800509// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
510bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
511 const SessionDescriptionInterface* new_desc,
512 const std::string& content_name) {
513 if (!old_desc) {
514 return false;
515 }
516 const SessionDescription* new_sd = new_desc->description();
517 const SessionDescription* old_sd = old_desc->description();
518 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
519 if (!cinfo || cinfo->rejected) {
520 return false;
521 }
522 // If the content isn't rejected, check if ufrag and password has changed.
523 const cricket::TransportDescription* new_transport_desc =
524 new_sd->GetTransportDescriptionByName(content_name);
525 const cricket::TransportDescription* old_transport_desc =
526 old_sd->GetTransportDescriptionByName(content_name);
527 if (!new_transport_desc || !old_transport_desc) {
528 // No transport description exists. This is not an ICE restart.
529 return false;
530 }
531 if (cricket::IceCredentialsChanged(
532 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
533 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100534 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
535 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800536 return true;
537 }
538 return false;
539}
540
541} // namespace
542
Henrik Boström31638672017-11-23 17:48:32 +0100543// Upon completion, posts a task to execute the callback of the
544// SetSessionDescriptionObserver asynchronously on the same thread. At this
545// point, the state of the peer connection might no longer reflect the effects
546// of the SetRemoteDescription operation, as the peer connection could have been
547// modified during the post.
548// TODO(hbos): Remove this class once we remove the version of
549// PeerConnectionInterface::SetRemoteDescription() that takes a
550// SetSessionDescriptionObserver as an argument.
551class PeerConnection::SetRemoteDescriptionObserverAdapter
552 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
553 public:
554 SetRemoteDescriptionObserverAdapter(
555 rtc::scoped_refptr<PeerConnection> pc,
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
557 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
558
559 // SetRemoteDescriptionObserverInterface implementation.
560 void OnSetRemoteDescriptionComplete(RTCError error) override {
561 if (error.ok())
562 pc_->PostSetSessionDescriptionSuccess(wrapper_);
563 else
564 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
565 }
566
567 private:
568 rtc::scoped_refptr<PeerConnection> pc_;
569 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
570};
571
deadbeef293e9262017-01-11 12:28:30 -0800572bool PeerConnectionInterface::RTCConfiguration::operator==(
573 const PeerConnectionInterface::RTCConfiguration& o) const {
574 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700575 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800576 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000577 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700578 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800579 BundlePolicy bundle_policy;
580 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700581 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
582 int ice_candidate_pool_size;
583 bool disable_ipv6;
584 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700585 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100586 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700587 bool enable_rtp_data_channel;
588 rtc::Optional<int> screencast_min_bitrate;
589 rtc::Optional<bool> combined_audio_video_bwe;
590 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800591 TcpCandidatePolicy tcp_candidate_policy;
592 CandidateNetworkPolicy candidate_network_policy;
593 int audio_jitter_buffer_max_packets;
594 bool audio_jitter_buffer_fast_accelerate;
595 int ice_connection_receiving_timeout;
596 int ice_backup_candidate_pair_ping_interval;
597 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800598 bool prioritize_most_likely_ice_candidate_pairs;
599 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800600 bool prune_turn_ports;
601 bool presume_writable_when_fully_relayed;
602 bool enable_ice_renomination;
603 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800604 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700605 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200606 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800607 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800608 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800609 };
610 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
611 "Did you add something to RTCConfiguration and forget to "
612 "update operator==?");
613 return type == o.type && servers == o.servers &&
614 bundle_policy == o.bundle_policy &&
615 rtcp_mux_policy == o.rtcp_mux_policy &&
616 tcp_candidate_policy == o.tcp_candidate_policy &&
617 candidate_network_policy == o.candidate_network_policy &&
618 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
619 audio_jitter_buffer_fast_accelerate ==
620 o.audio_jitter_buffer_fast_accelerate &&
621 ice_connection_receiving_timeout ==
622 o.ice_connection_receiving_timeout &&
623 ice_backup_candidate_pair_ping_interval ==
624 o.ice_backup_candidate_pair_ping_interval &&
625 continual_gathering_policy == o.continual_gathering_policy &&
626 certificates == o.certificates &&
627 prioritize_most_likely_ice_candidate_pairs ==
628 o.prioritize_most_likely_ice_candidate_pairs &&
629 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800630 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700631 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100632 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800633 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800634 screencast_min_bitrate == o.screencast_min_bitrate &&
635 combined_audio_video_bwe == o.combined_audio_video_bwe &&
636 enable_dtls_srtp == o.enable_dtls_srtp &&
637 ice_candidate_pool_size == o.ice_candidate_pool_size &&
638 prune_turn_ports == o.prune_turn_ports &&
639 presume_writable_when_fully_relayed ==
640 o.presume_writable_when_fully_relayed &&
641 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800642 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700643 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200644 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800645 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800646 sdp_semantics == o.sdp_semantics &&
647 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800648}
649
650bool PeerConnectionInterface::RTCConfiguration::operator!=(
651 const PeerConnectionInterface::RTCConfiguration& o) const {
652 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800653}
654
zhihuang8f65cdf2016-05-06 18:40:30 -0700655// Generate a RTCP CNAME when a PeerConnection is created.
656std::string GenerateRtcpCname() {
657 std::string cname;
658 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100659 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800660 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700661 }
662 return cname;
663}
664
zhihuang1c378ed2017-08-17 14:10:50 -0700665bool ValidateOfferAnswerOptions(
666 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
667 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
668 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700669}
670
zhihuang1c378ed2017-08-17 14:10:50 -0700671// From |rtc_options|, fill parts of |session_options| shared by all generated
672// m= sections (in other words, nothing that involves a map/array).
673void ExtractSharedMediaSessionOptions(
674 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
675 cricket::MediaSessionOptions* session_options) {
676 session_options->vad_enabled = rtc_options.voice_activity_detection;
677 session_options->bundle_enabled = rtc_options.use_rtp_mux;
678}
zhihuanga77e6bb2017-08-14 18:17:48 -0700679
zhihuang1c378ed2017-08-17 14:10:50 -0700680bool ConvertConstraintsToOfferAnswerOptions(
681 const MediaConstraintsInterface* constraints,
682 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700683 if (!constraints) {
684 return true;
685 }
zhihuang1c378ed2017-08-17 14:10:50 -0700686
687 bool value = false;
688 size_t mandatory_constraints_satisfied = 0;
689
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->offer_to_receive_audio =
694 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
695 kOfferToReceiveMediaTrue
696 : 0;
697 }
698
699 if (FindConstraint(constraints,
700 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
701 &mandatory_constraints_satisfied)) {
702 offer_answer_options->offer_to_receive_video =
703 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
704 kOfferToReceiveMediaTrue
705 : 0;
706 }
707 if (FindConstraint(constraints,
708 MediaConstraintsInterface::kVoiceActivityDetection, &value,
709 &mandatory_constraints_satisfied)) {
710 offer_answer_options->voice_activity_detection = value;
711 }
712 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
713 &mandatory_constraints_satisfied)) {
714 offer_answer_options->use_rtp_mux = value;
715 }
716 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
717 &value, &mandatory_constraints_satisfied)) {
718 offer_answer_options->ice_restart = value;
719 }
720
deadbeefab9b2d12015-10-14 11:33:11 -0700721 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
722}
723
zhihuang38ede132017-06-15 12:52:32 -0700724PeerConnection::PeerConnection(PeerConnectionFactory* factory,
725 std::unique_ptr<RtcEventLog> event_log,
726 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000727 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700728 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700729 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700730 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700731 remote_streams_(StreamCollection::Create()),
732 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733
734PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100735 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800736 RTC_DCHECK_RUN_ON(signaling_thread());
737
Steve Anton8af21862017-12-15 11:20:13 -0800738 // Need to stop transceivers before destroying the stats collector because
739 // AudioRtpSender has a reference to the StatsCollector it will update when
740 // stopping.
741 for (auto transceiver : transceivers_) {
742 transceiver->Stop();
743 }
Steve Anton4171afb2017-11-20 10:20:22 -0800744
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700745 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800746 if (stats_collector_) {
747 stats_collector_->WaitForPendingRequest();
748 stats_collector_ = nullptr;
749 }
Steve Anton75737c02017-11-06 10:37:17 -0800750
Steve Anton8af21862017-12-15 11:20:13 -0800751 // Don't destroy BaseChannels until after stats has been cleaned up so that
752 // the last stats request can still read from the channels.
753 DestroyAllChannels();
754
Mirko Bonadei675513b2017-11-09 11:09:25 +0100755 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800756
757 webrtc_session_desc_factory_.reset();
758 sctp_invoker_.reset();
759 sctp_factory_.reset();
760 transport_controller_.reset();
761
deadbeef91dd5672016-05-18 16:55:30 -0700762 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700763 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700764 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700765 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700766 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700767 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800768 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700769 event_log_.reset();
770 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771}
772
Steve Anton8af21862017-12-15 11:20:13 -0800773void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800774 // Destroy video channels first since they may have a pointer to a voice
775 // channel.
776 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800777 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800778 DestroyTransceiverChannel(transceiver);
779 }
780 }
781 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800782 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800783 DestroyTransceiverChannel(transceiver);
784 }
785 }
786 DestroyDataChannel();
787}
788
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000789bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000790 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700791 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200792 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800793 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100794 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700795
796 RTCError config_error = ValidateConfiguration(configuration);
797 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100798 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700799 return false;
800 }
801
deadbeef293e9262017-01-11 12:28:30 -0800802 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100803 RTC_LOG(LS_ERROR)
804 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100805 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800806 return false;
807 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200808
deadbeef653b8e02015-11-11 12:55:10 -0800809 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800810 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100811 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100812 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800813 return false;
814 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000815 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800816 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800817
deadbeef91dd5672016-05-18 16:55:30 -0700818 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700819 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700820 if (!network_thread()->Invoke<bool>(
821 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
822 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 return false;
824 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825
Steve Anton75737c02017-11-06 10:37:17 -0800826 // RFC 3264: The numeric value of the session id and version in the
827 // o line MUST be representable with a "64 bit signed integer".
828 // Due to this constraint session id |session_id_| is max limited to
829 // LLONG_MAX.
830 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
831 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800832 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
833 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800834 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
835 transport_controller_->SignalConnectionState.connect(
836 this, &PeerConnection::OnTransportControllerConnectionState);
837 transport_controller_->SignalGatheringState.connect(
838 this, &PeerConnection::OnTransportControllerGatheringState);
839 transport_controller_->SignalCandidatesGathered.connect(
840 this, &PeerConnection::OnTransportControllerCandidatesGathered);
841 transport_controller_->SignalCandidatesRemoved.connect(
842 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
843 transport_controller_->SignalDtlsHandshakeError.connect(
844 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
845
846 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700847
deadbeefab9b2d12015-10-14 11:33:11 -0700848 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700849 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850
Steve Antonba818672017-11-06 10:21:57 -0800851 configuration_ = configuration;
852
Steve Anton75737c02017-11-06 10:37:17 -0800853 const PeerConnectionFactoryInterface::Options& options = factory_->options();
854
855 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
856
857 // Obtain a certificate from RTCConfiguration if any were provided (optional).
858 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
859 if (!configuration.certificates.empty()) {
860 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
861 // just picking the first one. The decision should be made based on the DTLS
862 // handshake. The DTLS negotiations need to know about all certificates.
863 certificate = configuration.certificates[0];
864 }
865
Steve Antond25da372017-11-06 14:50:29 -0800866 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800867
868 if (options.disable_encryption) {
869 dtls_enabled_ = false;
870 } else {
871 // Enable DTLS by default if we have an identity store or a certificate.
872 dtls_enabled_ = (cert_generator || certificate);
873 // |configuration| can override the default |dtls_enabled_| value.
874 if (configuration.enable_dtls_srtp) {
875 dtls_enabled_ = *(configuration.enable_dtls_srtp);
876 }
877 }
878
879 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
880 // It takes precendence over the disable_sctp_data_channels
881 // PeerConnectionFactoryInterface::Options.
882 if (configuration.enable_rtp_data_channel) {
883 data_channel_type_ = cricket::DCT_RTP;
884 } else {
885 // DTLS has to be enabled to use SCTP.
886 if (!options.disable_sctp_data_channels && dtls_enabled_) {
887 data_channel_type_ = cricket::DCT_SCTP;
888 }
889 }
890
891 video_options_.screencast_min_bitrate_kbps =
892 configuration.screencast_min_bitrate;
893 audio_options_.combined_audio_video_bwe =
894 configuration.combined_audio_video_bwe;
895
896 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100897 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800898
899 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100900 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800901
902 // Whether the certificate generator/certificate is null or not determines
903 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
904 // the right instructions by clearing the variables if needed.
905 if (!dtls_enabled_) {
906 cert_generator.reset();
907 certificate = nullptr;
908 } else if (certificate) {
909 // Favor generated certificate over the certificate generator.
910 cert_generator.reset();
911 }
912
913 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
914 signaling_thread(), channel_manager(), this, session_id(),
915 std::move(cert_generator), certificate));
916 webrtc_session_desc_factory_->SignalCertificateReady.connect(
917 this, &PeerConnection::OnCertificateReady);
918
919 if (options.disable_encryption) {
920 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
921 }
922
923 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
924 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
Steve Anton4171afb2017-11-20 10:20:22 -0800926 // Add default audio/video transceivers for Plan B SDP.
927 if (!IsUnifiedPlan()) {
928 transceivers_.push_back(
929 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
930 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
931 transceivers_.push_back(
932 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
933 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
934 }
935
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936 return true;
937}
938
Steve Anton038834f2017-07-14 15:59:59 -0700939RTCError PeerConnection::ValidateConfiguration(
940 const RTCConfiguration& config) const {
941 if (config.ice_regather_interval_range &&
942 config.continual_gathering_policy == GATHER_ONCE) {
943 return RTCError(RTCErrorType::INVALID_PARAMETER,
944 "ice_regather_interval_range specified but continual "
945 "gathering policy is GATHER_ONCE");
946 }
947 return RTCError::OK();
948}
949
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000950rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700952 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953}
954
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000955rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700957 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958}
959
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000960bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100961 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 if (IsClosed()) {
963 return false;
964 }
deadbeefab9b2d12015-10-14 11:33:11 -0700965 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000966 return false;
967 }
deadbeefab9b2d12015-10-14 11:33:11 -0700968
969 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800970 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
971 observer->SignalAudioTrackAdded.connect(this,
972 &PeerConnection::OnAudioTrackAdded);
973 observer->SignalAudioTrackRemoved.connect(
974 this, &PeerConnection::OnAudioTrackRemoved);
975 observer->SignalVideoTrackAdded.connect(this,
976 &PeerConnection::OnVideoTrackAdded);
977 observer->SignalVideoTrackRemoved.connect(
978 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700979 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700980
deadbeefab9b2d12015-10-14 11:33:11 -0700981 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700982 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700983 }
984 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700985 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700986 }
987
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000988 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 observer_->OnRenegotiationNeeded();
990 return true;
991}
992
993void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100994 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700995 if (!IsClosed()) {
996 for (const auto& track : local_stream->GetAudioTracks()) {
997 RemoveAudioTrack(track.get(), local_stream);
998 }
999 for (const auto& track : local_stream->GetVideoTracks()) {
1000 RemoveVideoTrack(track.get(), local_stream);
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002 }
deadbeefab9b2d12015-10-14 11:33:11 -07001003 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001004 stream_observers_.erase(
1005 std::remove_if(
1006 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001007 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001008 return observer->stream()->label().compare(local_stream->label()) ==
1009 0;
1010 }),
1011 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 if (IsClosed()) {
1014 return;
1015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 observer_->OnRenegotiationNeeded();
1017}
1018
deadbeefe1f9d832016-01-14 15:35:42 -08001019rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1020 MediaStreamTrackInterface* track,
1021 std::vector<MediaStreamInterface*> streams) {
1022 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001023 std::vector<std::string> stream_labels;
1024 for (auto* stream : streams) {
1025 if (!stream) {
1026 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1027 return nullptr;
1028 }
1029 stream_labels.push_back(stream->label());
1030 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001031 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001032 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001033 return nullptr;
1034 }
Steve Antonf9381f02017-12-14 10:23:57 -08001035 return sender_or_error.MoveValue();
1036}
1037
Steve Anton2d6c76a2018-01-05 17:10:52 -08001038RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001039 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1040 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001041 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001042 if (!track) {
1043 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1044 }
1045 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1046 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1047 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1048 "Track has invalid kind: " + track->kind());
1049 }
1050 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1051 if (stream_labels.size() > 1u) {
1052 LOG_AND_RETURN_ERROR(
1053 RTCErrorType::UNSUPPORTED_OPERATION,
1054 "AddTrack with more than one stream is not currently supported.");
1055 }
1056 if (IsClosed()) {
1057 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1058 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001059 }
Steve Anton4171afb2017-11-20 10:20:22 -08001060 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001061 LOG_AND_RETURN_ERROR(
1062 RTCErrorType::INVALID_PARAMETER,
1063 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001064 }
Steve Antonf9381f02017-12-14 10:23:57 -08001065 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1066 // one stream. AddTrackInternal will return an error if there is more than one
1067 // stream, but if the caller specifies none then we need to generate a random
1068 // stream label.
1069 std::vector<std::string> adjusted_stream_labels = stream_labels;
1070 if (stream_labels.empty()) {
1071 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1072 }
1073 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1074 auto sender_or_error =
1075 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1076 : AddTrackPlanB(track, adjusted_stream_labels));
1077 if (sender_or_error.ok()) {
1078 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001079 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001080 }
1081 return sender_or_error;
1082}
deadbeefe1f9d832016-01-14 15:35:42 -08001083
Steve Antonf9381f02017-12-14 10:23:57 -08001084RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1085PeerConnection::AddTrackPlanB(
1086 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1087 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001088 cricket::MediaType media_type =
1089 (track->kind() == MediaStreamTrackInterface::kAudioKind
1090 ? cricket::MEDIA_TYPE_AUDIO
1091 : cricket::MEDIA_TYPE_VIDEO);
1092 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001093 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001094 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001095 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001096 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001097 const RtpSenderInfo* sender_info =
1098 FindSenderInfo(local_audio_sender_infos_,
1099 new_sender->internal()->stream_id(), track->id());
1100 if (sender_info) {
1101 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001102 }
Steve Antonf9381f02017-12-14 10:23:57 -08001103 } else {
1104 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001105 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001106 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001107 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001108 const RtpSenderInfo* sender_info =
1109 FindSenderInfo(local_video_sender_infos_,
1110 new_sender->internal()->stream_id(), track->id());
1111 if (sender_info) {
1112 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001113 }
deadbeefe1f9d832016-01-14 15:35:42 -08001114 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001115 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001116}
deadbeefe1f9d832016-01-14 15:35:42 -08001117
Steve Antonf9381f02017-12-14 10:23:57 -08001118RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1119PeerConnection::AddTrackUnifiedPlan(
1120 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1121 const std::vector<std::string>& stream_labels) {
1122 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1123 if (transceiver) {
1124 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1125 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1126 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1127 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1128 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001129 transceiver->sender()->SetTrack(track);
1130 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001131 } else {
1132 cricket::MediaType media_type =
1133 (track->kind() == MediaStreamTrackInterface::kAudioKind
1134 ? cricket::MEDIA_TYPE_AUDIO
1135 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001136 auto sender = CreateSender(media_type, track, stream_labels);
1137 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1138 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001139 transceiver->internal()->set_created_by_addtrack(true);
1140 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1141 }
Steve Antonf9381f02017-12-14 10:23:57 -08001142 return transceiver->sender();
1143}
1144
1145rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1146PeerConnection::FindFirstTransceiverForAddedTrack(
1147 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1148 RTC_DCHECK(track);
1149 for (auto transceiver : transceivers_) {
1150 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001151 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001152 track->kind() &&
1153 !transceiver->internal()->has_ever_been_used_to_send()) {
1154 return transceiver;
1155 }
1156 }
1157 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001158}
1159
1160bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1161 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001162 return RemoveTrackInternal(sender).ok();
1163}
1164
1165RTCError PeerConnection::RemoveTrackInternal(
1166 rtc::scoped_refptr<RtpSenderInterface> sender) {
1167 if (!sender) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1169 }
deadbeefe1f9d832016-01-14 15:35:42 -08001170 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001171 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1172 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001173 }
Steve Antonf9381f02017-12-14 10:23:57 -08001174 if (IsUnifiedPlan()) {
1175 auto transceiver = FindTransceiverBySender(sender);
1176 if (!transceiver || !sender->track()) {
1177 return RTCError::OK();
1178 }
1179 sender->SetTrack(nullptr);
1180 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1181 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1182 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1183 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1184 }
Steve Anton4171afb2017-11-20 10:20:22 -08001185 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001186 bool removed;
1187 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1188 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1189 } else {
1190 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1191 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1192 }
1193 if (!removed) {
1194 LOG_AND_RETURN_ERROR(
1195 RTCErrorType::INVALID_PARAMETER,
1196 "Couldn't find sender " + sender->id() + " to remove.");
1197 }
Steve Anton4171afb2017-11-20 10:20:22 -08001198 }
deadbeefe1f9d832016-01-14 15:35:42 -08001199 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001200 return RTCError::OK();
1201}
1202
1203rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1204PeerConnection::FindTransceiverBySender(
1205 rtc::scoped_refptr<RtpSenderInterface> sender) {
1206 for (auto transceiver : transceivers_) {
1207 if (transceiver->sender() == sender) {
1208 return transceiver;
1209 }
1210 }
1211 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001212}
1213
Steve Anton9158ef62017-11-27 13:01:52 -08001214RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1215PeerConnection::AddTransceiver(
1216 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1217 return AddTransceiver(track, RtpTransceiverInit());
1218}
1219
1220RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1221PeerConnection::AddTransceiver(
1222 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1223 const RtpTransceiverInit& init) {
1224 if (!IsUnifiedPlan()) {
1225 LOG_AND_RETURN_ERROR(
1226 RTCErrorType::INTERNAL_ERROR,
1227 "AddTransceiver only supported when Unified Plan is enabled.");
1228 }
1229 if (!track) {
1230 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1231 }
1232 cricket::MediaType media_type;
1233 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1234 media_type = cricket::MEDIA_TYPE_AUDIO;
1235 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1236 media_type = cricket::MEDIA_TYPE_VIDEO;
1237 } else {
1238 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1239 "Track kind is not audio or video");
1240 }
1241 return AddTransceiver(media_type, track, init);
1242}
1243
1244RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1245PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1246 return AddTransceiver(media_type, RtpTransceiverInit());
1247}
1248
1249RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1250PeerConnection::AddTransceiver(cricket::MediaType media_type,
1251 const RtpTransceiverInit& init) {
1252 if (!IsUnifiedPlan()) {
1253 LOG_AND_RETURN_ERROR(
1254 RTCErrorType::INTERNAL_ERROR,
1255 "AddTransceiver only supported when Unified Plan is enabled.");
1256 }
1257 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1258 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1260 "media type is not audio or video");
1261 }
1262 return AddTransceiver(media_type, nullptr, init);
1263}
1264
1265RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1266PeerConnection::AddTransceiver(
1267 cricket::MediaType media_type,
1268 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001269 const RtpTransceiverInit& init,
1270 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001271 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1272 media_type == cricket::MEDIA_TYPE_VIDEO));
1273 if (track) {
1274 RTC_DCHECK_EQ(media_type,
1275 (track->kind() == MediaStreamTrackInterface::kAudioKind
1276 ? cricket::MEDIA_TYPE_AUDIO
1277 : cricket::MEDIA_TYPE_VIDEO));
1278 }
1279
1280 // TODO(bugs.webrtc.org/7600): Verify init.
1281
Steve Anton02ee47c2018-01-10 16:26:06 -08001282 if (init.stream_labels.size() > 1u) {
1283 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1284 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001285 }
1286
Steve Anton02ee47c2018-01-10 16:26:06 -08001287 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1288 ? init.stream_labels[0]
1289 : rtc::CreateRandomUuid()};
1290
1291 auto sender = CreateSender(media_type, track, stream_labels);
1292 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1293 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1294 transceiver->internal()->set_direction(init.direction);
1295
Steve Anton22da89f2018-01-25 13:58:07 -08001296 if (fire_callback) {
1297 observer_->OnRenegotiationNeeded();
1298 }
Steve Antonf9381f02017-12-14 10:23:57 -08001299
1300 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1301}
1302
Steve Anton02ee47c2018-01-10 16:26:06 -08001303rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1304PeerConnection::CreateSender(
1305 cricket::MediaType media_type,
1306 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1307 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001308 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1310 RTC_DCHECK(!track ||
1311 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1312 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1313 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001314 new AudioRtpSender(worker_thread(),
1315 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001316 stream_labels, stats_.get()));
1317 } else {
1318 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1319 RTC_DCHECK(!track ||
1320 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1321 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1322 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001323 new VideoRtpSender(worker_thread(),
1324 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001325 stream_labels));
1326 }
1327 sender->internal()->set_stream_ids(stream_labels);
1328 return sender;
1329}
1330
1331rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1332PeerConnection::CreateReceiver(cricket::MediaType media_type,
1333 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001334 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1335 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001336 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001337 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001338 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001339 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001340 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001341 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001342 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1343 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001344 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001345 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001346 return receiver;
1347}
1348
1349rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1350PeerConnection::CreateAndAddTransceiver(
1351 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1352 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1353 receiver) {
1354 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1355 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001356 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001357 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001358}
1359
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001360rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001362 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001363 if (IsClosed()) {
1364 return nullptr;
1365 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001367 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001368 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 }
Steve Anton4171afb2017-11-20 10:20:22 -08001370 auto track_sender = FindSenderForTrack(track);
1371 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001372 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001373 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 }
1375
Steve Anton4171afb2017-11-20 10:20:22 -08001376 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377}
1378
deadbeeffac06552015-11-25 11:26:01 -08001379rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001380 const std::string& kind,
1381 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001382 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001383 if (IsClosed()) {
1384 return nullptr;
1385 }
Steve Anton4171afb2017-11-20 10:20:22 -08001386
Steve Anton02ee47c2018-01-10 16:26:06 -08001387 std::vector<std::string> stream_labels;
1388 if (!stream_id.empty()) {
1389 stream_labels.push_back(stream_id);
1390 }
1391
Steve Anton4171afb2017-11-20 10:20:22 -08001392 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001393 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001394 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001395 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1396 stream_labels, stats_.get());
1397 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001398 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001400 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001401 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001402 auto* video_sender =
1403 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1404 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001405 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001407 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001408 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001409 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001410 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001411 }
Steve Anton4171afb2017-11-20 10:20:22 -08001412
deadbeefe1f9d832016-01-14 15:35:42 -08001413 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001414}
1415
deadbeef70ab1a12015-09-28 16:53:55 -07001416std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1417 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001418 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001419 for (auto sender : GetSendersInternal()) {
1420 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001421 }
1422 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001423}
1424
Steve Anton4171afb2017-11-20 10:20:22 -08001425std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1426PeerConnection::GetSendersInternal() const {
1427 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1428 all_senders;
1429 for (auto transceiver : transceivers_) {
1430 auto senders = transceiver->internal()->senders();
1431 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1432 }
1433 return all_senders;
1434}
1435
deadbeef70ab1a12015-09-28 16:53:55 -07001436std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1437PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001438 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001439 for (const auto& receiver : GetReceiversInternal()) {
1440 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001441 }
1442 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001443}
1444
Steve Anton4171afb2017-11-20 10:20:22 -08001445std::vector<
1446 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1447PeerConnection::GetReceiversInternal() const {
1448 std::vector<
1449 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1450 all_receivers;
1451 for (auto transceiver : transceivers_) {
1452 auto receivers = transceiver->internal()->receivers();
1453 all_receivers.insert(all_receivers.end(), receivers.begin(),
1454 receivers.end());
1455 }
1456 return all_receivers;
1457}
1458
Steve Anton9158ef62017-11-27 13:01:52 -08001459std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1460PeerConnection::GetTransceivers() const {
1461 RTC_DCHECK(IsUnifiedPlan());
1462 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1463 for (auto transceiver : transceivers_) {
1464 all_transceivers.push_back(transceiver);
1465 }
1466 return all_transceivers;
1467}
1468
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001470 MediaStreamTrackInterface* track,
1471 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001472 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001473 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001474 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001475 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 return false;
1477 }
1478
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001479 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001480 // The StatsCollector is used to tell if a track is valid because it may
1481 // remember tracks that the PeerConnection previously removed.
1482 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001483 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1484 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001485 return false;
1486 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001487 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001488 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 return true;
1490}
1491
hbos74e1a4f2016-09-15 23:33:01 -07001492void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1493 RTC_DCHECK(stats_collector_);
1494 stats_collector_->GetStatsReport(callback);
1495}
1496
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1498 return signaling_state_;
1499}
1500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501PeerConnectionInterface::IceConnectionState
1502PeerConnection::ice_connection_state() {
1503 return ice_connection_state_;
1504}
1505
1506PeerConnectionInterface::IceGatheringState
1507PeerConnection::ice_gathering_state() {
1508 return ice_gathering_state_;
1509}
1510
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001511rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512PeerConnection::CreateDataChannel(
1513 const std::string& label,
1514 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001515 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001516
deadbeefab9b2d12015-10-14 11:33:11 -07001517 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001518
kwibergd1fe2812016-04-27 06:47:29 -07001519 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001520 if (config) {
1521 internal_config.reset(new InternalDataChannelInit(*config));
1522 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001523 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001524 InternalCreateDataChannel(label, internal_config.get()));
1525 if (!channel.get()) {
1526 return nullptr;
1527 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001529 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1530 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001531 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001532 observer_->OnRenegotiationNeeded();
1533 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535 return DataChannelProxy::Create(signaling_thread(), channel.get());
1536}
1537
1538void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1539 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001540 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001541
zhihuang1c378ed2017-08-17 14:10:50 -07001542 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1543 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1544 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1545 // compares the mandatory fields parsed with the mandatory fields added in the
1546 // |constraints| and some downstream applications might create offers with
1547 // mandatory fields which would not be parsed in the helper method. For
1548 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1549 // |constraints| as a mandatory field but it is not parsed.
1550 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001551
zhihuang1c378ed2017-08-17 14:10:50 -07001552 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001553}
1554
1555void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1556 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001557 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001558
nisse7ce109a2017-01-31 00:57:56 -08001559 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001560 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001561 return;
1562 }
deadbeefab9b2d12015-10-14 11:33:11 -07001563
Steve Anton8d3444d2017-10-20 15:30:51 -07001564 if (IsClosed()) {
1565 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001566 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001567 PostCreateSessionDescriptionFailure(observer, error);
1568 return;
1569 }
1570
zhihuang1c378ed2017-08-17 14:10:50 -07001571 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001572 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001573 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001574 PostCreateSessionDescriptionFailure(observer, error);
1575 return;
1576 }
1577
Steve Anton22da89f2018-01-25 13:58:07 -08001578 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1579 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1580 if (IsUnifiedPlan()) {
1581 RTCError error = HandleLegacyOfferOptions(options);
1582 if (!error.ok()) {
1583 PostCreateSessionDescriptionFailure(observer, error.message());
1584 return;
1585 }
1586 }
1587
zhihuang1c378ed2017-08-17 14:10:50 -07001588 cricket::MediaSessionOptions session_options;
1589 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001590 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591}
1592
Steve Anton22da89f2018-01-25 13:58:07 -08001593RTCError PeerConnection::HandleLegacyOfferOptions(
1594 const RTCOfferAnswerOptions& options) {
1595 RTC_DCHECK(IsUnifiedPlan());
1596
1597 if (options.offer_to_receive_audio == 0) {
1598 RemoveRecvDirectionFromReceivingTransceiversOfType(
1599 cricket::MEDIA_TYPE_AUDIO);
1600 } else if (options.offer_to_receive_audio == 1) {
1601 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1602 } else if (options.offer_to_receive_audio > 1) {
1603 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1604 "offer_to_receive_audio > 1 is not supported.");
1605 }
1606
1607 if (options.offer_to_receive_video == 0) {
1608 RemoveRecvDirectionFromReceivingTransceiversOfType(
1609 cricket::MEDIA_TYPE_VIDEO);
1610 } else if (options.offer_to_receive_video == 1) {
1611 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1612 } else if (options.offer_to_receive_video > 1) {
1613 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1614 "offer_to_receive_video > 1 is not supported.");
1615 }
1616
1617 return RTCError::OK();
1618}
1619
1620void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1621 cricket::MediaType media_type) {
1622 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1623 transceiver->internal()->set_direction(
1624 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1625 }
1626}
1627
1628void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1629 cricket::MediaType media_type) {
1630 if (GetReceivingTransceiversOfType(media_type).empty()) {
1631 RtpTransceiverInit init;
1632 init.direction = RtpTransceiverDirection::kRecvOnly;
1633 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1634 }
1635}
1636
1637std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1638PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1639 std::vector<
1640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1641 receiving_transceivers;
1642 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001643 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001644 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1645 receiving_transceivers.push_back(transceiver);
1646 }
1647 }
1648 return receiving_transceivers;
1649}
1650
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651void PeerConnection::CreateAnswer(
1652 CreateSessionDescriptionObserver* observer,
1653 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001654 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001655
nisse7ce109a2017-01-31 00:57:56 -08001656 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001657 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001658 return;
1659 }
deadbeefab9b2d12015-10-14 11:33:11 -07001660
zhihuang1c378ed2017-08-17 14:10:50 -07001661 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1662 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1663 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001664 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001665 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001666 PostCreateSessionDescriptionFailure(observer, error);
1667 return;
1668 }
1669
Steve Anton8d3444d2017-10-20 15:30:51 -07001670 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001671}
1672
1673void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1674 const RTCOfferAnswerOptions& options) {
1675 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001676 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001677 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001678 return;
1679 }
1680
Steve Antondffead82018-02-06 10:31:29 -08001681 if (!(signaling_state_ == kHaveRemoteOffer ||
1682 signaling_state_ == kHaveLocalPrAnswer)) {
1683 std::string error =
1684 "PeerConnection cannot create an answer in a state other than "
1685 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001686 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001687 PostCreateSessionDescriptionFailure(observer, error);
1688 return;
1689 }
1690
Steve Antondffead82018-02-06 10:31:29 -08001691 // The remote description should be set if we're in the right state.
1692 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001693
Steve Anton22da89f2018-01-25 13:58:07 -08001694 if (IsUnifiedPlan()) {
1695 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1696 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1697 "supported with Unified Plan semantics. Use the "
1698 "RtpTransceiver API instead.";
1699 }
1700 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1701 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1702 "supported with Unified Plan semantics. Use the "
1703 "RtpTransceiver API instead.";
1704 }
1705 }
1706
htaa2a49d92016-03-04 02:51:39 -08001707 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001708 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001709
Steve Antond25da372017-11-06 14:50:29 -08001710 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711}
1712
1713void PeerConnection::SetLocalDescription(
1714 SetSessionDescriptionObserver* observer,
1715 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001716 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001717
nisse7ce109a2017-01-31 00:57:56 -08001718 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001719 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001720 return;
1721 }
Steve Anton8a006912017-12-04 15:25:56 -08001722
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723 if (!desc) {
1724 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1725 return;
1726 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
Steve Antona3a92c22017-12-07 10:27:41 -08001728 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001729
Steve Anton8a006912017-12-04 15:25:56 -08001730 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1731 // |desc| may be destroyed at this point.
1732
1733 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001734 std::ostringstream oss;
1735 oss << "Failed to set local " << SdpTypeToString(type)
1736 << " sdp: " << error.message();
1737 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001738 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1739 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001740 return;
1741 }
Steve Anton8a006912017-12-04 15:25:56 -08001742 RTC_DCHECK(local_description());
1743
1744 PostSetSessionDescriptionSuccess(observer);
1745
1746 // According to JSEP, after setLocalDescription, changing the candidate pool
1747 // size is not allowed, and changing the set of ICE servers will not result
1748 // in new candidates being gathered.
1749 port_allocator_->FreezeCandidatePool();
1750
1751 // MaybeStartGathering needs to be called after posting
1752 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1753 // before signaling that SetLocalDescription completed.
1754 transport_controller_->MaybeStartGathering();
1755
Steve Antona3a92c22017-12-07 10:27:41 -08001756 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001757 // TODO(deadbeef): We already had to hop to the network thread for
1758 // MaybeStartGathering...
1759 network_thread()->Invoke<void>(
1760 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1761 port_allocator_.get()));
1762 }
1763}
1764
1765RTCError PeerConnection::ApplyLocalDescription(
1766 std::unique_ptr<SessionDescriptionInterface> desc) {
1767 RTC_DCHECK_RUN_ON(signaling_thread());
1768 RTC_DCHECK(desc);
1769
1770 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1771 if (!error.ok()) {
1772 return error;
1773 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001774
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775 // Update stats here so that we have the most recent stats for tracks and
1776 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001777 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001778
1779 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001780 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001781 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001782 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001783 if (*initial_offerer_) {
1784 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1785 } else {
1786 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1787 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788 }
Steve Anton8a006912017-12-04 15:25:56 -08001789
Steve Antondcc3c022017-12-22 16:02:54 -08001790 // Take a reference to the old local description since it's used below to
1791 // compare against the new local description. When setting the new local
1792 // description, grab ownership of the replaced session description in case it
1793 // is the same as |old_local_description|, to keep it alive for the duration
1794 // of the method.
1795 const SessionDescriptionInterface* old_local_description =
1796 local_description();
1797 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001798 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001799 replaced_local_description = pending_local_description_
1800 ? std::move(pending_local_description_)
1801 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001802 current_local_description_ = std::move(desc);
1803 pending_local_description_ = nullptr;
1804 current_remote_description_ = std::move(pending_remote_description_);
1805 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001806 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001807 pending_local_description_ = std::move(desc);
1808 }
1809 // The session description to apply now must be accessed by
1810 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001811 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001812
Steve Antondcc3c022017-12-22 16:02:54 -08001813 if (IsUnifiedPlan()) {
1814 RTCError error = UpdateTransceiversAndDataChannels(
1815 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001816 if (!error.ok()) {
1817 return error;
1818 }
Steve Antondcc3c022017-12-22 16:02:54 -08001819 for (auto transceiver : transceivers_) {
1820 const ContentInfo* content =
1821 FindMediaSectionForTransceiver(transceiver, local_description());
1822 if (!content) {
1823 continue;
1824 }
1825 const MediaContentDescription* media_desc = content->media_description();
1826 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1827 transceiver->internal()->set_current_direction(media_desc->direction());
1828 }
1829 if (content->rejected && !transceiver->stopped()) {
1830 transceiver->Stop();
1831 }
1832 }
1833 } else {
1834 // Transport and Media channels will be created only when offer is set.
1835 if (type == SdpType::kOffer) {
1836 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1837 // description is applied. Restore back to old description.
1838 RTCError error = CreateChannels(*local_description()->description());
1839 if (!error.ok()) {
1840 return error;
1841 }
1842 }
Steve Anton8a006912017-12-04 15:25:56 -08001843
Steve Antondcc3c022017-12-22 16:02:54 -08001844 // Remove unused channels if MediaContentDescription is rejected.
1845 RemoveUnusedChannels(local_description()->description());
1846 }
Steve Anton8a006912017-12-04 15:25:56 -08001847
Steve Anton3828c062017-12-06 10:34:51 -08001848 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001849 if (!error.ok()) {
1850 return error;
1851 }
Steve Antondcc3c022017-12-22 16:02:54 -08001852
Steve Anton8a006912017-12-04 15:25:56 -08001853 if (remote_description()) {
1854 // Now that we have a local description, we can push down remote candidates.
1855 UseCandidatesInSessionDescription(remote_description());
1856 }
1857
1858 pending_ice_restarts_.clear();
1859 if (session_error() != SessionError::kNone) {
1860 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1861 }
1862
deadbeefab9b2d12015-10-14 11:33:11 -07001863 // If setting the description decided our SSL role, allocate any necessary
1864 // SCTP sids.
1865 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001866 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001867 AllocateSctpSids(role);
1868 }
1869
Steve Antond3679212018-01-17 17:41:02 -08001870 if (IsUnifiedPlan()) {
1871 for (auto transceiver : transceivers_) {
1872 const ContentInfo* content =
1873 FindMediaSectionForTransceiver(transceiver, local_description());
1874 if (!content) {
1875 continue;
1876 }
1877 if (content->rejected && !transceiver->stopped()) {
1878 transceiver->Stop();
1879 }
Steve Anton74255ff2018-01-24 18:32:57 -08001880 const auto& streams = content->media_description()->streams();
1881 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001882 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001883 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001884 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001885 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001886 }
1887 }
1888 } else {
1889 // Plan B semantics.
1890
Steve Antondcc3c022017-12-22 16:02:54 -08001891 // Update state and SSRC of local MediaStreams and DataChannels based on the
1892 // local session description.
1893 const cricket::ContentInfo* audio_content =
1894 GetFirstAudioContent(local_description()->description());
1895 if (audio_content) {
1896 if (audio_content->rejected) {
1897 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1898 } else {
1899 const cricket::AudioContentDescription* audio_desc =
1900 audio_content->media_description()->as_audio();
1901 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1902 }
deadbeeffaac4972015-11-12 15:33:07 -08001903 }
deadbeefab9b2d12015-10-14 11:33:11 -07001904
Steve Antondcc3c022017-12-22 16:02:54 -08001905 const cricket::ContentInfo* video_content =
1906 GetFirstVideoContent(local_description()->description());
1907 if (video_content) {
1908 if (video_content->rejected) {
1909 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1910 } else {
1911 const cricket::VideoContentDescription* video_desc =
1912 video_content->media_description()->as_video();
1913 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1914 }
deadbeeffaac4972015-11-12 15:33:07 -08001915 }
deadbeefab9b2d12015-10-14 11:33:11 -07001916 }
1917
1918 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001919 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001920 if (data_content) {
1921 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001922 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001923 if (rtc::starts_with(data_desc->protocol().data(),
1924 cricket::kMediaProtocolRtpPrefix)) {
1925 UpdateLocalRtpDataChannels(data_desc->streams());
1926 }
1927 }
1928
Steve Anton8a006912017-12-04 15:25:56 -08001929 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930}
1931
1932void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001933 SetSessionDescriptionObserver* observer,
1934 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001935 SetRemoteDescription(
1936 std::unique_ptr<SessionDescriptionInterface>(desc),
1937 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1938 new SetRemoteDescriptionObserverAdapter(this, observer)));
1939}
1940
1941void PeerConnection::SetRemoteDescription(
1942 std::unique_ptr<SessionDescriptionInterface> desc,
1943 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001944 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001945
nisse7ce109a2017-01-31 00:57:56 -08001946 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001947 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948 return;
1949 }
Steve Anton8a006912017-12-04 15:25:56 -08001950
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001952 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001953 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 return;
1955 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
Steve Antona3a92c22017-12-07 10:27:41 -08001957 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001958
1959 RTCError error = ApplyRemoteDescription(std::move(desc));
1960 // |desc| may be destroyed at this point.
1961
1962 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001963 std::ostringstream oss;
1964 oss << "Failed to set remote " << SdpTypeToString(type)
1965 << " sdp: " << error.message();
1966 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001967 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001968 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001969 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001970 return;
1971 }
1972
Steve Antona3a92c22017-12-07 10:27:41 -08001973 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001974 // TODO(deadbeef): We already had to hop to the network thread for
1975 // MaybeStartGathering...
1976 network_thread()->Invoke<void>(
1977 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1978 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01001979 // Make UMA notes about what was agreed to.
1980 if (uma_observer_) {
1981 switch (remote_description()->description()->msid_signaling()) {
1982 case 0:
1983 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
1984 kSdpSemanticNegotiatedNone,
1985 kSdpSemanticNegotiatedMax);
1986 break;
1987 case cricket::kMsidSignalingMediaSection:
1988 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
1989 kSdpSemanticNegotiatedUnifiedPlan,
1990 kSdpSemanticNegotiatedMax);
1991 break;
1992 case cricket::kMsidSignalingSsrcAttribute:
1993 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
1994 kSdpSemanticNegotiatedPlanB,
1995 kSdpSemanticNegotiatedMax);
1996 break;
1997 case cricket::kMsidSignalingMediaSection |
1998 cricket::kMsidSignalingSsrcAttribute:
1999 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2000 kSdpSemanticNegotiatedMixed,
2001 kSdpSemanticNegotiatedMax);
2002 break;
2003 default:
2004 RTC_NOTREACHED();
2005 }
2006 }
Steve Anton8a006912017-12-04 15:25:56 -08002007 }
2008
2009 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2010}
2011
2012RTCError PeerConnection::ApplyRemoteDescription(
2013 std::unique_ptr<SessionDescriptionInterface> desc) {
2014 RTC_DCHECK_RUN_ON(signaling_thread());
2015 RTC_DCHECK(desc);
2016
2017 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
2018 if (!error.ok()) {
2019 return error;
2020 }
2021
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022 // Update stats here so that we have the most recent stats for tracks and
2023 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002024 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002025
Steve Antondcc3c022017-12-22 16:02:54 -08002026 // Take a reference to the old remote description since it's used below to
2027 // compare against the new remote description. When setting the new remote
2028 // description, grab ownership of the replaced session description in case it
2029 // is the same as |old_remote_description|, to keep it alive for the duration
2030 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002031 const SessionDescriptionInterface* old_remote_description =
2032 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002033 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002034 SdpType type = desc->GetType();
2035 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002036 replaced_remote_description = pending_remote_description_
2037 ? std::move(pending_remote_description_)
2038 : std::move(current_remote_description_);
2039 current_remote_description_ = std::move(desc);
2040 pending_remote_description_ = nullptr;
2041 current_local_description_ = std::move(pending_local_description_);
2042 } else {
2043 replaced_remote_description = std::move(pending_remote_description_);
2044 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 }
Steve Anton8a006912017-12-04 15:25:56 -08002046 // The session description to apply now must be accessed by
2047 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002048 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049
Steve Anton8a006912017-12-04 15:25:56 -08002050 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002051 if (IsUnifiedPlan()) {
2052 RTCError error = UpdateTransceiversAndDataChannels(
2053 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002054 if (!error.ok()) {
2055 return error;
2056 }
Steve Antondcc3c022017-12-22 16:02:54 -08002057 } else {
2058 if (type == SdpType::kOffer) {
2059 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2060 // description is applied. Restore back to old description.
2061 RTCError error = CreateChannels(*remote_description()->description());
2062 if (!error.ok()) {
2063 return error;
2064 }
2065 }
Steve Anton8a006912017-12-04 15:25:56 -08002066
Steve Antondcc3c022017-12-22 16:02:54 -08002067 // Remove unused channels if MediaContentDescription is rejected.
2068 RemoveUnusedChannels(remote_description()->description());
2069 }
Steve Anton8a006912017-12-04 15:25:56 -08002070
2071 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2072 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002073 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002074 if (!error.ok()) {
2075 return error;
2076 }
2077
2078 if (local_description() &&
2079 !UseCandidatesInSessionDescription(remote_description())) {
2080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2081 }
2082
2083 if (old_remote_description) {
2084 for (const cricket::ContentInfo& content :
2085 old_remote_description->description()->contents()) {
2086 // Check if this new SessionDescription contains new ICE ufrag and
2087 // password that indicates the remote peer requests an ICE restart.
2088 // TODO(deadbeef): When we start storing both the current and pending
2089 // remote description, this should reset pending_ice_restarts and compare
2090 // against the current description.
2091 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2092 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002093 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002094 pending_ice_restarts_.insert(content.name);
2095 }
2096 } else {
2097 // We retain all received candidates only if ICE is not restarted.
2098 // When ICE is restarted, all previous candidates belong to an old
2099 // generation and should not be kept.
2100 // TODO(deadbeef): This goes against the W3C spec which says the remote
2101 // description should only contain candidates from the last set remote
2102 // description plus any candidates added since then. We should remove
2103 // this once we're sure it won't break anything.
2104 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2105 old_remote_description, content.name, mutable_remote_description());
2106 }
2107 }
2108 }
2109
2110 if (session_error() != SessionError::kNone) {
2111 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2112 }
2113
2114 // Set the the ICE connection state to connecting since the connection may
2115 // become writable with peer reflexive candidates before any remote candidate
2116 // is signaled.
2117 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2118 // is to have a new signal the indicates a change in checking state from the
2119 // transport and expose a new checking() member from transport that can be
2120 // read to determine the current checking state. The existing SignalConnecting
2121 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002122 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002123 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2124 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2125 }
2126
deadbeefab9b2d12015-10-14 11:33:11 -07002127 // If setting the description decided our SSL role, allocate any necessary
2128 // SCTP sids.
2129 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002130 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002131 AllocateSctpSids(role);
2132 }
2133
Steve Antondcc3c022017-12-22 16:02:54 -08002134 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002135 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002136 for (auto transceiver : transceivers_) {
2137 const ContentInfo* content =
2138 FindMediaSectionForTransceiver(transceiver, remote_description());
2139 if (!content) {
2140 continue;
2141 }
2142 const MediaContentDescription* media_desc = content->media_description();
2143 RtpTransceiverDirection local_direction =
2144 RtpTransceiverDirectionReversed(media_desc->direction());
2145 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2146 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2147 // transceiver's current direction is neither sendrecv nor recvonly,
2148 // process the addition of a remote track for the media description.
2149 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2150 (!transceiver->current_direction() ||
2151 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002152 *transceiver->current_direction())) &&
2153 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002154 const std::string& sync_label = media_desc->streams()[0].sync_label;
2155 rtc::scoped_refptr<MediaStreamInterface> stream =
2156 remote_streams_->find(sync_label);
2157 if (!stream) {
2158 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2159 MediaStream::Create(sync_label));
2160 remote_streams_->AddStream(stream);
2161 }
2162 transceiver->internal()->receiver_internal()->SetStreams({stream});
2163 TrackEvent track_event;
2164 track_event.receiver = transceiver->receiver();
2165 track_event.streams = transceiver->receiver()->streams();
2166 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002167 }
2168 // If direction is sendonly or inactive, and transceiver's current
2169 // direction is neither sendonly nor inactive, process the removal of a
2170 // remote track for the media description.
2171 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002172 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002173 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002174 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002175 }
2176 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2177 transceiver->internal()->set_current_direction(local_direction);
2178 }
2179 if (content->rejected && !transceiver->stopped()) {
2180 transceiver->Stop();
2181 }
Steve Anton74255ff2018-01-24 18:32:57 -08002182 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002183 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002184 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002185 }
Steve Antondcc3c022017-12-22 16:02:54 -08002186 }
Steve Antonef65ef12018-01-10 17:15:20 -08002187 for (auto event : track_events) {
2188 observer_->OnAddTrack(event.receiver, event.streams);
2189 }
Steve Antondcc3c022017-12-22 16:02:54 -08002190 }
2191
Henrik Boströmfdb92012017-11-09 19:55:44 +01002192 const cricket::ContentInfo* audio_content =
2193 GetFirstAudioContent(remote_description()->description());
2194 const cricket::ContentInfo* video_content =
2195 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002196 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002197 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002198 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002199 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002200 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002201 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002202
2203 // Check if the descriptions include streams, just in case the peer supports
2204 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002205 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002206 (audio_desc && !audio_desc->streams().empty()) ||
2207 (video_desc && !video_desc->streams().empty())) {
2208 remote_peer_supports_msid_ = true;
2209 }
deadbeefab9b2d12015-10-14 11:33:11 -07002210
2211 // We wait to signal new streams until we finish processing the description,
2212 // since only at that point will new streams have all their tracks.
2213 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 if (!IsUnifiedPlan()) {
2216 // TODO(steveanton): When removing RTP senders/receivers in response to a
2217 // rejected media section, there is some cleanup logic that expects the
2218 // voice/ video channel to still be set. But in this method the voice/video
2219 // channel would have been destroyed by the SetRemoteDescription caller
2220 // above so the cleanup that relies on them fails to run. The RemoveSenders
2221 // calls should be moved to right before the DestroyChannel calls to fix
2222 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002223
Steve Antondcc3c022017-12-22 16:02:54 -08002224 // Find all audio rtp streams and create corresponding remote AudioTracks
2225 // and MediaStreams.
2226 if (audio_content) {
2227 if (audio_content->rejected) {
2228 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2229 } else {
2230 bool default_audio_track_needed =
2231 !remote_peer_supports_msid_ &&
2232 RtpTransceiverDirectionHasSend(audio_desc->direction());
2233 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2234 default_audio_track_needed, audio_desc->type(),
2235 new_streams);
2236 }
deadbeeffaac4972015-11-12 15:33:07 -08002237 }
deadbeefab9b2d12015-10-14 11:33:11 -07002238
Steve Antondcc3c022017-12-22 16:02:54 -08002239 // Find all video rtp streams and create corresponding remote VideoTracks
2240 // and MediaStreams.
2241 if (video_content) {
2242 if (video_content->rejected) {
2243 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2244 } else {
2245 bool default_video_track_needed =
2246 !remote_peer_supports_msid_ &&
2247 RtpTransceiverDirectionHasSend(video_desc->direction());
2248 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2249 default_video_track_needed, video_desc->type(),
2250 new_streams);
2251 }
deadbeeffaac4972015-11-12 15:33:07 -08002252 }
deadbeefab9b2d12015-10-14 11:33:11 -07002253
Steve Antondcc3c022017-12-22 16:02:54 -08002254 // Update the DataChannels with the information from the remote peer.
2255 if (data_desc) {
2256 if (rtc::starts_with(data_desc->protocol().data(),
2257 cricket::kMediaProtocolRtpPrefix)) {
2258 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2259 }
deadbeefab9b2d12015-10-14 11:33:11 -07002260 }
deadbeefab9b2d12015-10-14 11:33:11 -07002261
Steve Antondcc3c022017-12-22 16:02:54 -08002262 // Iterate new_streams and notify the observer about new MediaStreams.
2263 for (size_t i = 0; i < new_streams->count(); ++i) {
2264 MediaStreamInterface* new_stream = new_streams->at(i);
2265 stats_->AddStream(new_stream);
2266 observer_->OnAddStream(
2267 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2268 }
deadbeefab9b2d12015-10-14 11:33:11 -07002269
Steve Antondcc3c022017-12-22 16:02:54 -08002270 UpdateEndedRemoteMediaStreams();
2271 }
deadbeefab9b2d12015-10-14 11:33:11 -07002272
Steve Anton8a006912017-12-04 15:25:56 -08002273 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002274}
2275
Steve Antondcc3c022017-12-22 16:02:54 -08002276RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2277 cricket::ContentSource source,
2278 const SessionDescriptionInterface* old_session,
2279 const SessionDescriptionInterface& new_session) {
2280 RTC_DCHECK(IsUnifiedPlan());
2281
Steve Anton7464fca2018-01-19 11:10:37 -08002282 const cricket::ContentGroup* bundle_group = nullptr;
2283 if (new_session.GetType() == SdpType::kOffer) {
2284 auto bundle_group_or_error =
2285 GetEarlyBundleGroup(*new_session.description());
2286 if (!bundle_group_or_error.ok()) {
2287 return bundle_group_or_error.MoveError();
2288 }
2289 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002290 }
Steve Antondcc3c022017-12-22 16:02:54 -08002291
2292 const ContentInfos& old_contents =
2293 (old_session ? old_session->description()->contents() : ContentInfos());
2294 const ContentInfos& new_contents = new_session.description()->contents();
2295
2296 for (size_t i = 0; i < new_contents.size(); ++i) {
2297 const cricket::ContentInfo& new_content = new_contents[i];
2298 const cricket::ContentInfo* old_content =
2299 (i < old_contents.size() ? &old_contents[i] : nullptr);
2300 cricket::MediaType media_type = new_content.media_description()->type();
2301 seen_mids_.insert(new_content.name);
2302 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2303 media_type == cricket::MEDIA_TYPE_VIDEO) {
2304 auto transceiver_or_error =
2305 AssociateTransceiver(source, i, new_content, old_content);
2306 if (!transceiver_or_error.ok()) {
2307 return transceiver_or_error.MoveError();
2308 }
2309 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002310 RTCError error =
2311 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2312 if (!error.ok()) {
2313 return error;
2314 }
2315 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002316 if (GetDataMid() && new_content.name != *GetDataMid()) {
2317 // Ignore all but the first data section.
2318 continue;
2319 }
2320 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2321 if (!error.ok()) {
2322 return error;
2323 }
Steve Antondcc3c022017-12-22 16:02:54 -08002324 } else {
2325 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2326 "Unknown section type.");
2327 }
2328 }
2329
2330 return RTCError::OK();
2331}
2332
2333RTCError PeerConnection::UpdateTransceiverChannel(
2334 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2335 transceiver,
2336 const cricket::ContentInfo& content,
2337 const cricket::ContentGroup* bundle_group) {
2338 RTC_DCHECK(IsUnifiedPlan());
2339 RTC_DCHECK(transceiver);
2340 cricket::BaseChannel* channel = transceiver->internal()->channel();
2341 if (content.rejected) {
2342 if (channel) {
2343 transceiver->internal()->SetChannel(nullptr);
2344 DestroyBaseChannel(channel);
2345 }
2346 } else {
2347 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002348 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002349 channel = CreateVoiceChannel(
2350 content.name,
2351 GetTransportNameForMediaSection(content.name, bundle_group));
2352 } else {
Steve Anton69470252018-02-09 11:43:08 -08002353 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002354 channel = CreateVideoChannel(
2355 content.name,
2356 GetTransportNameForMediaSection(content.name, bundle_group));
2357 }
2358 if (!channel) {
2359 LOG_AND_RETURN_ERROR(
2360 RTCErrorType::INTERNAL_ERROR,
2361 "Failed to create channel for mid=" + content.name);
2362 }
2363 transceiver->internal()->SetChannel(channel);
2364 }
2365 }
2366 return RTCError::OK();
2367}
2368
Steve Antonfa2260d2017-12-28 16:38:23 -08002369RTCError PeerConnection::UpdateDataChannel(
2370 cricket::ContentSource source,
2371 const cricket::ContentInfo& content,
2372 const cricket::ContentGroup* bundle_group) {
2373 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002374 // If data channels are disabled, ignore this media section. CreateAnswer
2375 // will take care of rejecting it.
2376 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002377 }
2378 if (content.rejected) {
2379 DestroyDataChannel();
2380 } else {
2381 if (!rtp_data_channel_ && !sctp_transport_) {
2382 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2383 content.name, bundle_group))) {
2384 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2385 "Failed to create data channel.");
2386 }
2387 }
2388 if (source == cricket::CS_REMOTE) {
2389 const MediaContentDescription* data_desc = content.media_description();
2390 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2391 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2392 }
2393 }
2394 }
2395 return RTCError::OK();
2396}
2397
Steve Antondcc3c022017-12-22 16:02:54 -08002398RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2399PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2400 size_t mline_index,
2401 const ContentInfo& content,
2402 const ContentInfo* old_content) {
2403 RTC_DCHECK(IsUnifiedPlan());
2404 // If the m= section is being recycled (rejected in previous remote
2405 // description, not rejected in current description), dissociate the currently
2406 // associated RtpTransceiver by setting its mid property to null, and discard
2407 // the mapping between the transceiver and its m= section index.
2408 if (old_content && old_content->rejected && !content.rejected) {
2409 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2410 if (old_transceiver) {
2411 old_transceiver->internal()->set_mid(rtc::nullopt);
2412 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2413 }
2414 }
2415 const MediaContentDescription* media_desc = content.media_description();
2416 auto transceiver = GetAssociatedTransceiver(content.name);
2417 if (source == cricket::CS_LOCAL) {
2418 // Find the RtpTransceiver that corresponds to this m= section, using the
2419 // mapping between transceivers and m= section indices established when
2420 // creating the offer.
2421 if (!transceiver) {
2422 transceiver = GetTransceiverByMLineIndex(mline_index);
2423 }
2424 if (!transceiver) {
2425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2426 "Unknown transceiver");
2427 }
2428 } else {
2429 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2430 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2431 // of the same type...
2432 if (!transceiver &&
2433 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2434 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2435 }
2436 // If no RtpTransceiver was found in the previous step, create one with a
2437 // recvonly direction.
2438 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002439 auto sender =
2440 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002441 std::string receiver_id;
2442 if (!media_desc->streams().empty()) {
2443 receiver_id = media_desc->streams()[0].id;
2444 } else {
2445 receiver_id = rtc::CreateRandomUuid();
2446 }
2447 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002448 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002449 transceiver->internal()->set_direction(
2450 RtpTransceiverDirection::kRecvOnly);
2451 }
2452 }
2453 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002454 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002455 LOG_AND_RETURN_ERROR(
2456 RTCErrorType::INVALID_PARAMETER,
2457 "Transceiver type does not match media description type.");
2458 }
2459 // Associate the found or created RtpTransceiver with the m= section by
2460 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2461 // section, and establish a mapping between the transceiver and the index of
2462 // the m= section.
2463 transceiver->internal()->set_mid(content.name);
2464 transceiver->internal()->set_mline_index(mline_index);
2465 return std::move(transceiver);
2466}
2467
2468rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2469PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2470 RTC_DCHECK(IsUnifiedPlan());
2471 for (auto transceiver : transceivers_) {
2472 if (transceiver->mid() == mid) {
2473 return transceiver;
2474 }
2475 }
2476 return nullptr;
2477}
2478
2479rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2480PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2481 RTC_DCHECK(IsUnifiedPlan());
2482 for (auto transceiver : transceivers_) {
2483 if (transceiver->internal()->mline_index() == mline_index) {
2484 return transceiver;
2485 }
2486 }
2487 return nullptr;
2488}
2489
2490rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2491PeerConnection::FindAvailableTransceiverToReceive(
2492 cricket::MediaType media_type) const {
2493 RTC_DCHECK(IsUnifiedPlan());
2494 // From JSEP section 5.10 (Applying a Remote Description):
2495 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2496 // the same type that were added to the PeerConnection by addTrack and are not
2497 // associated with any m= section and are not stopped, find the first such
2498 // RtpTransceiver.
2499 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002500 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002501 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2502 !transceiver->stopped()) {
2503 return transceiver;
2504 }
2505 }
2506 return nullptr;
2507}
2508
Steve Antoned10bd92017-12-05 10:52:59 -08002509const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2510 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2511 transceiver,
2512 const SessionDescriptionInterface* sdesc) const {
2513 RTC_DCHECK(transceiver);
2514 RTC_DCHECK(sdesc);
2515 if (IsUnifiedPlan()) {
2516 if (!transceiver->internal()->mid()) {
2517 // This transceiver is not associated with a media section yet.
2518 return nullptr;
2519 }
2520 return sdesc->description()->GetContentByName(
2521 *transceiver->internal()->mid());
2522 } else {
2523 // Plan B only allows at most one audio and one video section, so use the
2524 // first media section of that type.
2525 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002526 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002527 }
2528}
2529
deadbeef46c73892016-11-16 19:42:04 -08002530PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2531 return configuration_;
2532}
2533
deadbeef293e9262017-01-11 12:28:30 -08002534bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2535 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002536 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002537
Steve Anton75737c02017-11-06 10:37:17 -08002538 if (local_description() && configuration.ice_candidate_pool_size !=
2539 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002540 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2541 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002542 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002543 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002544
deadbeef293e9262017-01-11 12:28:30 -08002545 // The simplest (and most future-compatible) way to tell if the config was
2546 // modified in an invalid way is to copy each property we do support
2547 // modifying, then use operator==. There are far more properties we don't
2548 // support modifying than those we do, and more could be added.
2549 RTCConfiguration modified_config = configuration_;
2550 modified_config.servers = configuration.servers;
2551 modified_config.type = configuration.type;
2552 modified_config.ice_candidate_pool_size =
2553 configuration.ice_candidate_pool_size;
2554 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002555 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002556 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002557 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002558 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002559 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002560 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2561 }
2562
Steve Anton038834f2017-07-14 15:59:59 -07002563 // Validate the modified configuration.
2564 RTCError validate_error = ValidateConfiguration(modified_config);
2565 if (!validate_error.ok()) {
2566 return SafeSetError(std::move(validate_error), error);
2567 }
2568
deadbeef293e9262017-01-11 12:28:30 -08002569 // Note that this isn't possible through chromium, since it's an unsigned
2570 // short in WebIDL.
2571 if (configuration.ice_candidate_pool_size < 0 ||
2572 configuration.ice_candidate_pool_size > UINT16_MAX) {
2573 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2574 }
2575
2576 // Parse ICE servers before hopping to network thread.
2577 cricket::ServerAddresses stun_servers;
2578 std::vector<cricket::RelayServerConfig> turn_servers;
2579 RTCErrorType parse_error =
2580 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2581 if (parse_error != RTCErrorType::NONE) {
2582 return SafeSetError(parse_error, error);
2583 }
2584
2585 // In theory this shouldn't fail.
2586 if (!network_thread()->Invoke<bool>(
2587 RTC_FROM_HERE,
2588 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2589 stun_servers, turn_servers, modified_config.type,
2590 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002591 modified_config.prune_turn_ports,
2592 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002593 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002594 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2595 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002596
deadbeefd1a38b52016-12-10 13:15:33 -08002597 // As described in JSEP, calling setConfiguration with new ICE servers or
2598 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2599 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002600 if (modified_config.servers != configuration_.servers ||
2601 modified_config.type != configuration_.type ||
2602 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002603 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002604 }
skvladd1f5fda2017-02-03 16:54:05 -08002605
2606 if (modified_config.ice_check_min_interval !=
2607 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002608 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002609 }
2610
deadbeef293e9262017-01-11 12:28:30 -08002611 configuration_ = modified_config;
2612 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002613}
2614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615bool PeerConnection::AddIceCandidate(
2616 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002617 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002618 if (IsClosed()) {
2619 return false;
2620 }
Steve Antond25da372017-11-06 14:50:29 -08002621
2622 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002623 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002624 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002625 return false;
2626 }
2627
2628 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002629 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002630 return false;
2631 }
2632
2633 bool valid = false;
2634 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2635 if (!valid) {
2636 return false;
2637 }
2638
2639 // Add this candidate to the remote session description.
2640 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002641 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002642 return false;
2643 }
2644
2645 if (ready) {
2646 return UseCandidate(ice_candidate);
2647 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002648 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002649 return true;
2650 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002651}
2652
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002653bool PeerConnection::RemoveIceCandidates(
2654 const std::vector<cricket::Candidate>& candidates) {
2655 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002656 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002657 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002658 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002659 return false;
2660 }
2661
2662 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002663 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002664 return false;
2665 }
2666
2667 size_t number_removed =
2668 mutable_remote_description()->RemoveCandidates(candidates);
2669 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002670 RTC_LOG(LS_ERROR)
2671 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002672 "Requested "
2673 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002674 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002675 }
2676
2677 // Remove the candidates from the transport controller.
2678 std::string error;
2679 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2680 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002681 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002682 }
2683 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002684}
2685
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002686void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002687 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002688 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002689
Steve Anton75737c02017-11-06 10:37:17 -08002690 if (transport_controller()) {
2691 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002692 }
2693
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002694 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002695 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002696 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002697 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002698 uma_observer_->IncrementEnumCounter(
2699 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2700 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002701 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002702 uma_observer_->IncrementEnumCounter(
2703 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2704 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002705 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002706 // Send information about the requested SDP semantics.
2707 switch (configuration_.sdp_semantics) {
2708 case SdpSemantics::kDefault:
2709 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2710 kSdpSemanticRequestDefault,
2711 kSdpSemanticRequestMax);
2712
2713 break;
2714 case SdpSemantics::kPlanB:
2715 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2716 kSdpSemanticRequestPlanB,
2717 kSdpSemanticRequestMax);
2718 break;
2719 case SdpSemantics::kUnifiedPlan:
2720 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2721 kSdpSemanticRequestUnifiedPlan,
2722 kSdpSemanticRequestMax);
2723 break;
2724 default:
2725 RTC_NOTREACHED();
2726 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002727 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002728}
2729
zstein4b979802017-06-02 14:37:37 -07002730RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002731 if (!worker_thread()->IsCurrent()) {
2732 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002733 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2734 }
2735
2736 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2737 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2738 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2739 if (has_min && *bitrate.min_bitrate_bps < 0) {
2740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2741 "min_bitrate_bps <= 0");
2742 }
2743 if (has_current) {
2744 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2746 "current_bitrate_bps < min_bitrate_bps");
2747 } else if (*bitrate.current_bitrate_bps < 0) {
2748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2749 "curent_bitrate_bps < 0");
2750 }
2751 }
2752 if (has_max) {
2753 if (has_current &&
2754 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2756 "max_bitrate_bps < current_bitrate_bps");
2757 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2758 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2759 "max_bitrate_bps < min_bitrate_bps");
2760 } else if (*bitrate.max_bitrate_bps < 0) {
2761 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2762 "max_bitrate_bps < 0");
2763 }
2764 }
2765
2766 Call::Config::BitrateConfigMask mask;
2767 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2768 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2769 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2770
2771 RTC_DCHECK(call_.get());
2772 call_->SetBitrateConfigMask(mask);
2773
2774 return RTCError::OK();
2775}
2776
Alex Narest78609d52017-10-20 10:37:47 +02002777void PeerConnection::SetBitrateAllocationStrategy(
2778 std::unique_ptr<rtc::BitrateAllocationStrategy>
2779 bitrate_allocation_strategy) {
2780 rtc::Thread* worker_thread = factory_->worker_thread();
2781 if (!worker_thread->IsCurrent()) {
2782 rtc::BitrateAllocationStrategy* strategy_raw =
2783 bitrate_allocation_strategy.release();
2784 auto functor = [this, strategy_raw]() {
2785 call_->SetBitrateAllocationStrategy(
2786 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2787 };
2788 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2789 return;
2790 }
2791 RTC_DCHECK(call_.get());
2792 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2793}
2794
henrika5f6bf242017-11-01 11:06:56 +01002795void PeerConnection::SetAudioPlayout(bool playout) {
2796 if (!worker_thread()->IsCurrent()) {
2797 worker_thread()->Invoke<void>(
2798 RTC_FROM_HERE,
2799 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2800 return;
2801 }
2802 auto audio_state =
2803 factory_->channel_manager()->media_engine()->GetAudioState();
2804 audio_state->SetPlayout(playout);
2805}
2806
2807void PeerConnection::SetAudioRecording(bool recording) {
2808 if (!worker_thread()->IsCurrent()) {
2809 worker_thread()->Invoke<void>(
2810 RTC_FROM_HERE,
2811 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2812 return;
2813 }
2814 auto audio_state =
2815 factory_->channel_manager()->media_engine()->GetAudioState();
2816 audio_state->SetRecording(recording);
2817}
2818
Steve Anton8c0f7a72017-10-03 10:03:10 -07002819std::unique_ptr<rtc::SSLCertificate>
2820PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002821 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002822 return nullptr;
2823 }
Steve Anton75737c02017-11-06 10:37:17 -08002824 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002825}
2826
Zhi Huang70b820f2018-01-27 14:16:15 -08002827std::unique_ptr<rtc::SSLCertChain>
2828PeerConnection::GetRemoteAudioSSLCertChain() {
2829 if (!voice_channel()) {
2830 return nullptr;
2831 }
2832
2833 return transport_controller_->GetRemoteSSLCertChain(
2834 voice_channel()->transport_name());
2835}
2836
ivoc14d5dbe2016-07-04 07:06:55 -07002837bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2838 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002839 // TODO(eladalon): It would be better to not allow negative values into PC.
2840 const size_t max_size = (max_size_bytes < 0)
2841 ? RtcEventLog::kUnlimitedOutput
2842 : rtc::saturated_cast<size_t>(max_size_bytes);
2843 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002844 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2845 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002846}
2847
Bjorn Tereliusde939432017-11-20 17:38:14 +01002848bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2849 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002850 // TODO(eladalon): In C++14, this can be done with a lambda.
2851 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002852 bool operator()() {
2853 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2854 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002855 PeerConnection* const pc;
2856 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002857 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002858 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002859 return worker_thread()->Invoke<bool>(
2860 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002861}
2862
2863void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002864 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002865 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2866}
2867
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002869 return pending_local_description_ ? pending_local_description_.get()
2870 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871}
2872
2873const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002874 return pending_remote_description_ ? pending_remote_description_.get()
2875 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876}
2877
deadbeeffe4a8a42016-12-20 17:56:17 -08002878const SessionDescriptionInterface* PeerConnection::current_local_description()
2879 const {
Steve Anton75737c02017-11-06 10:37:17 -08002880 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002881}
2882
2883const SessionDescriptionInterface* PeerConnection::current_remote_description()
2884 const {
Steve Anton75737c02017-11-06 10:37:17 -08002885 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002886}
2887
2888const SessionDescriptionInterface* PeerConnection::pending_local_description()
2889 const {
Steve Anton75737c02017-11-06 10:37:17 -08002890 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002891}
2892
2893const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2894 const {
Steve Anton75737c02017-11-06 10:37:17 -08002895 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002896}
2897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002898void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002899 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 // Update stats here so that we have the most recent stats for tracks and
2901 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002902 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002903
Steve Anton75737c02017-11-06 10:37:17 -08002904 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002905
Steve Anton8af21862017-12-15 11:20:13 -08002906 for (auto transceiver : transceivers_) {
2907 transceiver->Stop();
2908 }
2909 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002910
Qingsi Wang93a84392018-01-30 17:13:09 -08002911 // The event log is used in the transport controller, which must be outlived
2912 // by the former. CreateOffer by the peer connection is implemented
2913 // asynchronously and if the peer connection is closed without resetting the
2914 // WebRTC session description factory, the session description factory would
2915 // call the transport controller.
2916 webrtc_session_desc_factory_.reset();
2917 transport_controller_.reset();
2918
deadbeef42a42632017-03-10 15:18:00 -08002919 network_thread()->Invoke<void>(
2920 RTC_FROM_HERE,
2921 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2922 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002923
Steve Anton978b8762017-09-29 12:15:02 -07002924 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002925 call_.reset();
2926 // The event log must outlive call (and any other object that uses it).
2927 event_log_.reset();
2928 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002929}
2930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002931void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2934 SetSessionDescriptionMsg* param =
2935 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2936 param->observer->OnSuccess();
2937 delete param;
2938 break;
2939 }
2940 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2941 SetSessionDescriptionMsg* param =
2942 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2943 param->observer->OnFailure(param->error);
2944 delete param;
2945 break;
2946 }
deadbeefab9b2d12015-10-14 11:33:11 -07002947 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2948 CreateSessionDescriptionMsg* param =
2949 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2950 param->observer->OnFailure(param->error);
2951 delete param;
2952 break;
2953 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 case MSG_GETSTATS: {
2955 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002956 StatsReports reports;
2957 stats_->GetStats(param->track, &reports);
2958 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959 delete param;
2960 break;
2961 }
deadbeefbd292462015-12-14 18:15:29 -08002962 case MSG_FREE_DATACHANNELS: {
2963 sctp_data_channels_to_free_.clear();
2964 break;
2965 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002967 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 break;
2969 }
2970}
2971
Steve Anton4171afb2017-11-20 10:20:22 -08002972void PeerConnection::CreateAudioReceiver(
2973 MediaStreamInterface* stream,
2974 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002975 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2976 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002977 auto* audio_receiver = new AudioRtpReceiver(
2978 worker_thread(), remote_sender_info.sender_id, streams);
2979 audio_receiver->SetMediaChannel(voice_media_channel());
2980 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2981 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2982 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002983 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002984 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002985}
2986
Steve Anton4171afb2017-11-20 10:20:22 -08002987void PeerConnection::CreateVideoReceiver(
2988 MediaStreamInterface* stream,
2989 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002990 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2991 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002992 auto* video_receiver = new VideoRtpReceiver(
2993 worker_thread(), remote_sender_info.sender_id, streams);
2994 video_receiver->SetMediaChannel(video_media_channel());
2995 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2996 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2997 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002998 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002999 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000}
3001
deadbeef70ab1a12015-09-28 16:53:55 -07003002// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3003// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003004rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003005 const RtpSenderInfo& remote_sender_info) {
3006 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3007 if (!receiver) {
3008 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3009 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003010 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003011 }
Steve Anton4171afb2017-11-20 10:20:22 -08003012 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3013 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3014 } else {
3015 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3016 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003017 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003018}
3019
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003020void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3021 MediaStreamInterface* stream) {
3022 RTC_DCHECK(!IsClosed());
3023 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003024 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003025 // We already have a sender for this track, so just change the stream_id
3026 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003027 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003028 return;
3029 }
3030
3031 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003032 auto new_sender =
3033 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
3034 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003035 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003036 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003037 // If the sender has already been configured in SDP, we call SetSsrc,
3038 // which will connect the sender to the underlying transport. This can
3039 // occur if a local session description that contains the ID of the sender
3040 // is set before AddStream is called. It can also occur if the local
3041 // session description is not changed and RemoveStream is called, and
3042 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003043 const RtpSenderInfo* sender_info =
3044 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3045 if (sender_info) {
3046 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003047 }
3048}
3049
3050// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3051// indefinitely, when we have unified plan SDP.
3052void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3053 MediaStreamInterface* stream) {
3054 RTC_DCHECK(!IsClosed());
3055 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003056 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003057 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3058 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003059 return;
3060 }
Steve Anton4171afb2017-11-20 10:20:22 -08003061 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003062}
3063
3064void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3065 MediaStreamInterface* stream) {
3066 RTC_DCHECK(!IsClosed());
3067 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003068 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003069 // We already have a sender for this track, so just change the stream_id
3070 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003071 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003072 return;
3073 }
3074
3075 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003076 auto new_sender =
3077 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3078 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003079 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003080 GetVideoTransceiver()->internal()->AddSender(new_sender);
3081 const RtpSenderInfo* sender_info =
3082 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3083 if (sender_info) {
3084 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003085 }
3086}
3087
3088void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3089 MediaStreamInterface* stream) {
3090 RTC_DCHECK(!IsClosed());
3091 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003092 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003093 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3094 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003095 return;
3096 }
Steve Anton4171afb2017-11-20 10:20:22 -08003097 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003098}
3099
Steve Antonba818672017-11-06 10:21:57 -08003100void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003101 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003102 if (ice_connection_state_ == new_state) {
3103 return;
3104 }
3105
deadbeefcbecd352015-09-23 11:50:27 -07003106 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003107 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003108 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003109 return;
3110 }
Steve Antonba818672017-11-06 10:21:57 -08003111
Mirko Bonadei675513b2017-11-09 11:09:25 +01003112 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3113 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003114 RTC_DCHECK(ice_connection_state_ !=
3115 PeerConnectionInterface::kIceConnectionClosed);
3116
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003118 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119}
3120
3121void PeerConnection::OnIceGatheringChange(
3122 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003123 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003124 if (IsClosed()) {
3125 return;
3126 }
3127 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003128 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003129}
3130
jbauch81bf7b02017-03-25 08:31:12 -07003131void PeerConnection::OnIceCandidate(
3132 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003133 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003134 if (IsClosed()) {
3135 return;
3136 }
jbauch81bf7b02017-03-25 08:31:12 -07003137 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138}
3139
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003140void PeerConnection::OnIceCandidatesRemoved(
3141 const std::vector<cricket::Candidate>& candidates) {
3142 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003143 if (IsClosed()) {
3144 return;
3145 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003146 observer_->OnIceCandidatesRemoved(candidates);
3147}
3148
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003149void PeerConnection::ChangeSignalingState(
3150 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003151 RTC_DCHECK(signaling_thread()->IsCurrent());
3152 if (signaling_state_ == signaling_state) {
3153 return;
3154 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003155 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3156 << GetSignalingStateString(signaling_state_)
3157 << " New state: "
3158 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003159 signaling_state_ = signaling_state;
3160 if (signaling_state == kClosed) {
3161 ice_connection_state_ = kIceConnectionClosed;
3162 observer_->OnIceConnectionChange(ice_connection_state_);
3163 if (ice_gathering_state_ != kIceGatheringComplete) {
3164 ice_gathering_state_ = kIceGatheringComplete;
3165 observer_->OnIceGatheringChange(ice_gathering_state_);
3166 }
3167 }
3168 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169}
3170
deadbeefeb459812015-12-15 19:24:43 -08003171void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3172 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003173 if (IsClosed()) {
3174 return;
3175 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003176 AddAudioTrack(track, stream);
3177 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003178}
3179
deadbeefeb459812015-12-15 19:24:43 -08003180void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3181 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003182 if (IsClosed()) {
3183 return;
3184 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003185 RemoveAudioTrack(track, stream);
3186 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003187}
3188
3189void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3190 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003191 if (IsClosed()) {
3192 return;
3193 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003194 AddVideoTrack(track, stream);
3195 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003196}
3197
3198void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3199 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003200 if (IsClosed()) {
3201 return;
3202 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003203 RemoveVideoTrack(track, stream);
3204 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003205}
3206
Henrik Boström31638672017-11-23 17:48:32 +01003207void PeerConnection::PostSetSessionDescriptionSuccess(
3208 SetSessionDescriptionObserver* observer) {
3209 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3210 signaling_thread()->Post(RTC_FROM_HERE, this,
3211 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3212}
3213
deadbeefab9b2d12015-10-14 11:33:11 -07003214void PeerConnection::PostSetSessionDescriptionFailure(
3215 SetSessionDescriptionObserver* observer,
3216 const std::string& error) {
3217 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3218 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003219 signaling_thread()->Post(RTC_FROM_HERE, this,
3220 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003221}
3222
3223void PeerConnection::PostCreateSessionDescriptionFailure(
3224 CreateSessionDescriptionObserver* observer,
3225 const std::string& error) {
3226 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3227 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003228 signaling_thread()->Post(RTC_FROM_HERE, this,
3229 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003230}
3231
zhihuang1c378ed2017-08-17 14:10:50 -07003232void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003233 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003234 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003235 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003236
Steve Antondcc3c022017-12-22 16:02:54 -08003237 if (IsUnifiedPlan()) {
3238 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3239 } else {
3240 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3241 }
3242
Steve Antonfa2260d2017-12-28 16:38:23 -08003243 // Intentionally unset the data channel type for RTP data channel with the
3244 // second condition. Otherwise the RTP data channels would be successfully
3245 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3246 // when building with chromium. We want to leave RTP data channels broken, so
3247 // people won't try to use them.
3248 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3249 session_options->data_channel_type = data_channel_type();
3250 }
3251
Steve Antondcc3c022017-12-22 16:02:54 -08003252 // Apply ICE restart flag and renomination flag.
3253 for (auto& options : session_options->media_description_options) {
3254 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3255 options.transport_options.enable_ice_renomination =
3256 configuration_.enable_ice_renomination;
3257 }
3258
3259 session_options->rtcp_cname = rtcp_cname_;
3260 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003261 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003262}
3263
3264void PeerConnection::GetOptionsForPlanBOffer(
3265 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3266 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003267 // Figure out transceiver directional preferences.
3268 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3269 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3270
3271 // By default, generate sendrecv/recvonly m= sections.
3272 bool recv_audio = true;
3273 bool recv_video = true;
3274
3275 // By default, only offer a new m= section if we have media to send with it.
3276 bool offer_new_audio_description = send_audio;
3277 bool offer_new_video_description = send_video;
3278 bool offer_new_data_description = HasDataChannels();
3279
3280 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003281 if (offer_answer_options.offer_to_receive_audio !=
3282 RTCOfferAnswerOptions::kUndefined) {
3283 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003284 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003285 offer_new_audio_description ||
3286 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003287 }
Steve Antondcc3c022017-12-22 16:02:54 -08003288 if (offer_answer_options.offer_to_receive_video !=
3289 RTCOfferAnswerOptions::kUndefined) {
3290 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003291 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003292 offer_new_video_description ||
3293 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003294 }
3295
3296 rtc::Optional<size_t> audio_index;
3297 rtc::Optional<size_t> video_index;
3298 rtc::Optional<size_t> data_index;
3299 // If a current description exists, generate m= sections in the same order,
3300 // using the first audio/video/data section that appears and rejecting
3301 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003302 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003303 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003304 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003305 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3306 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3307 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003308 }
3309
zhihuang1c378ed2017-08-17 14:10:50 -07003310 // Add audio/video/data m= sections to the end if needed.
3311 if (!audio_index && offer_new_audio_description) {
3312 session_options->media_description_options.push_back(
3313 cricket::MediaDescriptionOptions(
3314 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003315 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3316 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003317 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003318 }
zhihuang1c378ed2017-08-17 14:10:50 -07003319 if (!video_index && offer_new_video_description) {
3320 session_options->media_description_options.push_back(
3321 cricket::MediaDescriptionOptions(
3322 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003323 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3324 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003325 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003326 }
zhihuang1c378ed2017-08-17 14:10:50 -07003327 if (!data_index && offer_new_data_description) {
3328 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003329 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003330 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003331 }
3332
3333 cricket::MediaDescriptionOptions* audio_media_description_options =
3334 !audio_index ? nullptr
3335 : &session_options->media_description_options[*audio_index];
3336 cricket::MediaDescriptionOptions* video_media_description_options =
3337 !video_index ? nullptr
3338 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003339
Steve Anton4171afb2017-11-20 10:20:22 -08003340 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003341 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003342}
3343
3344// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3345// and return a reference to it.
3346// Generated MIDs should be no more than 3 bytes long to take up less space in
3347// the RTP packet.
3348static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3349 RTC_DCHECK(used_mids);
3350 // We're boring: just generate MIDs 0, 1, 2, ...
3351 size_t i = 0;
3352 std::set<std::string>::iterator it;
3353 bool inserted;
3354 do {
3355 std::string mid = rtc::ToString(i++);
3356 auto insert_result = used_mids->insert(mid);
3357 it = insert_result.first;
3358 inserted = insert_result.second;
3359 } while (!inserted);
3360 return *it;
3361}
3362
3363static cricket::MediaDescriptionOptions
3364GetMediaDescriptionOptionsForTransceiver(
3365 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3366 transceiver,
3367 const std::string& mid) {
3368 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003369 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003370 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003371 // This behavior is specified in JSEP. The gist is that:
3372 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3373 // sendrecv.
3374 // 2. If the MSID is included, then it must be included in any subsequent
3375 // offer/answer exactly the same until the RtpTransceiver is stopped.
3376 if (!transceiver->stopped() &&
3377 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3378 transceiver->internal()->has_ever_been_used_to_send())) {
3379 cricket::SenderOptions sender_options;
3380 sender_options.track_id = transceiver->sender()->id();
3381 sender_options.stream_ids = transceiver->sender()->stream_ids();
3382 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3383 // set in the RTP parameters when the transceiver was added.
3384 sender_options.num_sim_layers = 1;
3385 media_description_options.sender_options.push_back(sender_options);
3386 }
Steve Antondcc3c022017-12-22 16:02:54 -08003387 return media_description_options;
3388}
3389
3390void PeerConnection::GetOptionsForUnifiedPlanOffer(
3391 const RTCOfferAnswerOptions& offer_answer_options,
3392 cricket::MediaSessionOptions* session_options) {
3393 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3394 // Offers) and 5.2.2 (Subsequent Offers).
3395 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3396 const ContentInfos& local_contents =
3397 (local_description() ? local_description()->description()->contents()
3398 : ContentInfos());
3399 const ContentInfos& remote_contents =
3400 (remote_description() ? remote_description()->description()->contents()
3401 : ContentInfos());
3402 // The mline indices that can be recycled. New transceivers should reuse these
3403 // slots first.
3404 std::queue<size_t> recycleable_mline_indices;
3405 // Track the MIDs used in previous offer/answer exchanges and the current
3406 // offer so that new, unique MIDs are generated.
3407 std::set<std::string> used_mids = seen_mids_;
3408 // First, go through each media section that exists in either the local or
3409 // remote description and generate a media section in this offer for the
3410 // associated transceiver. If a media section can be recycled, generate a
3411 // default, rejected media section here that can be later overwritten.
3412 for (size_t i = 0;
3413 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3414 // Either |local_content| or |remote_content| is non-null.
3415 const ContentInfo* local_content =
3416 (i < local_contents.size() ? &local_contents[i] : nullptr);
3417 const ContentInfo* remote_content =
3418 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3419 bool had_been_rejected = (local_content && local_content->rejected) ||
3420 (remote_content && remote_content->rejected);
3421 const std::string& mid =
3422 (local_content ? local_content->name : remote_content->name);
3423 cricket::MediaType media_type =
3424 (local_content ? local_content->media_description()->type()
3425 : remote_content->media_description()->type());
3426 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3427 media_type == cricket::MEDIA_TYPE_VIDEO) {
3428 auto transceiver = GetAssociatedTransceiver(mid);
3429 RTC_CHECK(transceiver);
3430 // A media section is considered eligible for recycling if it is marked as
3431 // rejected in either the local or remote description.
3432 if (had_been_rejected) {
3433 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003434 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3435 RtpTransceiverDirection::kInactive,
3436 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003437 recycleable_mline_indices.push(i);
3438 } else {
3439 session_options->media_description_options.push_back(
3440 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3441 // CreateOffer shouldn't really cause any state changes in
3442 // PeerConnection, but we need a way to match new transceivers to new
3443 // media sections in SetLocalDescription and JSEP specifies this is done
3444 // by recording the index of the media section generated for the
3445 // transceiver in the offer.
3446 transceiver->internal()->set_mline_index(i);
3447 }
3448 } else {
3449 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003450 RTC_CHECK(GetDataMid());
3451 if (had_been_rejected || mid != *GetDataMid()) {
3452 session_options->media_description_options.push_back(
3453 GetMediaDescriptionOptionsForRejectedData(mid));
3454 } else {
3455 session_options->media_description_options.push_back(
3456 GetMediaDescriptionOptionsForActiveData(mid));
3457 }
Steve Antondcc3c022017-12-22 16:02:54 -08003458 }
3459 }
3460 // Next, look for transceivers that are newly added (that is, are not stopped
3461 // and not associated). Reuse media sections marked as recyclable first,
3462 // otherwise append to the end of the offer. New media sections should be
3463 // added in the order they were added to the PeerConnection.
3464 for (auto transceiver : transceivers_) {
3465 if (transceiver->mid() || transceiver->stopped()) {
3466 continue;
3467 }
3468 size_t mline_index;
3469 if (!recycleable_mline_indices.empty()) {
3470 mline_index = recycleable_mline_indices.front();
3471 recycleable_mline_indices.pop();
3472 session_options->media_description_options[mline_index] =
3473 GetMediaDescriptionOptionsForTransceiver(transceiver,
3474 AllocateMid(&used_mids));
3475 } else {
3476 mline_index = session_options->media_description_options.size();
3477 session_options->media_description_options.push_back(
3478 GetMediaDescriptionOptionsForTransceiver(transceiver,
3479 AllocateMid(&used_mids)));
3480 }
3481 // See comment above for why CreateOffer changes the transceiver's state.
3482 transceiver->internal()->set_mline_index(mline_index);
3483 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003484 // Lastly, add a m-section if we have local data channels and an m section
3485 // does not already exist.
3486 if (!GetDataMid() && HasDataChannels()) {
3487 session_options->media_description_options.push_back(
3488 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3489 }
Steve Antondcc3c022017-12-22 16:02:54 -08003490}
3491
3492void PeerConnection::GetOptionsForAnswer(
3493 const RTCOfferAnswerOptions& offer_answer_options,
3494 cricket::MediaSessionOptions* session_options) {
3495 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3496
3497 if (IsUnifiedPlan()) {
3498 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3499 } else {
3500 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3501 }
3502
Steve Antonfa2260d2017-12-28 16:38:23 -08003503 // Intentionally unset the data channel type for RTP data channel. Otherwise
3504 // the RTP data channels would be successfully negotiated by default and the
3505 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3506 // We want to leave RTP data channels broken, so people won't try to use them.
3507 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3508 session_options->data_channel_type = data_channel_type();
3509 }
3510
Steve Antondcc3c022017-12-22 16:02:54 -08003511 // Apply ICE renomination flag.
3512 for (auto& options : session_options->media_description_options) {
3513 options.transport_options.enable_ice_renomination =
3514 configuration_.enable_ice_renomination;
3515 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003516
3517 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003518 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003519 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003520}
3521
Steve Antondcc3c022017-12-22 16:02:54 -08003522void PeerConnection::GetOptionsForPlanBAnswer(
3523 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003524 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003525 // Figure out transceiver directional preferences.
3526 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3527 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3528
3529 // By default, generate sendrecv/recvonly m= sections. The direction is also
3530 // restricted by the direction in the offer.
3531 bool recv_audio = true;
3532 bool recv_video = true;
3533
3534 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003535 if (offer_answer_options.offer_to_receive_audio !=
3536 RTCOfferAnswerOptions::kUndefined) {
3537 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003538 }
Steve Antondcc3c022017-12-22 16:02:54 -08003539 if (offer_answer_options.offer_to_receive_video !=
3540 RTCOfferAnswerOptions::kUndefined) {
3541 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003542 }
3543
3544 rtc::Optional<size_t> audio_index;
3545 rtc::Optional<size_t> video_index;
3546 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003547
3548 // Generate m= sections that match those in the offer.
3549 // Note that mediasession.cc will handle intersection our preferred
3550 // direction with the offered direction.
3551 GenerateMediaDescriptionOptions(
3552 remote_description(),
3553 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3554 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3555 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003556
3557 cricket::MediaDescriptionOptions* audio_media_description_options =
3558 !audio_index ? nullptr
3559 : &session_options->media_description_options[*audio_index];
3560 cricket::MediaDescriptionOptions* video_media_description_options =
3561 !video_index ? nullptr
3562 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003563
Steve Anton4171afb2017-11-20 10:20:22 -08003564 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003565 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003566}
zhihuangaf388472016-11-02 16:49:48 -07003567
Steve Antondcc3c022017-12-22 16:02:54 -08003568void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3569 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3570 cricket::MediaSessionOptions* session_options) {
3571 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3572 // Answers) and 5.3.2 (Subsequent Answers).
3573 RTC_DCHECK(remote_description());
3574 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3575 for (const ContentInfo& content :
3576 remote_description()->description()->contents()) {
3577 cricket::MediaType media_type = content.media_description()->type();
3578 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3579 media_type == cricket::MEDIA_TYPE_VIDEO) {
3580 auto transceiver = GetAssociatedTransceiver(content.name);
3581 RTC_CHECK(transceiver);
3582 session_options->media_description_options.push_back(
3583 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3584 } else {
3585 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003586 // Reject all data sections if data channels are disabled.
3587 // Reject a data section if it has already been rejected.
3588 // Reject all data sections except for the first one.
3589 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3590 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003591 session_options->media_description_options.push_back(
3592 GetMediaDescriptionOptionsForRejectedData(content.name));
3593 } else {
3594 session_options->media_description_options.push_back(
3595 GetMediaDescriptionOptionsForActiveData(content.name));
3596 }
Steve Antondcc3c022017-12-22 16:02:54 -08003597 }
3598 }
htaa2a49d92016-03-04 02:51:39 -08003599}
3600
zhihuang1c378ed2017-08-17 14:10:50 -07003601void PeerConnection::GenerateMediaDescriptionOptions(
3602 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003603 RtpTransceiverDirection audio_direction,
3604 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003605 rtc::Optional<size_t>* audio_index,
3606 rtc::Optional<size_t>* video_index,
3607 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003608 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003609 for (const cricket::ContentInfo& content :
3610 session_desc->description()->contents()) {
3611 if (IsAudioContent(&content)) {
3612 // If we already have an audio m= section, reject this extra one.
3613 if (*audio_index) {
3614 session_options->media_description_options.push_back(
3615 cricket::MediaDescriptionOptions(
3616 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003617 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003618 } else {
3619 session_options->media_description_options.push_back(
3620 cricket::MediaDescriptionOptions(
3621 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003622 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003623 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003624 }
3625 } else if (IsVideoContent(&content)) {
3626 // If we already have an video m= section, reject this extra one.
3627 if (*video_index) {
3628 session_options->media_description_options.push_back(
3629 cricket::MediaDescriptionOptions(
3630 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003631 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003632 } else {
3633 session_options->media_description_options.push_back(
3634 cricket::MediaDescriptionOptions(
3635 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003636 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003637 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003638 }
3639 } else {
3640 RTC_DCHECK(IsDataContent(&content));
3641 // If we already have an data m= section, reject this extra one.
3642 if (*data_index) {
3643 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003644 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003645 } else {
3646 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003647 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003648 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003649 }
3650 }
htaa2a49d92016-03-04 02:51:39 -08003651 }
deadbeefab9b2d12015-10-14 11:33:11 -07003652}
3653
Steve Antonfa2260d2017-12-28 16:38:23 -08003654cricket::MediaDescriptionOptions
3655PeerConnection::GetMediaDescriptionOptionsForActiveData(
3656 const std::string& mid) const {
3657 // Direction for data sections is meaningless, but legacy endpoints might
3658 // expect sendrecv.
3659 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3660 RtpTransceiverDirection::kSendRecv,
3661 /*stopped=*/false);
3662 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3663 return options;
3664}
3665
3666cricket::MediaDescriptionOptions
3667PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3668 const std::string& mid) const {
3669 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3670 RtpTransceiverDirection::kInactive,
3671 /*stopped=*/true);
3672 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3673 return options;
3674}
3675
3676rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3677 switch (data_channel_type_) {
3678 case cricket::DCT_RTP:
3679 if (!rtp_data_channel_) {
3680 return rtc::nullopt;
3681 }
3682 return rtp_data_channel_->content_name();
3683 case cricket::DCT_SCTP:
3684 return sctp_content_name_;
3685 default:
3686 return rtc::nullopt;
3687 }
3688}
3689
Steve Anton4171afb2017-11-20 10:20:22 -08003690void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3691 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3692 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003693 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003694}
3695
Steve Anton4171afb2017-11-20 10:20:22 -08003696void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003697 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003698 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003699 cricket::MediaType media_type,
3700 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003701 std::vector<RtpSenderInfo>* current_senders =
3702 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003703
Steve Anton4171afb2017-11-20 10:20:22 -08003704 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003705 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003706 for (auto sender_it = current_senders->begin();
3707 sender_it != current_senders->end();
3708 /* incremented manually */) {
3709 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003710 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003711 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3712 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003713 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003714 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3715 sender_exists) {
3716 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003717 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003718 OnRemoteSenderRemoved(info, media_type);
3719 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003720 }
3721 }
3722
Steve Anton4171afb2017-11-20 10:20:22 -08003723 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003724 for (const cricket::StreamParams& params : streams) {
3725 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003726 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003727 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003728 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003729 uint32_t ssrc = params.first_ssrc();
3730
3731 rtc::scoped_refptr<MediaStreamInterface> stream =
3732 remote_streams_->find(stream_label);
3733 if (!stream) {
3734 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003735 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3736 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003737 remote_streams_->AddStream(stream);
3738 new_streams->AddStream(stream);
3739 }
3740
Steve Anton4171afb2017-11-20 10:20:22 -08003741 const RtpSenderInfo* sender_info =
3742 FindSenderInfo(*current_senders, stream_label, sender_id);
3743 if (!sender_info) {
3744 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3745 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003746 }
3747 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003748
Steve Anton4171afb2017-11-20 10:20:22 -08003749 // Add default sender if necessary.
3750 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003751 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3752 remote_streams_->find(kDefaultStreamLabel);
3753 if (!default_stream) {
3754 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003755 default_stream = MediaStreamProxy::Create(
3756 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003757 remote_streams_->AddStream(default_stream);
3758 new_streams->AddStream(default_stream);
3759 }
Steve Anton4171afb2017-11-20 10:20:22 -08003760 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3761 ? kDefaultAudioSenderId
3762 : kDefaultVideoSenderId;
3763 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3764 *current_senders, kDefaultStreamLabel, default_sender_id);
3765 if (!default_sender_info) {
3766 current_senders->push_back(
3767 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3768 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003769 }
3770 }
deadbeefab9b2d12015-10-14 11:33:11 -07003771}
3772
Steve Anton4171afb2017-11-20 10:20:22 -08003773void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3774 cricket::MediaType media_type) {
3775 MediaStreamInterface* stream =
3776 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003777
3778 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003779 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003780 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003781 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003782 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003783 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003784 }
3785}
3786
Steve Anton4171afb2017-11-20 10:20:22 -08003787void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3788 cricket::MediaType media_type) {
3789 MediaStreamInterface* stream =
3790 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003791
Henrik Boström933d8b02017-10-10 10:05:16 -07003792 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003793 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003794 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3795 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003796 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003797 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003798 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003799 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003800 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003801 }
3802 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003803 // Stopping or destroying a VideoRtpReceiver will end the
3804 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003805 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003806 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003807 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003808 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003809 // There's no guarantee the track is still available, e.g. the track may
3810 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003811 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003812 }
3813 } else {
nisseede5da42017-01-12 05:15:36 -08003814 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003815 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003816 if (receiver) {
3817 observer_->OnRemoveTrack(receiver);
3818 }
deadbeefab9b2d12015-10-14 11:33:11 -07003819}
3820
3821void PeerConnection::UpdateEndedRemoteMediaStreams() {
3822 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3823 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3824 MediaStreamInterface* stream = remote_streams_->at(i);
3825 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3826 streams_to_remove.push_back(stream);
3827 }
3828 }
3829
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003830 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003831 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003832 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003833 }
3834}
3835
Steve Anton4171afb2017-11-20 10:20:22 -08003836void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003837 const std::vector<cricket::StreamParams>& streams,
3838 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003839 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003840
3841 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3842 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003843 for (auto sender_it = current_senders->begin();
3844 sender_it != current_senders->end();
3845 /* incremented manually */) {
3846 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003847 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003848 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3849 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003850 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003851 OnLocalSenderRemoved(info, media_type);
3852 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003853 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003854 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003855 }
3856 }
3857
Steve Anton4171afb2017-11-20 10:20:22 -08003858 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003859 for (const cricket::StreamParams& params : streams) {
3860 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003861 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003862 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003863 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003864 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003865 const RtpSenderInfo* sender_info =
3866 FindSenderInfo(*current_senders, stream_label, sender_id);
3867 if (!sender_info) {
3868 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3869 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003870 }
3871 }
3872}
3873
Steve Anton4171afb2017-11-20 10:20:22 -08003874void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3875 cricket::MediaType media_type) {
3876 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003877 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003878 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3879 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003880 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003881 return;
3882 }
3883
deadbeeffac06552015-11-25 11:26:01 -08003884 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003885 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003886 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003887 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003888 }
deadbeeffac06552015-11-25 11:26:01 -08003889
Steve Anton4171afb2017-11-20 10:20:22 -08003890 sender->internal()->set_stream_id(sender_info.stream_label);
3891 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003892}
3893
Steve Anton4171afb2017-11-20 10:20:22 -08003894void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3895 cricket::MediaType media_type) {
3896 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003897 if (!sender) {
3898 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003899 // SessionDescriptions has been renegotiated.
3900 return;
3901 }
deadbeeffac06552015-11-25 11:26:01 -08003902
3903 // A sender has been removed from the SessionDescription but it's still
3904 // associated with the PeerConnection. This only occurs if the SDP doesn't
3905 // match with the calls to CreateSender, AddStream and RemoveStream.
3906 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003907 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003908 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003909 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003910 }
deadbeeffac06552015-11-25 11:26:01 -08003911
Steve Anton4171afb2017-11-20 10:20:22 -08003912 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003913}
3914
3915void PeerConnection::UpdateLocalRtpDataChannels(
3916 const cricket::StreamParamsVec& streams) {
3917 std::vector<std::string> existing_channels;
3918
3919 // Find new and active data channels.
3920 for (const cricket::StreamParams& params : streams) {
3921 // |it->sync_label| is actually the data channel label. The reason is that
3922 // we use the same naming of data channels as we do for
3923 // MediaStreams and Tracks.
3924 // For MediaStreams, the sync_label is the MediaStream label and the
3925 // track label is the same as |streamid|.
3926 const std::string& channel_label = params.sync_label;
3927 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003928 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003929 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003930 continue;
3931 }
3932 // Set the SSRC the data channel should use for sending.
3933 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3934 existing_channels.push_back(data_channel_it->first);
3935 }
3936
3937 UpdateClosingRtpDataChannels(existing_channels, true);
3938}
3939
3940void PeerConnection::UpdateRemoteRtpDataChannels(
3941 const cricket::StreamParamsVec& streams) {
3942 std::vector<std::string> existing_channels;
3943
3944 // Find new and active data channels.
3945 for (const cricket::StreamParams& params : streams) {
3946 // The data channel label is either the mslabel or the SSRC if the mslabel
3947 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3948 std::string label = params.sync_label.empty()
3949 ? rtc::ToString(params.first_ssrc())
3950 : params.sync_label;
3951 auto data_channel_it = rtp_data_channels_.find(label);
3952 if (data_channel_it == rtp_data_channels_.end()) {
3953 // This is a new data channel.
3954 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3955 } else {
3956 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3957 }
3958 existing_channels.push_back(label);
3959 }
3960
3961 UpdateClosingRtpDataChannels(existing_channels, false);
3962}
3963
3964void PeerConnection::UpdateClosingRtpDataChannels(
3965 const std::vector<std::string>& active_channels,
3966 bool is_local_update) {
3967 auto it = rtp_data_channels_.begin();
3968 while (it != rtp_data_channels_.end()) {
3969 DataChannel* data_channel = it->second;
3970 if (std::find(active_channels.begin(), active_channels.end(),
3971 data_channel->label()) != active_channels.end()) {
3972 ++it;
3973 continue;
3974 }
3975
3976 if (is_local_update) {
3977 data_channel->SetSendSsrc(0);
3978 } else {
3979 data_channel->RemotePeerRequestClose();
3980 }
3981
3982 if (data_channel->state() == DataChannel::kClosed) {
3983 rtp_data_channels_.erase(it);
3984 it = rtp_data_channels_.begin();
3985 } else {
3986 ++it;
3987 }
3988 }
3989}
3990
3991void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3992 uint32_t remote_ssrc) {
3993 rtc::scoped_refptr<DataChannel> channel(
3994 InternalCreateDataChannel(label, nullptr));
3995 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003996 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003997 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003998 return;
3999 }
4000 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004001 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4002 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004003 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004004}
4005
4006rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4007 const std::string& label,
4008 const InternalDataChannelInit* config) {
4009 if (IsClosed()) {
4010 return nullptr;
4011 }
Steve Anton75737c02017-11-06 10:37:17 -08004012 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004013 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004014 << "InternalCreateDataChannel: Data is not supported in this call.";
4015 return nullptr;
4016 }
4017 InternalDataChannelInit new_config =
4018 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004019 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004020 if (new_config.id < 0) {
4021 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004022 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004023 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004024 RTC_LOG(LS_ERROR)
4025 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004026 return nullptr;
4027 }
4028 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004029 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004030 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004031 return nullptr;
4032 }
4033 }
4034
Steve Anton75737c02017-11-06 10:37:17 -08004035 rtc::scoped_refptr<DataChannel> channel(
4036 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004037 if (!channel) {
4038 sid_allocator_.ReleaseSid(new_config.id);
4039 return nullptr;
4040 }
4041
4042 if (channel->data_channel_type() == cricket::DCT_RTP) {
4043 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004044 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4045 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004046 return nullptr;
4047 }
4048 rtp_data_channels_[channel->label()] = channel;
4049 } else {
4050 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4051 sctp_data_channels_.push_back(channel);
4052 channel->SignalClosed.connect(this,
4053 &PeerConnection::OnSctpDataChannelClosed);
4054 }
4055
Steve Anton2d8609c2018-01-23 16:38:46 -08004056 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004057 return channel;
4058}
4059
4060bool PeerConnection::HasDataChannels() const {
4061 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4062}
4063
4064void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4065 for (const auto& channel : sctp_data_channels_) {
4066 if (channel->id() < 0) {
4067 int sid;
4068 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004069 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004070 continue;
4071 }
4072 channel->SetSctpSid(sid);
4073 }
4074 }
4075}
4076
4077void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004078 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004079 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4080 ++it) {
4081 if (it->get() == channel) {
4082 if (channel->id() >= 0) {
4083 sid_allocator_.ReleaseSid(channel->id());
4084 }
deadbeefbd292462015-12-14 18:15:29 -08004085 // Since this method is triggered by a signal from the DataChannel,
4086 // we can't free it directly here; we need to free it asynchronously.
4087 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004088 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004089 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4090 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004091 return;
4092 }
4093 }
4094}
4095
deadbeefab9b2d12015-10-14 11:33:11 -07004096void PeerConnection::OnDataChannelDestroyed() {
4097 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4098 // DataChannel may callback to us and try to modify the list.
4099 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4100 temp_rtp_dcs.swap(rtp_data_channels_);
4101 for (const auto& kv : temp_rtp_dcs) {
4102 kv.second->OnTransportChannelDestroyed();
4103 }
4104
4105 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4106 temp_sctp_dcs.swap(sctp_data_channels_);
4107 for (const auto& channel : temp_sctp_dcs) {
4108 channel->OnTransportChannelDestroyed();
4109 }
4110}
4111
4112void PeerConnection::OnDataChannelOpenMessage(
4113 const std::string& label,
4114 const InternalDataChannelInit& config) {
4115 rtc::scoped_refptr<DataChannel> channel(
4116 InternalCreateDataChannel(label, &config));
4117 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004118 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004119 return;
4120 }
4121
deadbeefa601f5c2016-06-06 14:27:39 -07004122 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4123 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004124 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004125}
4126
Steve Anton4171afb2017-11-20 10:20:22 -08004127rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4128PeerConnection::GetAudioTransceiver() const {
4129 // This method only works with Plan B SDP, where there is a single
4130 // audio/video transceiver.
4131 RTC_DCHECK(!IsUnifiedPlan());
4132 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004133 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004134 return transceiver;
4135 }
4136 }
4137 RTC_NOTREACHED();
4138 return nullptr;
4139}
4140
4141rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4142PeerConnection::GetVideoTransceiver() const {
4143 // This method only works with Plan B SDP, where there is a single
4144 // audio/video transceiver.
4145 RTC_DCHECK(!IsUnifiedPlan());
4146 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004147 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004148 return transceiver;
4149 }
4150 }
4151 RTC_NOTREACHED();
4152 return nullptr;
4153}
4154
4155// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4156// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004157bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004158 switch (type) {
4159 case cricket::MEDIA_TYPE_AUDIO:
4160 return !GetAudioTransceiver()->internal()->senders().empty();
4161 case cricket::MEDIA_TYPE_VIDEO:
4162 return !GetVideoTransceiver()->internal()->senders().empty();
4163 case cricket::MEDIA_TYPE_DATA:
4164 return false;
4165 }
4166 RTC_NOTREACHED();
4167 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004168}
4169
Steve Anton4171afb2017-11-20 10:20:22 -08004170rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4171PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4172 for (auto transceiver : transceivers_) {
4173 for (auto sender : transceiver->internal()->senders()) {
4174 if (sender->track() == track) {
4175 return sender;
4176 }
4177 }
4178 }
4179 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004180}
4181
Steve Anton4171afb2017-11-20 10:20:22 -08004182rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4183PeerConnection::FindSenderById(const std::string& sender_id) const {
4184 for (auto transceiver : transceivers_) {
4185 for (auto sender : transceiver->internal()->senders()) {
4186 if (sender->id() == sender_id) {
4187 return sender;
4188 }
4189 }
4190 }
4191 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004192}
4193
Steve Anton4171afb2017-11-20 10:20:22 -08004194rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4195PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4196 for (auto transceiver : transceivers_) {
4197 for (auto receiver : transceiver->internal()->receivers()) {
4198 if (receiver->id() == receiver_id) {
4199 return receiver;
4200 }
4201 }
4202 }
4203 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004204}
4205
Steve Anton4171afb2017-11-20 10:20:22 -08004206std::vector<PeerConnection::RtpSenderInfo>*
4207PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4208 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4209 media_type == cricket::MEDIA_TYPE_VIDEO);
4210 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4211 ? &remote_audio_sender_infos_
4212 : &remote_video_sender_infos_;
4213}
4214
4215std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004216 cricket::MediaType media_type) {
4217 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4218 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004219 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4220 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004221}
4222
Steve Anton4171afb2017-11-20 10:20:22 -08004223const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4224 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004225 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004226 const std::string sender_id) const {
4227 for (const RtpSenderInfo& sender_info : infos) {
4228 if (sender_info.stream_label == stream_label &&
4229 sender_info.sender_id == sender_id) {
4230 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004231 }
4232 }
4233 return nullptr;
4234}
4235
4236DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4237 for (const auto& channel : sctp_data_channels_) {
4238 if (channel->id() == sid) {
4239 return channel;
4240 }
4241 }
4242 return nullptr;
4243}
4244
deadbeef91dd5672016-05-18 16:55:30 -07004245bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004246 const RTCConfiguration& configuration) {
4247 cricket::ServerAddresses stun_servers;
4248 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004249 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4250 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004251 return false;
4252 }
4253
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004254 port_allocator_->Initialize();
4255
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004256 // To handle both internal and externally created port allocator, we will
4257 // enable BUNDLE here.
4258 int portallocator_flags = port_allocator_->flags();
4259 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004260 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4261 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004262 // If the disable-IPv6 flag was specified, we'll not override it
4263 // by experiment.
4264 if (configuration.disable_ipv6) {
4265 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004266 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4267 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004268 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4269 }
4270
zhihuangb09b3f92017-03-07 14:40:51 -08004271 if (configuration.disable_ipv6_on_wifi) {
4272 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004273 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004274 }
4275
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004276 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4277 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004278 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004279 }
4280
honghaiz60347052016-05-31 18:29:12 -07004281 if (configuration.candidate_network_policy ==
4282 kCandidateNetworkPolicyLowCost) {
4283 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004284 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004285 }
4286
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004287 if (configuration.disable_link_local_networks) {
4288 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4289 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4290 }
4291
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004292 port_allocator_->set_flags(portallocator_flags);
4293 // No step delay is used while allocating ports.
4294 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4295 port_allocator_->set_candidate_filter(
4296 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004297 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004298
4299 // Call this last since it may create pooled allocator sessions using the
4300 // properties set above.
4301 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004302 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004303 configuration.prune_turn_ports,
4304 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004305 return true;
4306}
4307
deadbeef91dd5672016-05-18 16:55:30 -07004308bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004309 const cricket::ServerAddresses& stun_servers,
4310 const std::vector<cricket::RelayServerConfig>& turn_servers,
4311 IceTransportsType type,
4312 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004313 bool prune_turn_ports,
4314 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004315 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004316 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004317 // Call this last since it may create pooled allocator sessions using the
4318 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004319 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004320 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4321 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004322}
4323
Steve Antonba818672017-11-06 10:21:57 -08004324cricket::ChannelManager* PeerConnection::channel_manager() const {
4325 return factory_->channel_manager();
4326}
4327
4328MetricsObserverInterface* PeerConnection::metrics_observer() const {
4329 return uma_observer_;
4330}
4331
Elad Alon99c3fe52017-10-13 16:29:40 +02004332bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004333 std::unique_ptr<RtcEventLogOutput> output,
4334 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004335 if (!event_log_) {
4336 return false;
4337 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004338 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004339}
4340
4341void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004342 if (event_log_) {
4343 event_log_->StopLogging();
4344 }
ivoc14d5dbe2016-07-04 07:06:55 -07004345}
nisseeaabdf62017-05-05 02:23:02 -07004346
Steve Anton75737c02017-11-06 10:37:17 -08004347cricket::BaseChannel* PeerConnection::GetChannel(
4348 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004349 for (auto transceiver : transceivers_) {
4350 cricket::BaseChannel* channel = transceiver->internal()->channel();
4351 if (channel && channel->content_name() == content_name) {
4352 return channel;
4353 }
Steve Anton75737c02017-11-06 10:37:17 -08004354 }
4355 if (rtp_data_channel() &&
4356 rtp_data_channel()->content_name() == content_name) {
4357 return rtp_data_channel();
4358 }
4359 return nullptr;
4360}
4361
4362bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4363 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004364 RTC_LOG(LS_INFO)
4365 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004366 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004367 return false;
4368 }
4369 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004370 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004371 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004372 return false;
4373 }
4374
4375 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4376}
4377
4378bool PeerConnection::GetSslRole(const std::string& content_name,
4379 rtc::SSLRole* role) {
4380 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004381 RTC_LOG(LS_INFO)
4382 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004383 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004384 return false;
4385 }
4386
4387 return transport_controller_->GetSslRole(GetTransportName(content_name),
4388 role);
4389}
4390
Steve Anton75737c02017-11-06 10:37:17 -08004391// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4392// vector of BaseChannel pointers instead of separate voice and video channel
4393// vectors. At that point, this will become a simple getter.
4394std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4395 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004396 if (voice_channel()) {
4397 channels.push_back(voice_channel());
4398 }
4399 if (video_channel()) {
4400 channels.push_back(video_channel());
4401 }
Steve Anton75737c02017-11-06 10:37:17 -08004402 if (rtp_data_channel_) {
4403 channels.push_back(rtp_data_channel_);
4404 }
4405 return channels;
4406}
4407
Steve Antonf8470812017-12-04 10:46:21 -08004408void PeerConnection::SetSessionError(SessionError error,
4409 const std::string& error_desc) {
4410 RTC_DCHECK_RUN_ON(signaling_thread());
4411 if (error != session_error_) {
4412 session_error_ = error;
4413 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004414 }
4415}
4416
Steve Anton3828c062017-12-06 10:34:51 -08004417RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004418 cricket::ContentSource source) {
4419 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004420
4421 // If there's already a pending error then no state transition should happen.
4422 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004423 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004424
4425 // If this is an answer then we know whether to BUNDLE or not. If both the
4426 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004427 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004428 const cricket::ContentGroup* local_bundle =
4429 local_description()->description()->GetGroupByName(
4430 cricket::GROUP_TYPE_BUNDLE);
4431 const cricket::ContentGroup* remote_bundle =
4432 remote_description()->description()->GetGroupByName(
4433 cricket::GROUP_TYPE_BUNDLE);
4434 if (local_bundle && remote_bundle) {
4435 // The answerer decides the transport to bundle on.
4436 const cricket::ContentGroup* answer_bundle =
4437 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4438 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004439 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4440 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004441 }
4442 }
Steve Anton75737c02017-11-06 10:37:17 -08004443 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004444
4445 // Only push down the transport description after potentially enabling BUNDLE;
4446 // we don't want to push down a description on a transport about to be
4447 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004448 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004449 if (!error.ok()) {
4450 return error;
4451 }
4452
4453 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004454 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004455 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004456 }
4457
4458 // Update the signaling state according to the specified state machine (see
4459 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004460 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004461 ChangeSignalingState(source == cricket::CS_LOCAL
4462 ? PeerConnectionInterface::kHaveLocalOffer
4463 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004464 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004465 ChangeSignalingState(source == cricket::CS_LOCAL
4466 ? PeerConnectionInterface::kHaveLocalPrAnswer
4467 : PeerConnectionInterface::kHaveRemotePrAnswer);
4468 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004469 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004470 ChangeSignalingState(PeerConnectionInterface::kStable);
4471 }
4472
4473 // Update internal objects according to the session description's media
4474 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004475 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004476 if (!error.ok()) {
4477 SetSessionError(SessionError::kContent, error.message());
4478 }
4479 if (session_error() != SessionError::kNone) {
4480 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4481 }
4482
Steve Anton8a006912017-12-04 15:25:56 -08004483 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004484}
4485
Steve Anton8a006912017-12-04 15:25:56 -08004486RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004487 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004488 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004489 const SessionDescriptionInterface* sdesc =
4490 (source == cricket::CS_LOCAL ? local_description()
4491 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004492 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004493
4494 // Push down the new SDP media section for each audio/video transceiver.
4495 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004496 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004497 FindMediaSectionForTransceiver(transceiver, sdesc);
4498 cricket::BaseChannel* channel = transceiver->internal()->channel();
4499 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004500 continue;
4501 }
4502 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004503 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004504 if (!content_desc) {
4505 continue;
4506 }
4507 std::string error;
4508 bool success =
4509 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004510 ? channel->SetLocalContent(content_desc, type, &error)
4511 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004512 if (!success) {
4513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4514 }
4515 }
4516
4517 // If using the RtpDataChannel, push down the new SDP section for it too.
4518 if (rtp_data_channel_) {
4519 const ContentInfo* data_content =
4520 cricket::GetFirstDataContent(sdesc->description());
4521 if (data_content && !data_content->rejected) {
4522 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004523 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004524 if (data_desc) {
4525 std::string error;
4526 bool success =
4527 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004528 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4529 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004530 &error);
4531 if (!success) {
4532 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4533 std::move(error));
4534 }
Steve Anton75737c02017-11-06 10:37:17 -08004535 }
4536 }
4537 }
Steve Antoned10bd92017-12-05 10:52:59 -08004538
Steve Anton75737c02017-11-06 10:37:17 -08004539 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4540 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4541 if (sctp_transport_ && local_description() && remote_description() &&
4542 cricket::GetFirstDataContent(local_description()->description()) &&
4543 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004544 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004545 RTC_FROM_HERE,
4546 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004547 if (!success) {
4548 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4549 "Failed to push down SCTP parameters.");
4550 }
Steve Anton75737c02017-11-06 10:37:17 -08004551 }
Steve Antoned10bd92017-12-05 10:52:59 -08004552
Steve Anton8a006912017-12-04 15:25:56 -08004553 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004554}
4555
4556bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4557 RTC_DCHECK(network_thread()->IsCurrent());
4558 RTC_DCHECK(local_description());
4559 RTC_DCHECK(remote_description());
4560 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4561 // When we support "max-message-size", that would also be pushed down here.
4562 return sctp_transport_->Start(
4563 GetSctpPort(local_description()->description()),
4564 GetSctpPort(remote_description()->description()));
4565}
4566
Steve Anton8a006912017-12-04 15:25:56 -08004567RTCError PeerConnection::PushdownTransportDescription(
4568 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004569 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004570 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004571
Steve Anton8a006912017-12-04 15:25:56 -08004572 const SessionDescriptionInterface* sdesc =
4573 (source == cricket::CS_LOCAL ? local_description()
4574 : remote_description());
4575 RTC_DCHECK(sdesc);
4576 for (const cricket::TransportInfo& tinfo :
4577 sdesc->description()->transport_infos()) {
4578 std::string error;
4579 bool success;
4580 if (source == cricket::CS_LOCAL) {
4581 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004582 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004583 } else {
4584 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004585 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004586 }
4587 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4589 "Failed to push down transport description for " +
4590 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004591 }
4592 }
4593
Steve Anton8a006912017-12-04 15:25:56 -08004594 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004595}
4596
4597bool PeerConnection::GetTransportDescription(
4598 const SessionDescription* description,
4599 const std::string& content_name,
4600 cricket::TransportDescription* tdesc) {
4601 if (!description || !tdesc) {
4602 return false;
4603 }
4604 const TransportInfo* transport_info =
4605 description->GetTransportInfoByName(content_name);
4606 if (!transport_info) {
4607 return false;
4608 }
4609 *tdesc = transport_info->description;
4610 return true;
4611}
4612
4613bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4614 const std::string* first_content_name = bundle.FirstContentName();
4615 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004616 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004617 return false;
4618 }
4619 const std::string& transport_name = *first_content_name;
4620
4621 auto maybe_set_transport = [this, bundle,
4622 transport_name](cricket::BaseChannel* ch) {
4623 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004624 return;
Steve Anton75737c02017-11-06 10:37:17 -08004625 }
4626
4627 std::string old_transport_name = ch->transport_name();
4628 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004629 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4630 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004631 return;
Steve Anton75737c02017-11-06 10:37:17 -08004632 }
4633
4634 cricket::DtlsTransportInternal* rtp_dtls_transport =
4635 transport_controller_->CreateDtlsTransport(
4636 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4637 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4638 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4639 if (need_rtcp) {
4640 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4641 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4642 }
4643
4644 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004645 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4646 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004647 transport_controller_->DestroyDtlsTransport(
4648 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4649 // If the channel needs rtcp, it means that the channel used to have a
4650 // rtcp transport which needs to be deleted now.
4651 if (need_rtcp) {
4652 transport_controller_->DestroyDtlsTransport(
4653 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4654 }
Steve Anton75737c02017-11-06 10:37:17 -08004655 };
4656
Steve Antoned10bd92017-12-05 10:52:59 -08004657 for (auto transceiver : transceivers_) {
4658 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004659 }
Steve Antoned10bd92017-12-05 10:52:59 -08004660 maybe_set_transport(rtp_data_channel_);
4661
Steve Anton75737c02017-11-06 10:37:17 -08004662 // For SCTP, transport creation/deletion happens here instead of in the
4663 // object itself.
4664 if (sctp_transport_) {
4665 RTC_DCHECK(sctp_transport_name_);
4666 RTC_DCHECK(sctp_content_name_);
4667 if (transport_name != *sctp_transport_name_ &&
4668 bundle.HasContentName(*sctp_content_name_)) {
4669 network_thread()->Invoke<void>(
4670 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4671 transport_name));
4672 }
4673 }
4674
4675 return true;
4676}
4677
Steve Anton75737c02017-11-06 10:37:17 -08004678cricket::IceConfig PeerConnection::ParseIceConfig(
4679 const PeerConnectionInterface::RTCConfiguration& config) const {
4680 cricket::ContinualGatheringPolicy gathering_policy;
4681 // TODO(honghaiz): Add the third continual gathering policy in
4682 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4683 switch (config.continual_gathering_policy) {
4684 case PeerConnectionInterface::GATHER_ONCE:
4685 gathering_policy = cricket::GATHER_ONCE;
4686 break;
4687 case PeerConnectionInterface::GATHER_CONTINUALLY:
4688 gathering_policy = cricket::GATHER_CONTINUALLY;
4689 break;
4690 default:
4691 RTC_NOTREACHED();
4692 gathering_policy = cricket::GATHER_ONCE;
4693 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004694
Steve Anton75737c02017-11-06 10:37:17 -08004695 cricket::IceConfig ice_config;
4696 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4697 ice_config.prioritize_most_likely_candidate_pairs =
4698 config.prioritize_most_likely_ice_candidate_pairs;
4699 ice_config.backup_connection_ping_interval =
4700 config.ice_backup_candidate_pair_ping_interval;
4701 ice_config.continual_gathering_policy = gathering_policy;
4702 ice_config.presume_writable_when_fully_relayed =
4703 config.presume_writable_when_fully_relayed;
4704 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4705 ice_config.regather_all_networks_interval_range =
4706 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004707 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004708 return ice_config;
4709}
4710
Steve Anton75737c02017-11-06 10:37:17 -08004711bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4712 std::string* track_id) {
4713 if (!local_description()) {
4714 return false;
4715 }
4716 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4717 track_id);
4718}
4719
4720bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4721 std::string* track_id) {
4722 if (!remote_description()) {
4723 return false;
4724 }
4725 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4726 track_id);
4727}
4728
4729bool PeerConnection::SendData(const cricket::SendDataParams& params,
4730 const rtc::CopyOnWriteBuffer& payload,
4731 cricket::SendDataResult* result) {
4732 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004733 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004734 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004735 return false;
4736 }
4737 return rtp_data_channel_
4738 ? rtp_data_channel_->SendData(params, payload, result)
4739 : network_thread()->Invoke<bool>(
4740 RTC_FROM_HERE,
4741 Bind(&cricket::SctpTransportInternal::SendData,
4742 sctp_transport_.get(), params, payload, result));
4743}
4744
4745bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4746 if (!rtp_data_channel_ && !sctp_transport_) {
4747 // Don't log an error here, because DataChannels are expected to call
4748 // ConnectDataChannel in this state. It's the only way to initially tell
4749 // whether or not the underlying transport is ready.
4750 return false;
4751 }
4752 if (rtp_data_channel_) {
4753 rtp_data_channel_->SignalReadyToSendData.connect(
4754 webrtc_data_channel, &DataChannel::OnChannelReady);
4755 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4756 &DataChannel::OnDataReceived);
4757 } else {
4758 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4759 &DataChannel::OnChannelReady);
4760 SignalSctpDataReceived.connect(webrtc_data_channel,
4761 &DataChannel::OnDataReceived);
4762 SignalSctpStreamClosedRemotely.connect(
4763 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4764 }
4765 return true;
4766}
4767
4768void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4769 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004770 RTC_LOG(LS_ERROR)
4771 << "DisconnectDataChannel called when rtp_data_channel_ and "
4772 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004773 return;
4774 }
4775 if (rtp_data_channel_) {
4776 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4777 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4778 } else {
4779 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4780 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4781 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4782 }
4783}
4784
4785void PeerConnection::AddSctpDataStream(int sid) {
4786 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004787 RTC_LOG(LS_ERROR)
4788 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004789 return;
4790 }
4791 network_thread()->Invoke<void>(
4792 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4793 sctp_transport_.get(), sid));
4794}
4795
4796void PeerConnection::RemoveSctpDataStream(int sid) {
4797 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004798 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004799 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004800 return;
4801 }
4802 network_thread()->Invoke<void>(
4803 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4804 sctp_transport_.get(), sid));
4805}
4806
4807bool PeerConnection::ReadyToSendData() const {
4808 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4809 sctp_ready_to_send_data_;
4810}
4811
Steve Anton5dfde182018-02-06 10:34:40 -08004812std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4813 const {
4814 std::map<std::string, std::string> transport_names_by_mid;
4815 for (auto transceiver : transceivers_) {
4816 cricket::BaseChannel* channel = transceiver->internal()->channel();
4817 if (channel) {
4818 transport_names_by_mid[channel->content_name()] =
4819 channel->transport_name();
4820 }
Steve Anton75737c02017-11-06 10:37:17 -08004821 }
Steve Anton5dfde182018-02-06 10:34:40 -08004822 if (rtp_data_channel_) {
4823 transport_names_by_mid[rtp_data_channel_->content_name()] =
4824 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004825 }
4826 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004827 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004828 }
Steve Anton5dfde182018-02-06 10:34:40 -08004829 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004830}
4831
Steve Anton5dfde182018-02-06 10:34:40 -08004832std::map<std::string, cricket::TransportStats>
4833PeerConnection::GetTransportStatsByNames(
4834 const std::set<std::string>& transport_names) {
4835 if (!network_thread()->IsCurrent()) {
4836 return network_thread()
4837 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4838 RTC_FROM_HERE,
4839 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004840 }
Steve Anton5dfde182018-02-06 10:34:40 -08004841 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4842 for (const std::string& transport_name : transport_names) {
4843 cricket::TransportStats transport_stats;
4844 bool success =
4845 transport_controller_->GetStats(transport_name, &transport_stats);
4846 if (success) {
4847 transport_stats_by_name[transport_name] = std::move(transport_stats);
4848 } else {
4849 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4850 << transport_name;
4851 }
4852 }
4853 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004854}
4855
4856bool PeerConnection::GetLocalCertificate(
4857 const std::string& transport_name,
4858 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4859 return transport_controller_->GetLocalCertificate(transport_name,
4860 certificate);
4861}
4862
4863std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4864 const std::string& transport_name) {
4865 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4866}
4867
4868cricket::DataChannelType PeerConnection::data_channel_type() const {
4869 return data_channel_type_;
4870}
4871
4872bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4873 return pending_ice_restarts_.find(content_name) !=
4874 pending_ice_restarts_.end();
4875}
4876
Steve Anton75737c02017-11-06 10:37:17 -08004877bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4878 return transport_controller_->NeedsIceRestart(content_name);
4879}
4880
4881void PeerConnection::OnCertificateReady(
4882 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4883 transport_controller_->SetLocalCertificate(certificate);
4884}
4885
4886void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004887 SetSessionError(SessionError::kTransport,
4888 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004889}
4890
4891void PeerConnection::OnTransportControllerConnectionState(
4892 cricket::IceConnectionState state) {
4893 switch (state) {
4894 case cricket::kIceConnectionConnecting:
4895 // If the current state is Connected or Completed, then there were
4896 // writable channels but now there are not, so the next state must
4897 // be Disconnected.
4898 // kIceConnectionConnecting is currently used as the default,
4899 // un-connected state by the TransportController, so its only use is
4900 // detecting disconnections.
4901 if (ice_connection_state_ ==
4902 PeerConnectionInterface::kIceConnectionConnected ||
4903 ice_connection_state_ ==
4904 PeerConnectionInterface::kIceConnectionCompleted) {
4905 SetIceConnectionState(
4906 PeerConnectionInterface::kIceConnectionDisconnected);
4907 }
4908 break;
4909 case cricket::kIceConnectionFailed:
4910 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4911 break;
4912 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004913 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004914 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004915 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4916 break;
4917 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004918 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004919 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004920 if (ice_connection_state_ !=
4921 PeerConnectionInterface::kIceConnectionConnected) {
4922 // If jumping directly from "checking" to "connected",
4923 // signal "connected" first.
4924 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4925 }
4926 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4927 if (metrics_observer()) {
4928 ReportTransportStats();
4929 }
4930 break;
4931 default:
4932 RTC_NOTREACHED();
4933 }
4934}
4935
4936void PeerConnection::OnTransportControllerCandidatesGathered(
4937 const std::string& transport_name,
4938 const cricket::Candidates& candidates) {
4939 RTC_DCHECK(signaling_thread()->IsCurrent());
4940 int sdp_mline_index;
4941 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004942 RTC_LOG(LS_ERROR)
4943 << "OnTransportControllerCandidatesGathered: content name "
4944 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004945 return;
4946 }
4947
4948 for (cricket::Candidates::const_iterator citer = candidates.begin();
4949 citer != candidates.end(); ++citer) {
4950 // Use transport_name as the candidate media id.
4951 std::unique_ptr<JsepIceCandidate> candidate(
4952 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4953 if (local_description()) {
4954 mutable_local_description()->AddCandidate(candidate.get());
4955 }
4956 OnIceCandidate(std::move(candidate));
4957 }
4958}
4959
4960void PeerConnection::OnTransportControllerCandidatesRemoved(
4961 const std::vector<cricket::Candidate>& candidates) {
4962 RTC_DCHECK(signaling_thread()->IsCurrent());
4963 // Sanity check.
4964 for (const cricket::Candidate& candidate : candidates) {
4965 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004966 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004967 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01004968 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004969 return;
4970 }
4971 }
4972
4973 if (local_description()) {
4974 mutable_local_description()->RemoveCandidates(candidates);
4975 }
4976 OnIceCandidatesRemoved(candidates);
4977}
4978
4979void PeerConnection::OnTransportControllerDtlsHandshakeError(
4980 rtc::SSLHandshakeError error) {
4981 if (metrics_observer()) {
4982 metrics_observer()->IncrementEnumCounter(
4983 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4984 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4985 }
4986}
4987
Steve Antoned10bd92017-12-05 10:52:59 -08004988void PeerConnection::EnableSending() {
4989 for (auto transceiver : transceivers_) {
4990 cricket::BaseChannel* channel = transceiver->internal()->channel();
4991 if (channel && !channel->enabled()) {
4992 channel->Enable(true);
4993 }
Steve Anton75737c02017-11-06 10:37:17 -08004994 }
4995
Steve Anton4171afb2017-11-20 10:20:22 -08004996 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004997 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004998 }
Steve Anton75737c02017-11-06 10:37:17 -08004999}
5000
5001// Returns the media index for a local ice candidate given the content name.
5002bool PeerConnection::GetLocalCandidateMediaIndex(
5003 const std::string& content_name,
5004 int* sdp_mline_index) {
5005 if (!local_description() || !sdp_mline_index) {
5006 return false;
5007 }
5008
5009 bool content_found = false;
5010 const ContentInfos& contents = local_description()->description()->contents();
5011 for (size_t index = 0; index < contents.size(); ++index) {
5012 if (contents[index].name == content_name) {
5013 *sdp_mline_index = static_cast<int>(index);
5014 content_found = true;
5015 break;
5016 }
5017 }
5018 return content_found;
5019}
5020
5021bool PeerConnection::UseCandidatesInSessionDescription(
5022 const SessionDescriptionInterface* remote_desc) {
5023 if (!remote_desc) {
5024 return true;
5025 }
5026 bool ret = true;
5027
5028 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5029 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5030 for (size_t n = 0; n < candidates->count(); ++n) {
5031 const IceCandidateInterface* candidate = candidates->at(n);
5032 bool valid = false;
5033 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5034 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005035 RTC_LOG(LS_INFO)
5036 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005037 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005038 }
5039 continue;
5040 }
5041 ret = UseCandidate(candidate);
5042 if (!ret) {
5043 break;
5044 }
5045 }
5046 }
5047 return ret;
5048}
5049
5050bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5051 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5052 size_t remote_content_size =
5053 remote_description()->description()->contents().size();
5054 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005055 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005056 return false;
5057 }
5058
5059 cricket::ContentInfo content =
5060 remote_description()->description()->contents()[mediacontent_index];
5061 std::vector<cricket::Candidate> candidates;
5062 candidates.push_back(candidate->candidate());
5063 // Invoking BaseSession method to handle remote candidates.
5064 std::string error;
5065 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5066 &error)) {
5067 // Candidates successfully submitted for checking.
5068 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5069 ice_connection_state_ ==
5070 PeerConnectionInterface::kIceConnectionDisconnected) {
5071 // If state is New, then the session has just gotten its first remote ICE
5072 // candidates, so go to Checking.
5073 // If state is Disconnected, the session is re-using old candidates or
5074 // receiving additional ones, so go to Checking.
5075 // If state is Connected, stay Connected.
5076 // TODO(bemasc): If state is Connected, and the new candidates are for a
5077 // newly added transport, then the state actually _should_ move to
5078 // checking. Add a way to distinguish that case.
5079 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5080 }
5081 // TODO(bemasc): If state is Completed, go back to Connected.
5082 } else {
5083 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005084 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005085 }
5086 }
5087 return true;
5088}
5089
5090void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005091 // Destroy video channel first since it may have a pointer to the
5092 // voice channel.
5093 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005094 if (!video_info || video_info->rejected) {
5095 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005096 }
5097
Steve Anton6fec8802017-12-04 10:37:29 -08005098 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5099 if (!audio_info || audio_info->rejected) {
5100 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
5102
5103 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5104 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005105 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005106 }
5107}
5108
Steve Antoneda6ccd2017-12-04 10:21:55 -08005109std::string PeerConnection::GetTransportNameForMediaSection(
5110 const std::string& mid,
5111 const cricket::ContentGroup* bundle_group) const {
5112 if (!bundle_group) {
5113 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005114 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005115 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005116 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005117 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005118 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005119 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005120 if (!bundle_group->HasContentName(mid)) {
5121 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5122 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005123 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005124 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5125 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005126}
5127
Steve Antondcc3c022017-12-22 16:02:54 -08005128RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5129 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005130 const cricket::ContentGroup* bundle_group = nullptr;
5131 if (configuration_.bundle_policy ==
5132 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005133 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005134 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005135 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5136 "max-bundle configured but session description "
5137 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005138 }
5139 }
Steve Antondcc3c022017-12-22 16:02:54 -08005140 return std::move(bundle_group);
5141}
5142
5143RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5144 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5145 if (!bundle_group_or_error.ok()) {
5146 return bundle_group_or_error.MoveError();
5147 }
5148 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005149
Steve Antoneda6ccd2017-12-04 10:21:55 -08005150 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005151 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005152 if (voice && !voice->rejected &&
5153 !GetAudioTransceiver()->internal()->channel()) {
5154 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5155 voice->name,
5156 GetTransportNameForMediaSection(voice->name, bundle_group));
5157 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005158 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5159 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005160 }
5161 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5162 }
5163
Steve Antondcc3c022017-12-22 16:02:54 -08005164 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005165 if (video && !video->rejected &&
5166 !GetVideoTransceiver()->internal()->channel()) {
5167 cricket::VideoChannel* video_channel = CreateVideoChannel(
5168 video->name,
5169 GetTransportNameForMediaSection(video->name, bundle_group));
5170 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005171 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5172 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005173 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005174 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005175 }
5176
Steve Antondcc3c022017-12-22 16:02:54 -08005177 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005178 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5179 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005180 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5181 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005182 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5183 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005184 }
5185 }
5186
Steve Anton8a006912017-12-04 15:25:56 -08005187 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005188}
5189
Steve Anton4171afb2017-11-20 10:20:22 -08005190// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005191cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5192 const std::string& mid,
5193 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005194 cricket::DtlsTransportInternal* rtp_dtls_transport =
5195 transport_controller_->CreateDtlsTransport(
5196 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5197 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5198 if (configuration_.rtcp_mux_policy !=
5199 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5200 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5201 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5202 }
5203
5204 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5205 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005206 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5207 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005208 if (!voice_channel) {
5209 transport_controller_->DestroyDtlsTransport(
5210 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5211 if (rtcp_dtls_transport) {
5212 transport_controller_->DestroyDtlsTransport(
5213 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5214 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005215 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005216 }
Steve Anton75737c02017-11-06 10:37:17 -08005217 voice_channel->SignalRtcpMuxFullyActive.connect(
5218 this, &PeerConnection::DestroyRtcpTransport_n);
5219 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5220 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005221 voice_channel->SignalSentPacket.connect(this,
5222 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005223
Steve Antoneda6ccd2017-12-04 10:21:55 -08005224 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005225}
5226
Steve Anton4171afb2017-11-20 10:20:22 -08005227// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005228cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5229 const std::string& mid,
5230 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005231 cricket::DtlsTransportInternal* rtp_dtls_transport =
5232 transport_controller_->CreateDtlsTransport(
5233 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5234 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5235 if (configuration_.rtcp_mux_policy !=
5236 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5237 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5238 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5239 }
5240
5241 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5242 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005243 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5244 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005245
5246 if (!video_channel) {
5247 transport_controller_->DestroyDtlsTransport(
5248 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5249 if (rtcp_dtls_transport) {
5250 transport_controller_->DestroyDtlsTransport(
5251 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5252 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005253 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005254 }
Steve Anton75737c02017-11-06 10:37:17 -08005255 video_channel->SignalRtcpMuxFullyActive.connect(
5256 this, &PeerConnection::DestroyRtcpTransport_n);
5257 video_channel->SignalDtlsSrtpSetupFailure.connect(
5258 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005259 video_channel->SignalSentPacket.connect(this,
5260 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005261
Steve Antoneda6ccd2017-12-04 10:21:55 -08005262 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005263}
5264
Steve Antoneda6ccd2017-12-04 10:21:55 -08005265bool PeerConnection::CreateDataChannel(const std::string& mid,
5266 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005267 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5268 if (sctp) {
5269 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005270 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005271 << "Trying to create SCTP transport, but didn't compile with "
5272 "SCTP support (HAVE_SCTP)";
5273 return false;
5274 }
5275 if (!network_thread()->Invoke<bool>(
5276 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005277 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005278 return false;
5279 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005280 for (const auto& channel : sctp_data_channels_) {
5281 channel->OnTransportChannelCreated();
5282 }
Steve Anton75737c02017-11-06 10:37:17 -08005283 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005284 cricket::DtlsTransportInternal* rtp_dtls_transport =
5285 transport_controller_->CreateDtlsTransport(
5286 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5287 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5288 if (configuration_.rtcp_mux_policy !=
5289 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5290 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5291 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5292 }
5293
5294 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5295 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005296 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005297
5298 if (!rtp_data_channel_) {
5299 transport_controller_->DestroyDtlsTransport(
5300 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5301 if (rtcp_dtls_transport) {
5302 transport_controller_->DestroyDtlsTransport(
5303 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5304 }
5305 return false;
5306 }
5307
5308 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5309 this, &PeerConnection::DestroyRtcpTransport_n);
5310 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5311 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5312 rtp_data_channel_->SignalSentPacket.connect(
5313 this, &PeerConnection::OnSentPacket_w);
5314 }
5315
Steve Anton75737c02017-11-06 10:37:17 -08005316 return true;
5317}
5318
5319Call::Stats PeerConnection::GetCallStats() {
5320 if (!worker_thread()->IsCurrent()) {
5321 return worker_thread()->Invoke<Call::Stats>(
5322 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5323 }
5324 if (call_) {
5325 return call_->GetStats();
5326 } else {
5327 return Call::Stats();
5328 }
5329}
5330
Steve Anton75737c02017-11-06 10:37:17 -08005331bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5332 const std::string& transport_name) {
5333 RTC_DCHECK(network_thread()->IsCurrent());
5334 RTC_DCHECK(sctp_factory_);
5335 cricket::DtlsTransportInternal* tc =
5336 transport_controller_->CreateDtlsTransport_n(
5337 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5338 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5339 RTC_DCHECK(sctp_transport_);
5340 sctp_invoker_.reset(new rtc::AsyncInvoker());
5341 sctp_transport_->SignalReadyToSendData.connect(
5342 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5343 sctp_transport_->SignalDataReceived.connect(
5344 this, &PeerConnection::OnSctpTransportDataReceived_n);
5345 sctp_transport_->SignalStreamClosedRemotely.connect(
5346 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005347 sctp_transport_name_ = transport_name;
5348 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005349 return true;
5350}
5351
5352void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5353 RTC_DCHECK(network_thread()->IsCurrent());
5354 RTC_DCHECK(sctp_transport_);
5355 RTC_DCHECK(sctp_transport_name_);
5356 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005357 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005358 cricket::DtlsTransportInternal* tc =
5359 transport_controller_->CreateDtlsTransport_n(
5360 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5361 sctp_transport_->SetTransportChannel(tc);
5362 transport_controller_->DestroyDtlsTransport_n(
5363 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5364}
5365
5366void PeerConnection::DestroySctpTransport_n() {
5367 RTC_DCHECK(network_thread()->IsCurrent());
5368 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005369 transport_controller_->DestroyDtlsTransport_n(
5370 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005371 sctp_content_name_.reset();
5372 sctp_transport_name_.reset();
5373 sctp_invoker_.reset(nullptr);
5374 sctp_ready_to_send_data_ = false;
5375}
5376
5377void PeerConnection::OnSctpTransportReadyToSendData_n() {
5378 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5379 RTC_DCHECK(network_thread()->IsCurrent());
5380 // Note: Cannot use rtc::Bind here because it will grab a reference to
5381 // PeerConnection and potentially cause PeerConnection to live longer than
5382 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5383 // be destroyed before PeerConnection is destroyed, and at that point all
5384 // pending tasks will be cleared.
5385 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5386 OnSctpTransportReadyToSendData_s(true);
5387 });
5388}
5389
5390void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5391 RTC_DCHECK(signaling_thread()->IsCurrent());
5392 sctp_ready_to_send_data_ = ready;
5393 SignalSctpReadyToSendData(ready);
5394}
5395
5396void PeerConnection::OnSctpTransportDataReceived_n(
5397 const cricket::ReceiveDataParams& params,
5398 const rtc::CopyOnWriteBuffer& payload) {
5399 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5400 RTC_DCHECK(network_thread()->IsCurrent());
5401 // Note: Cannot use rtc::Bind here because it will grab a reference to
5402 // PeerConnection and potentially cause PeerConnection to live longer than
5403 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5404 // be destroyed before PeerConnection is destroyed, and at that point all
5405 // pending tasks will be cleared.
5406 sctp_invoker_->AsyncInvoke<void>(
5407 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5408 OnSctpTransportDataReceived_s(params, payload);
5409 });
5410}
5411
5412void PeerConnection::OnSctpTransportDataReceived_s(
5413 const cricket::ReceiveDataParams& params,
5414 const rtc::CopyOnWriteBuffer& payload) {
5415 RTC_DCHECK(signaling_thread()->IsCurrent());
5416 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5417 // Received OPEN message; parse and signal that a new data channel should
5418 // be created.
5419 std::string label;
5420 InternalDataChannelInit config;
5421 config.id = params.ssrc;
5422 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005423 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5424 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005425 return;
5426 }
5427 config.open_handshake_role = InternalDataChannelInit::kAcker;
5428 OnDataChannelOpenMessage(label, config);
5429 } else {
5430 // Otherwise just forward the signal.
5431 SignalSctpDataReceived(params, payload);
5432 }
5433}
5434
5435void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5436 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5437 RTC_DCHECK(network_thread()->IsCurrent());
5438 sctp_invoker_->AsyncInvoke<void>(
5439 RTC_FROM_HERE, signaling_thread(),
5440 rtc::Bind(&sigslot::signal1<int>::operator(),
5441 &SignalSctpStreamClosedRemotely, sid));
5442}
5443
5444// Returns false if bundle is enabled and rtcp_mux is disabled.
5445bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5446 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5447 if (!bundle_enabled)
5448 return true;
5449
5450 const cricket::ContentGroup* bundle_group =
5451 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5452 RTC_DCHECK(bundle_group != NULL);
5453
5454 const cricket::ContentInfos& contents = desc->contents();
5455 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5456 citer != contents.end(); ++citer) {
5457 const cricket::ContentInfo* content = (&*citer);
5458 RTC_DCHECK(content != NULL);
5459 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005460 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005461 if (!HasRtcpMuxEnabled(content))
5462 return false;
5463 }
5464 }
5465 // RTCP-MUX is enabled in all the contents.
5466 return true;
5467}
5468
5469bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005470 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005471}
5472
Steve Anton8a006912017-12-04 15:25:56 -08005473RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005474 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005475 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005476 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005477 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
5479
5480 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005482 }
5483
Steve Anton3828c062017-12-06 10:34:51 -08005484 SdpType type = sdesc->GetType();
5485 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5486 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005487 LOG_AND_RETURN_ERROR(
5488 RTCErrorType::INVALID_PARAMETER,
5489 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005490 }
5491
5492 // Verify crypto settings.
5493 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005494 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5495 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005496 RTCError crypto_error =
5497 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005498 if (!crypto_error.ok()) {
5499 return crypto_error;
5500 }
Steve Anton75737c02017-11-06 10:37:17 -08005501 }
5502
5503 // Verify ice-ufrag and ice-pwd.
5504 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005505 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5506 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005507 }
5508
5509 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5511 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005512 }
5513
5514 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5515 // m-lines that do not rtcp-mux enabled.
5516
5517 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005518 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005519 const cricket::SessionDescription* offer_desc =
5520 (source == cricket::CS_LOCAL) ? remote_description()->description()
5521 : local_description()->description();
5522 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5523 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005524 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5525 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005526 }
5527 } else {
5528 const cricket::SessionDescription* current_desc = nullptr;
5529 if (source == cricket::CS_LOCAL && local_description()) {
5530 current_desc = local_description()->description();
5531 } else if (source == cricket::CS_REMOTE && remote_description()) {
5532 current_desc = remote_description()->description();
5533 }
5534 // The re-offers should respect the order of m= sections in current
5535 // description. See RFC3264 Section 8 paragraph 4 for more details.
5536 if (current_desc &&
5537 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5539 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005540 }
5541 }
5542
Steve Anton8a006912017-12-04 15:25:56 -08005543 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005544}
5545
Steve Anton3828c062017-12-06 10:34:51 -08005546bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005547 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005548 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005549 return (state == PeerConnectionInterface::kStable) ||
5550 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005551 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005552 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005553 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5554 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5555 }
5556}
5557
Steve Anton3828c062017-12-06 10:34:51 -08005558bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005559 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005560 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005561 return (state == PeerConnectionInterface::kStable) ||
5562 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005563 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005564 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005565 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5566 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5567 }
5568}
5569
Steve Antonf8470812017-12-04 10:46:21 -08005570const char* PeerConnection::SessionErrorToString(SessionError error) const {
5571 switch (error) {
5572 case SessionError::kNone:
5573 return "ERROR_NONE";
5574 case SessionError::kContent:
5575 return "ERROR_CONTENT";
5576 case SessionError::kTransport:
5577 return "ERROR_TRANSPORT";
5578 }
5579 RTC_NOTREACHED();
5580 return "";
5581}
5582
Steve Anton75737c02017-11-06 10:37:17 -08005583std::string PeerConnection::GetSessionErrorMsg() {
5584 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005585 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5586 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005587 return desc.str();
5588}
5589
5590// We need to check the local/remote description for the Transport instead of
5591// the session, because a new Transport added during renegotiation may have
5592// them unset while the session has them set from the previous negotiation.
5593// Not doing so may trigger the auto generation of transport description and
5594// mess up DTLS identity information, ICE credential, etc.
5595bool PeerConnection::ReadyToUseRemoteCandidate(
5596 const IceCandidateInterface* candidate,
5597 const SessionDescriptionInterface* remote_desc,
5598 bool* valid) {
5599 *valid = true;
5600
5601 const SessionDescriptionInterface* current_remote_desc =
5602 remote_desc ? remote_desc : remote_description();
5603
5604 if (!current_remote_desc) {
5605 return false;
5606 }
5607
5608 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5609 size_t remote_content_size =
5610 current_remote_desc->description()->contents().size();
5611 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005612 RTC_LOG(LS_ERROR)
5613 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5614 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005615
5616 *valid = false;
5617 return false;
5618 }
5619
5620 cricket::ContentInfo content =
5621 current_remote_desc->description()->contents()[mediacontent_index];
5622
5623 const std::string transport_name = GetTransportName(content.name);
5624 if (transport_name.empty()) {
5625 return false;
5626 }
5627 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5628}
5629
5630bool PeerConnection::SrtpRequired() const {
5631 return dtls_enabled_ ||
5632 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5633}
5634
5635void PeerConnection::OnTransportControllerGatheringState(
5636 cricket::IceGatheringState state) {
5637 RTC_DCHECK(signaling_thread()->IsCurrent());
5638 if (state == cricket::kIceGatheringGathering) {
5639 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5640 } else if (state == cricket::kIceGatheringComplete) {
5641 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5642 }
5643}
5644
5645void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005646 std::map<std::string, std::set<cricket::MediaType>>
5647 media_types_by_transport_name;
5648 for (auto transceiver : transceivers_) {
5649 if (transceiver->internal()->channel()) {
5650 const std::string& transport_name =
5651 transceiver->internal()->channel()->transport_name();
5652 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005653 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005654 }
Steve Anton75737c02017-11-06 10:37:17 -08005655 }
5656 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005657 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5658 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005659 }
5660 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005661 media_types_by_transport_name[*sctp_transport_name_].insert(
5662 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005663 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005664 for (const auto& entry : media_types_by_transport_name) {
5665 const std::string& transport_name = entry.first;
5666 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005667 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005668 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005669 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005670 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005671 }
5672 }
5673}
5674// Walk through the ConnectionInfos to gather best connection usage
5675// for IPv4 and IPv6.
5676void PeerConnection::ReportBestConnectionState(
5677 const cricket::TransportStats& stats) {
5678 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005679 for (const cricket::TransportChannelStats& channel_stats :
5680 stats.channel_stats) {
5681 for (const cricket::ConnectionInfo& connection_info :
5682 channel_stats.connection_infos) {
5683 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005684 continue;
5685 }
5686
5687 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005688 const cricket::Candidate& local = connection_info.local_candidate;
5689 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005690
5691 // Increment the counter for IceCandidatePairType.
5692 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5693 (local.type() == RELAY_PORT_TYPE &&
5694 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5695 type = kEnumCounterIceCandidatePairTypeTcp;
5696 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5697 type = kEnumCounterIceCandidatePairTypeUdp;
5698 } else {
5699 RTC_CHECK(0);
5700 }
5701 metrics_observer()->IncrementEnumCounter(
5702 type, GetIceCandidatePairCounter(local, remote),
5703 kIceCandidatePairMax);
5704
5705 // Increment the counter for IP type.
5706 if (local.address().family() == AF_INET) {
5707 metrics_observer()->IncrementEnumCounter(
5708 kEnumCounterAddressFamily, kBestConnections_IPv4,
5709 kPeerConnectionAddressFamilyCounter_Max);
5710
5711 } else if (local.address().family() == AF_INET6) {
5712 metrics_observer()->IncrementEnumCounter(
5713 kEnumCounterAddressFamily, kBestConnections_IPv6,
5714 kPeerConnectionAddressFamilyCounter_Max);
5715 } else {
5716 RTC_CHECK(0);
5717 }
5718
5719 return;
5720 }
5721 }
5722}
5723
5724void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005725 const cricket::TransportStats& stats,
5726 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005727 RTC_DCHECK(metrics_observer());
5728 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5729 return;
5730 }
5731
5732 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5733 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5734 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5735 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5736 return;
5737 }
5738
Steve Antonc7b964c2018-02-01 14:39:45 -08005739 for (cricket::MediaType media_type : media_types) {
5740 PeerConnectionEnumCounterType srtp_counter_type;
5741 PeerConnectionEnumCounterType ssl_counter_type;
5742 switch (media_type) {
5743 case cricket::MEDIA_TYPE_AUDIO:
5744 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5745 ssl_counter_type = kEnumCounterAudioSslCipher;
5746 break;
5747 case cricket::MEDIA_TYPE_VIDEO:
5748 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5749 ssl_counter_type = kEnumCounterVideoSslCipher;
5750 break;
5751 case cricket::MEDIA_TYPE_DATA:
5752 srtp_counter_type = kEnumCounterDataSrtpCipher;
5753 ssl_counter_type = kEnumCounterDataSslCipher;
5754 break;
5755 default:
5756 RTC_NOTREACHED();
5757 continue;
5758 }
5759 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5760 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5761 srtp_crypto_suite);
5762 }
5763 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5764 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5765 ssl_cipher_suite);
5766 }
Steve Anton75737c02017-11-06 10:37:17 -08005767 }
5768}
5769
5770void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5771 RTC_DCHECK(worker_thread()->IsCurrent());
5772 RTC_DCHECK(call_);
5773 call_->OnSentPacket(sent_packet);
5774}
5775
5776const std::string PeerConnection::GetTransportName(
5777 const std::string& content_name) {
5778 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005779 if (channel) {
5780 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
Steve Anton6fec8802017-12-04 10:37:29 -08005782 if (sctp_transport_) {
5783 RTC_DCHECK(sctp_content_name_);
5784 RTC_DCHECK(sctp_transport_name_);
5785 if (content_name == *sctp_content_name_) {
5786 return *sctp_transport_name_;
5787 }
5788 }
5789 // Return an empty string if failed to retrieve the transport name.
5790 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005791}
5792
5793void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5794 RTC_DCHECK(network_thread()->IsCurrent());
5795 transport_controller_->DestroyDtlsTransport_n(
5796 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5797}
5798
Steve Anton6fec8802017-12-04 10:37:29 -08005799void PeerConnection::DestroyTransceiverChannel(
5800 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5801 transceiver) {
5802 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005803
Steve Anton6fec8802017-12-04 10:37:29 -08005804 cricket::BaseChannel* channel = transceiver->internal()->channel();
5805 if (channel) {
5806 transceiver->internal()->SetChannel(nullptr);
5807 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005808 }
5809}
5810
5811void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005812 if (rtp_data_channel_) {
5813 OnDataChannelDestroyed();
5814 DestroyBaseChannel(rtp_data_channel_);
5815 rtp_data_channel_ = nullptr;
5816 }
5817
5818 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5819 // grab a reference to this PeerConnection. If this is called from the
5820 // PeerConnection destructor, the RefCountedObject vtable will have already
5821 // been destroyed (since it is a subclass of PeerConnection) and using
5822 // rtc::Bind will cause "Pure virtual function called" error to appear.
5823
5824 if (sctp_transport_) {
5825 OnDataChannelDestroyed();
5826 network_thread()->Invoke<void>(RTC_FROM_HERE,
5827 [this] { DestroySctpTransport_n(); });
5828 }
5829}
5830
5831void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5832 RTC_DCHECK(channel);
5833 RTC_DCHECK(channel->rtp_dtls_transport());
5834
5835 // Need to cache these before destroying the base channel so that we do not
5836 // access uninitialized memory.
5837 const std::string transport_name =
5838 channel->rtp_dtls_transport()->transport_name();
5839 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5840
5841 switch (channel->media_type()) {
5842 case cricket::MEDIA_TYPE_AUDIO:
5843 channel_manager()->DestroyVoiceChannel(
5844 static_cast<cricket::VoiceChannel*>(channel));
5845 break;
5846 case cricket::MEDIA_TYPE_VIDEO:
5847 channel_manager()->DestroyVideoChannel(
5848 static_cast<cricket::VideoChannel*>(channel));
5849 break;
5850 case cricket::MEDIA_TYPE_DATA:
5851 channel_manager()->DestroyRtpDataChannel(
5852 static_cast<cricket::RtpDataChannel*>(channel));
5853 break;
5854 default:
5855 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5856 break;
5857 }
5858
5859 // |channel| can no longer be used.
5860
Steve Anton75737c02017-11-06 10:37:17 -08005861 transport_controller_->DestroyDtlsTransport(
5862 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5863 if (need_to_delete_rtcp) {
5864 transport_controller_->DestroyDtlsTransport(
5865 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5866 }
5867}
5868
Harald Alvestrand89061872018-01-02 14:08:34 +01005869void PeerConnection::ClearStatsCache() {
5870 if (stats_collector_) {
5871 stats_collector_->ClearCachedStatsReport();
5872 }
5873}
5874
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005875} // namespace webrtc