blob: 87bef82f159ded78ce927b9b13518a3e3b65deef [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;
Steve Anton300bf8e2017-07-14 10:13:10 -0700586 bool enable_rtp_data_channel;
587 rtc::Optional<int> screencast_min_bitrate;
588 rtc::Optional<bool> combined_audio_video_bwe;
589 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800590 TcpCandidatePolicy tcp_candidate_policy;
591 CandidateNetworkPolicy candidate_network_policy;
592 int audio_jitter_buffer_max_packets;
593 bool audio_jitter_buffer_fast_accelerate;
594 int ice_connection_receiving_timeout;
595 int ice_backup_candidate_pair_ping_interval;
596 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800597 bool prioritize_most_likely_ice_candidate_pairs;
598 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800599 bool prune_turn_ports;
600 bool presume_writable_when_fully_relayed;
601 bool enable_ice_renomination;
602 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800603 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700604 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200605 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800606 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800607 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800608 };
609 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
610 "Did you add something to RTCConfiguration and forget to "
611 "update operator==?");
612 return type == o.type && servers == o.servers &&
613 bundle_policy == o.bundle_policy &&
614 rtcp_mux_policy == o.rtcp_mux_policy &&
615 tcp_candidate_policy == o.tcp_candidate_policy &&
616 candidate_network_policy == o.candidate_network_policy &&
617 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
618 audio_jitter_buffer_fast_accelerate ==
619 o.audio_jitter_buffer_fast_accelerate &&
620 ice_connection_receiving_timeout ==
621 o.ice_connection_receiving_timeout &&
622 ice_backup_candidate_pair_ping_interval ==
623 o.ice_backup_candidate_pair_ping_interval &&
624 continual_gathering_policy == o.continual_gathering_policy &&
625 certificates == o.certificates &&
626 prioritize_most_likely_ice_candidate_pairs ==
627 o.prioritize_most_likely_ice_candidate_pairs &&
628 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800629 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700630 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800631 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800632 screencast_min_bitrate == o.screencast_min_bitrate &&
633 combined_audio_video_bwe == o.combined_audio_video_bwe &&
634 enable_dtls_srtp == o.enable_dtls_srtp &&
635 ice_candidate_pool_size == o.ice_candidate_pool_size &&
636 prune_turn_ports == o.prune_turn_ports &&
637 presume_writable_when_fully_relayed ==
638 o.presume_writable_when_fully_relayed &&
639 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800640 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700641 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200642 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800643 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800644 sdp_semantics == o.sdp_semantics &&
645 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800646}
647
648bool PeerConnectionInterface::RTCConfiguration::operator!=(
649 const PeerConnectionInterface::RTCConfiguration& o) const {
650 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800651}
652
zhihuang8f65cdf2016-05-06 18:40:30 -0700653// Generate a RTCP CNAME when a PeerConnection is created.
654std::string GenerateRtcpCname() {
655 std::string cname;
656 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100657 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800658 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700659 }
660 return cname;
661}
662
zhihuang1c378ed2017-08-17 14:10:50 -0700663bool ValidateOfferAnswerOptions(
664 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
665 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
666 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700667}
668
zhihuang1c378ed2017-08-17 14:10:50 -0700669// From |rtc_options|, fill parts of |session_options| shared by all generated
670// m= sections (in other words, nothing that involves a map/array).
671void ExtractSharedMediaSessionOptions(
672 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
673 cricket::MediaSessionOptions* session_options) {
674 session_options->vad_enabled = rtc_options.voice_activity_detection;
675 session_options->bundle_enabled = rtc_options.use_rtp_mux;
676}
zhihuanga77e6bb2017-08-14 18:17:48 -0700677
zhihuang1c378ed2017-08-17 14:10:50 -0700678bool ConvertConstraintsToOfferAnswerOptions(
679 const MediaConstraintsInterface* constraints,
680 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700681 if (!constraints) {
682 return true;
683 }
zhihuang1c378ed2017-08-17 14:10:50 -0700684
685 bool value = false;
686 size_t mandatory_constraints_satisfied = 0;
687
688 if (FindConstraint(constraints,
689 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
690 &mandatory_constraints_satisfied)) {
691 offer_answer_options->offer_to_receive_audio =
692 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
693 kOfferToReceiveMediaTrue
694 : 0;
695 }
696
697 if (FindConstraint(constraints,
698 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
699 &mandatory_constraints_satisfied)) {
700 offer_answer_options->offer_to_receive_video =
701 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
702 kOfferToReceiveMediaTrue
703 : 0;
704 }
705 if (FindConstraint(constraints,
706 MediaConstraintsInterface::kVoiceActivityDetection, &value,
707 &mandatory_constraints_satisfied)) {
708 offer_answer_options->voice_activity_detection = value;
709 }
710 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
711 &mandatory_constraints_satisfied)) {
712 offer_answer_options->use_rtp_mux = value;
713 }
714 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
715 &value, &mandatory_constraints_satisfied)) {
716 offer_answer_options->ice_restart = value;
717 }
718
deadbeefab9b2d12015-10-14 11:33:11 -0700719 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
720}
721
zhihuang38ede132017-06-15 12:52:32 -0700722PeerConnection::PeerConnection(PeerConnectionFactory* factory,
723 std::unique_ptr<RtcEventLog> event_log,
724 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700726 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700727 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700728 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700729 remote_streams_(StreamCollection::Create()),
730 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731
732PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100733 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800734 RTC_DCHECK_RUN_ON(signaling_thread());
735
Steve Anton8af21862017-12-15 11:20:13 -0800736 // Need to stop transceivers before destroying the stats collector because
737 // AudioRtpSender has a reference to the StatsCollector it will update when
738 // stopping.
739 for (auto transceiver : transceivers_) {
740 transceiver->Stop();
741 }
Steve Anton4171afb2017-11-20 10:20:22 -0800742
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700743 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800744 if (stats_collector_) {
745 stats_collector_->WaitForPendingRequest();
746 stats_collector_ = nullptr;
747 }
Steve Anton75737c02017-11-06 10:37:17 -0800748
Steve Anton8af21862017-12-15 11:20:13 -0800749 // Don't destroy BaseChannels until after stats has been cleaned up so that
750 // the last stats request can still read from the channels.
751 DestroyAllChannels();
752
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800754
755 webrtc_session_desc_factory_.reset();
756 sctp_invoker_.reset();
757 sctp_factory_.reset();
758 transport_controller_.reset();
759
deadbeef91dd5672016-05-18 16:55:30 -0700760 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700761 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700762 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700763 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700764 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700765 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800766 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700767 event_log_.reset();
768 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769}
770
Steve Anton8af21862017-12-15 11:20:13 -0800771void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800772 // Destroy video channels first since they may have a pointer to a voice
773 // channel.
774 for (auto transceiver : transceivers_) {
775 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
776 DestroyTransceiverChannel(transceiver);
777 }
778 }
779 for (auto transceiver : transceivers_) {
780 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
781 DestroyTransceiverChannel(transceiver);
782 }
783 }
784 DestroyDataChannel();
785}
786
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000788 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700789 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200790 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800791 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100792 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700793
794 RTCError config_error = ValidateConfiguration(configuration);
795 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100796 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700797 return false;
798 }
799
deadbeef293e9262017-01-11 12:28:30 -0800800 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100801 RTC_LOG(LS_ERROR)
802 << "PeerConnection initialized without a PortAllocator? "
803 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800804 return false;
805 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200806
deadbeef653b8e02015-11-11 12:55:10 -0800807 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800808 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
810 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800811 return false;
812 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000813 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800814 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800815
deadbeef91dd5672016-05-18 16:55:30 -0700816 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700817 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700818 if (!network_thread()->Invoke<bool>(
819 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
820 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 return false;
822 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823
Steve Anton75737c02017-11-06 10:37:17 -0800824 // RFC 3264: The numeric value of the session id and version in the
825 // o line MUST be representable with a "64 bit signed integer".
826 // Due to this constraint session id |session_id_| is max limited to
827 // LLONG_MAX.
828 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
829 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800830 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
831 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800832 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
833 transport_controller_->SignalConnectionState.connect(
834 this, &PeerConnection::OnTransportControllerConnectionState);
835 transport_controller_->SignalGatheringState.connect(
836 this, &PeerConnection::OnTransportControllerGatheringState);
837 transport_controller_->SignalCandidatesGathered.connect(
838 this, &PeerConnection::OnTransportControllerCandidatesGathered);
839 transport_controller_->SignalCandidatesRemoved.connect(
840 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
841 transport_controller_->SignalDtlsHandshakeError.connect(
842 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
843
844 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700845
deadbeefab9b2d12015-10-14 11:33:11 -0700846 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700847 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848
Steve Antonba818672017-11-06 10:21:57 -0800849 configuration_ = configuration;
850
Steve Anton75737c02017-11-06 10:37:17 -0800851 const PeerConnectionFactoryInterface::Options& options = factory_->options();
852
853 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
854
855 // Obtain a certificate from RTCConfiguration if any were provided (optional).
856 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
857 if (!configuration.certificates.empty()) {
858 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
859 // just picking the first one. The decision should be made based on the DTLS
860 // handshake. The DTLS negotiations need to know about all certificates.
861 certificate = configuration.certificates[0];
862 }
863
Steve Antond25da372017-11-06 14:50:29 -0800864 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800865
866 if (options.disable_encryption) {
867 dtls_enabled_ = false;
868 } else {
869 // Enable DTLS by default if we have an identity store or a certificate.
870 dtls_enabled_ = (cert_generator || certificate);
871 // |configuration| can override the default |dtls_enabled_| value.
872 if (configuration.enable_dtls_srtp) {
873 dtls_enabled_ = *(configuration.enable_dtls_srtp);
874 }
875 }
876
877 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
878 // It takes precendence over the disable_sctp_data_channels
879 // PeerConnectionFactoryInterface::Options.
880 if (configuration.enable_rtp_data_channel) {
881 data_channel_type_ = cricket::DCT_RTP;
882 } else {
883 // DTLS has to be enabled to use SCTP.
884 if (!options.disable_sctp_data_channels && dtls_enabled_) {
885 data_channel_type_ = cricket::DCT_SCTP;
886 }
887 }
888
889 video_options_.screencast_min_bitrate_kbps =
890 configuration.screencast_min_bitrate;
891 audio_options_.combined_audio_video_bwe =
892 configuration.combined_audio_video_bwe;
893
894 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100895 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800896
897 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100898 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800899
900 // Whether the certificate generator/certificate is null or not determines
901 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
902 // the right instructions by clearing the variables if needed.
903 if (!dtls_enabled_) {
904 cert_generator.reset();
905 certificate = nullptr;
906 } else if (certificate) {
907 // Favor generated certificate over the certificate generator.
908 cert_generator.reset();
909 }
910
911 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
912 signaling_thread(), channel_manager(), this, session_id(),
913 std::move(cert_generator), certificate));
914 webrtc_session_desc_factory_->SignalCertificateReady.connect(
915 this, &PeerConnection::OnCertificateReady);
916
917 if (options.disable_encryption) {
918 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
919 }
920
921 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
922 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923
Steve Anton4171afb2017-11-20 10:20:22 -0800924 // Add default audio/video transceivers for Plan B SDP.
925 if (!IsUnifiedPlan()) {
926 transceivers_.push_back(
927 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
928 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
929 transceivers_.push_back(
930 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
931 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
932 }
933
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934 return true;
935}
936
Steve Anton038834f2017-07-14 15:59:59 -0700937RTCError PeerConnection::ValidateConfiguration(
938 const RTCConfiguration& config) const {
939 if (config.ice_regather_interval_range &&
940 config.continual_gathering_policy == GATHER_ONCE) {
941 return RTCError(RTCErrorType::INVALID_PARAMETER,
942 "ice_regather_interval_range specified but continual "
943 "gathering policy is GATHER_ONCE");
944 }
945 return RTCError::OK();
946}
947
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700950 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951}
952
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000953rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700955 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956}
957
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000958bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100959 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960 if (IsClosed()) {
961 return false;
962 }
deadbeefab9b2d12015-10-14 11:33:11 -0700963 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964 return false;
965 }
deadbeefab9b2d12015-10-14 11:33:11 -0700966
967 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800968 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
969 observer->SignalAudioTrackAdded.connect(this,
970 &PeerConnection::OnAudioTrackAdded);
971 observer->SignalAudioTrackRemoved.connect(
972 this, &PeerConnection::OnAudioTrackRemoved);
973 observer->SignalVideoTrackAdded.connect(this,
974 &PeerConnection::OnVideoTrackAdded);
975 observer->SignalVideoTrackRemoved.connect(
976 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700977 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700978
deadbeefab9b2d12015-10-14 11:33:11 -0700979 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700980 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700981 }
982 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700983 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700984 }
985
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000986 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987 observer_->OnRenegotiationNeeded();
988 return true;
989}
990
991void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100992 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700993 if (!IsClosed()) {
994 for (const auto& track : local_stream->GetAudioTracks()) {
995 RemoveAudioTrack(track.get(), local_stream);
996 }
997 for (const auto& track : local_stream->GetVideoTracks()) {
998 RemoveVideoTrack(track.get(), local_stream);
999 }
deadbeefab9b2d12015-10-14 11:33:11 -07001000 }
deadbeefab9b2d12015-10-14 11:33:11 -07001001 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001002 stream_observers_.erase(
1003 std::remove_if(
1004 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001005 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001006 return observer->stream()->label().compare(local_stream->label()) ==
1007 0;
1008 }),
1009 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 if (IsClosed()) {
1012 return;
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 observer_->OnRenegotiationNeeded();
1015}
1016
deadbeefe1f9d832016-01-14 15:35:42 -08001017rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1018 MediaStreamTrackInterface* track,
1019 std::vector<MediaStreamInterface*> streams) {
1020 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001021 std::vector<std::string> stream_labels;
1022 for (auto* stream : streams) {
1023 if (!stream) {
1024 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1025 return nullptr;
1026 }
1027 stream_labels.push_back(stream->label());
1028 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001029 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001030 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001031 return nullptr;
1032 }
Steve Antonf9381f02017-12-14 10:23:57 -08001033 return sender_or_error.MoveValue();
1034}
1035
Steve Anton2d6c76a2018-01-05 17:10:52 -08001036RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001037 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1038 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001039 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001040 if (!track) {
1041 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1042 }
1043 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1044 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1045 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1046 "Track has invalid kind: " + track->kind());
1047 }
1048 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1049 if (stream_labels.size() > 1u) {
1050 LOG_AND_RETURN_ERROR(
1051 RTCErrorType::UNSUPPORTED_OPERATION,
1052 "AddTrack with more than one stream is not currently supported.");
1053 }
1054 if (IsClosed()) {
1055 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1056 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001057 }
Steve Anton4171afb2017-11-20 10:20:22 -08001058 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001059 LOG_AND_RETURN_ERROR(
1060 RTCErrorType::INVALID_PARAMETER,
1061 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001062 }
Steve Antonf9381f02017-12-14 10:23:57 -08001063 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1064 // one stream. AddTrackInternal will return an error if there is more than one
1065 // stream, but if the caller specifies none then we need to generate a random
1066 // stream label.
1067 std::vector<std::string> adjusted_stream_labels = stream_labels;
1068 if (stream_labels.empty()) {
1069 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1070 }
1071 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1072 auto sender_or_error =
1073 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1074 : AddTrackPlanB(track, adjusted_stream_labels));
1075 if (sender_or_error.ok()) {
1076 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001077 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001078 }
1079 return sender_or_error;
1080}
deadbeefe1f9d832016-01-14 15:35:42 -08001081
Steve Antonf9381f02017-12-14 10:23:57 -08001082RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1083PeerConnection::AddTrackPlanB(
1084 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1085 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001086 cricket::MediaType media_type =
1087 (track->kind() == MediaStreamTrackInterface::kAudioKind
1088 ? cricket::MEDIA_TYPE_AUDIO
1089 : cricket::MEDIA_TYPE_VIDEO);
1090 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001091 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001092 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001093 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001094 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001095 const RtpSenderInfo* sender_info =
1096 FindSenderInfo(local_audio_sender_infos_,
1097 new_sender->internal()->stream_id(), track->id());
1098 if (sender_info) {
1099 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001100 }
Steve Antonf9381f02017-12-14 10:23:57 -08001101 } else {
1102 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001103 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001104 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001105 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001106 const RtpSenderInfo* sender_info =
1107 FindSenderInfo(local_video_sender_infos_,
1108 new_sender->internal()->stream_id(), track->id());
1109 if (sender_info) {
1110 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001111 }
deadbeefe1f9d832016-01-14 15:35:42 -08001112 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001113 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001114}
deadbeefe1f9d832016-01-14 15:35:42 -08001115
Steve Antonf9381f02017-12-14 10:23:57 -08001116RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1117PeerConnection::AddTrackUnifiedPlan(
1118 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1119 const std::vector<std::string>& stream_labels) {
1120 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1121 if (transceiver) {
1122 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1123 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1124 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1125 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1126 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001127 transceiver->sender()->SetTrack(track);
1128 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001129 } else {
1130 cricket::MediaType media_type =
1131 (track->kind() == MediaStreamTrackInterface::kAudioKind
1132 ? cricket::MEDIA_TYPE_AUDIO
1133 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001134 auto sender = CreateSender(media_type, track, stream_labels);
1135 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1136 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001137 transceiver->internal()->set_created_by_addtrack(true);
1138 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1139 }
Steve Antonf9381f02017-12-14 10:23:57 -08001140 return transceiver->sender();
1141}
1142
1143rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1144PeerConnection::FindFirstTransceiverForAddedTrack(
1145 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1146 RTC_DCHECK(track);
1147 for (auto transceiver : transceivers_) {
1148 if (!transceiver->sender()->track() &&
1149 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1150 track->kind() &&
1151 !transceiver->internal()->has_ever_been_used_to_send()) {
1152 return transceiver;
1153 }
1154 }
1155 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001156}
1157
1158bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1159 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001160 return RemoveTrackInternal(sender).ok();
1161}
1162
1163RTCError PeerConnection::RemoveTrackInternal(
1164 rtc::scoped_refptr<RtpSenderInterface> sender) {
1165 if (!sender) {
1166 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1167 }
deadbeefe1f9d832016-01-14 15:35:42 -08001168 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1170 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001171 }
Steve Antonf9381f02017-12-14 10:23:57 -08001172 if (IsUnifiedPlan()) {
1173 auto transceiver = FindTransceiverBySender(sender);
1174 if (!transceiver || !sender->track()) {
1175 return RTCError::OK();
1176 }
1177 sender->SetTrack(nullptr);
1178 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1179 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1180 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1181 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1182 }
Steve Anton4171afb2017-11-20 10:20:22 -08001183 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001184 bool removed;
1185 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1186 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1187 } else {
1188 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1189 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1190 }
1191 if (!removed) {
1192 LOG_AND_RETURN_ERROR(
1193 RTCErrorType::INVALID_PARAMETER,
1194 "Couldn't find sender " + sender->id() + " to remove.");
1195 }
Steve Anton4171afb2017-11-20 10:20:22 -08001196 }
deadbeefe1f9d832016-01-14 15:35:42 -08001197 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001198 return RTCError::OK();
1199}
1200
1201rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1202PeerConnection::FindTransceiverBySender(
1203 rtc::scoped_refptr<RtpSenderInterface> sender) {
1204 for (auto transceiver : transceivers_) {
1205 if (transceiver->sender() == sender) {
1206 return transceiver;
1207 }
1208 }
1209 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001210}
1211
Steve Anton9158ef62017-11-27 13:01:52 -08001212RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1213PeerConnection::AddTransceiver(
1214 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1215 return AddTransceiver(track, RtpTransceiverInit());
1216}
1217
1218RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1219PeerConnection::AddTransceiver(
1220 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1221 const RtpTransceiverInit& init) {
1222 if (!IsUnifiedPlan()) {
1223 LOG_AND_RETURN_ERROR(
1224 RTCErrorType::INTERNAL_ERROR,
1225 "AddTransceiver only supported when Unified Plan is enabled.");
1226 }
1227 if (!track) {
1228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1229 }
1230 cricket::MediaType media_type;
1231 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1232 media_type = cricket::MEDIA_TYPE_AUDIO;
1233 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1234 media_type = cricket::MEDIA_TYPE_VIDEO;
1235 } else {
1236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1237 "Track kind is not audio or video");
1238 }
1239 return AddTransceiver(media_type, track, init);
1240}
1241
1242RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1243PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1244 return AddTransceiver(media_type, RtpTransceiverInit());
1245}
1246
1247RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1248PeerConnection::AddTransceiver(cricket::MediaType media_type,
1249 const RtpTransceiverInit& init) {
1250 if (!IsUnifiedPlan()) {
1251 LOG_AND_RETURN_ERROR(
1252 RTCErrorType::INTERNAL_ERROR,
1253 "AddTransceiver only supported when Unified Plan is enabled.");
1254 }
1255 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1256 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1257 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1258 "media type is not audio or video");
1259 }
1260 return AddTransceiver(media_type, nullptr, init);
1261}
1262
1263RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1264PeerConnection::AddTransceiver(
1265 cricket::MediaType media_type,
1266 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001267 const RtpTransceiverInit& init,
1268 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001269 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1270 media_type == cricket::MEDIA_TYPE_VIDEO));
1271 if (track) {
1272 RTC_DCHECK_EQ(media_type,
1273 (track->kind() == MediaStreamTrackInterface::kAudioKind
1274 ? cricket::MEDIA_TYPE_AUDIO
1275 : cricket::MEDIA_TYPE_VIDEO));
1276 }
1277
1278 // TODO(bugs.webrtc.org/7600): Verify init.
1279
Steve Anton02ee47c2018-01-10 16:26:06 -08001280 if (init.stream_labels.size() > 1u) {
1281 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1282 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001283 }
1284
Steve Anton02ee47c2018-01-10 16:26:06 -08001285 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1286 ? init.stream_labels[0]
1287 : rtc::CreateRandomUuid()};
1288
1289 auto sender = CreateSender(media_type, track, stream_labels);
1290 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1291 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1292 transceiver->internal()->set_direction(init.direction);
1293
Steve Anton22da89f2018-01-25 13:58:07 -08001294 if (fire_callback) {
1295 observer_->OnRenegotiationNeeded();
1296 }
Steve Antonf9381f02017-12-14 10:23:57 -08001297
1298 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1299}
1300
Steve Anton02ee47c2018-01-10 16:26:06 -08001301rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1302PeerConnection::CreateSender(
1303 cricket::MediaType media_type,
1304 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1305 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001306 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001307 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1308 RTC_DCHECK(!track ||
1309 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1310 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1311 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001312 new AudioRtpSender(worker_thread(),
1313 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001314 stream_labels, stats_.get()));
1315 } else {
1316 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1317 RTC_DCHECK(!track ||
1318 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1319 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1320 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001321 new VideoRtpSender(worker_thread(),
1322 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001323 stream_labels));
1324 }
1325 sender->internal()->set_stream_ids(stream_labels);
1326 return sender;
1327}
1328
1329rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1330PeerConnection::CreateReceiver(cricket::MediaType media_type,
1331 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001332 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1333 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001334 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001335 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001336 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001337 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001338 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001339 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001340 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1341 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001342 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001343 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001344 return receiver;
1345}
1346
1347rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1348PeerConnection::CreateAndAddTransceiver(
1349 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1350 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1351 receiver) {
1352 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1353 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001354 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001355 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001356}
1357
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001358rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001360 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001361 if (IsClosed()) {
1362 return nullptr;
1363 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001365 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001366 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 }
Steve Anton4171afb2017-11-20 10:20:22 -08001368 auto track_sender = FindSenderForTrack(track);
1369 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001370 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001371 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 }
1373
Steve Anton4171afb2017-11-20 10:20:22 -08001374 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375}
1376
deadbeeffac06552015-11-25 11:26:01 -08001377rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001378 const std::string& kind,
1379 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001380 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001381 if (IsClosed()) {
1382 return nullptr;
1383 }
Steve Anton4171afb2017-11-20 10:20:22 -08001384
Steve Anton02ee47c2018-01-10 16:26:06 -08001385 std::vector<std::string> stream_labels;
1386 if (!stream_id.empty()) {
1387 stream_labels.push_back(stream_id);
1388 }
1389
Steve Anton4171afb2017-11-20 10:20:22 -08001390 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001391 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001392 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001393 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1394 stream_labels, stats_.get());
1395 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001396 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001397 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001398 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001399 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001400 auto* video_sender =
1401 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1402 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001403 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001405 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001406 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001407 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001408 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001409 }
Steve Anton4171afb2017-11-20 10:20:22 -08001410
deadbeefe1f9d832016-01-14 15:35:42 -08001411 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001412}
1413
deadbeef70ab1a12015-09-28 16:53:55 -07001414std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1415 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001416 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001417 for (auto sender : GetSendersInternal()) {
1418 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001419 }
1420 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001421}
1422
Steve Anton4171afb2017-11-20 10:20:22 -08001423std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1424PeerConnection::GetSendersInternal() const {
1425 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1426 all_senders;
1427 for (auto transceiver : transceivers_) {
1428 auto senders = transceiver->internal()->senders();
1429 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1430 }
1431 return all_senders;
1432}
1433
deadbeef70ab1a12015-09-28 16:53:55 -07001434std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1435PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001436 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001437 for (const auto& receiver : GetReceiversInternal()) {
1438 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001439 }
1440 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001441}
1442
Steve Anton4171afb2017-11-20 10:20:22 -08001443std::vector<
1444 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1445PeerConnection::GetReceiversInternal() const {
1446 std::vector<
1447 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1448 all_receivers;
1449 for (auto transceiver : transceivers_) {
1450 auto receivers = transceiver->internal()->receivers();
1451 all_receivers.insert(all_receivers.end(), receivers.begin(),
1452 receivers.end());
1453 }
1454 return all_receivers;
1455}
1456
Steve Anton9158ef62017-11-27 13:01:52 -08001457std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1458PeerConnection::GetTransceivers() const {
1459 RTC_DCHECK(IsUnifiedPlan());
1460 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1461 for (auto transceiver : transceivers_) {
1462 all_transceivers.push_back(transceiver);
1463 }
1464 return all_transceivers;
1465}
1466
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001468 MediaStreamTrackInterface* track,
1469 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001470 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001471 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001472 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001473 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 return false;
1475 }
1476
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001477 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001478 // The StatsCollector is used to tell if a track is valid because it may
1479 // remember tracks that the PeerConnection previously removed.
1480 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001481 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1482 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001483 return false;
1484 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001485 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001486 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487 return true;
1488}
1489
hbos74e1a4f2016-09-15 23:33:01 -07001490void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1491 RTC_DCHECK(stats_collector_);
1492 stats_collector_->GetStatsReport(callback);
1493}
1494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1496 return signaling_state_;
1497}
1498
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499PeerConnectionInterface::IceConnectionState
1500PeerConnection::ice_connection_state() {
1501 return ice_connection_state_;
1502}
1503
1504PeerConnectionInterface::IceGatheringState
1505PeerConnection::ice_gathering_state() {
1506 return ice_gathering_state_;
1507}
1508
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001509rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510PeerConnection::CreateDataChannel(
1511 const std::string& label,
1512 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001513 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001514
deadbeefab9b2d12015-10-14 11:33:11 -07001515 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001516
kwibergd1fe2812016-04-27 06:47:29 -07001517 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001518 if (config) {
1519 internal_config.reset(new InternalDataChannelInit(*config));
1520 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001521 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001522 InternalCreateDataChannel(label, internal_config.get()));
1523 if (!channel.get()) {
1524 return nullptr;
1525 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001527 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1528 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001529 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001530 observer_->OnRenegotiationNeeded();
1531 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 return DataChannelProxy::Create(signaling_thread(), channel.get());
1534}
1535
1536void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1537 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001538 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001539
zhihuang1c378ed2017-08-17 14:10:50 -07001540 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1541 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1542 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1543 // compares the mandatory fields parsed with the mandatory fields added in the
1544 // |constraints| and some downstream applications might create offers with
1545 // mandatory fields which would not be parsed in the helper method. For
1546 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1547 // |constraints| as a mandatory field but it is not parsed.
1548 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001549
zhihuang1c378ed2017-08-17 14:10:50 -07001550 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001551}
1552
1553void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1554 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001555 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001556
nisse7ce109a2017-01-31 00:57:56 -08001557 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001558 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001559 return;
1560 }
deadbeefab9b2d12015-10-14 11:33:11 -07001561
Steve Anton8d3444d2017-10-20 15:30:51 -07001562 if (IsClosed()) {
1563 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001564 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001565 PostCreateSessionDescriptionFailure(observer, error);
1566 return;
1567 }
1568
zhihuang1c378ed2017-08-17 14:10:50 -07001569 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001570 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001571 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001572 PostCreateSessionDescriptionFailure(observer, error);
1573 return;
1574 }
1575
Steve Anton22da89f2018-01-25 13:58:07 -08001576 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1577 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1578 if (IsUnifiedPlan()) {
1579 RTCError error = HandleLegacyOfferOptions(options);
1580 if (!error.ok()) {
1581 PostCreateSessionDescriptionFailure(observer, error.message());
1582 return;
1583 }
1584 }
1585
zhihuang1c378ed2017-08-17 14:10:50 -07001586 cricket::MediaSessionOptions session_options;
1587 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001588 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001589}
1590
Steve Anton22da89f2018-01-25 13:58:07 -08001591RTCError PeerConnection::HandleLegacyOfferOptions(
1592 const RTCOfferAnswerOptions& options) {
1593 RTC_DCHECK(IsUnifiedPlan());
1594
1595 if (options.offer_to_receive_audio == 0) {
1596 RemoveRecvDirectionFromReceivingTransceiversOfType(
1597 cricket::MEDIA_TYPE_AUDIO);
1598 } else if (options.offer_to_receive_audio == 1) {
1599 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1600 } else if (options.offer_to_receive_audio > 1) {
1601 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1602 "offer_to_receive_audio > 1 is not supported.");
1603 }
1604
1605 if (options.offer_to_receive_video == 0) {
1606 RemoveRecvDirectionFromReceivingTransceiversOfType(
1607 cricket::MEDIA_TYPE_VIDEO);
1608 } else if (options.offer_to_receive_video == 1) {
1609 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1610 } else if (options.offer_to_receive_video > 1) {
1611 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1612 "offer_to_receive_video > 1 is not supported.");
1613 }
1614
1615 return RTCError::OK();
1616}
1617
1618void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1619 cricket::MediaType media_type) {
1620 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1621 transceiver->internal()->set_direction(
1622 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1623 }
1624}
1625
1626void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1627 cricket::MediaType media_type) {
1628 if (GetReceivingTransceiversOfType(media_type).empty()) {
1629 RtpTransceiverInit init;
1630 init.direction = RtpTransceiverDirection::kRecvOnly;
1631 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1632 }
1633}
1634
1635std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1636PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1637 std::vector<
1638 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1639 receiving_transceivers;
1640 for (auto transceiver : transceivers_) {
1641 if (!transceiver->stopped() &&
1642 transceiver->internal()->media_type() == media_type &&
1643 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1644 receiving_transceivers.push_back(transceiver);
1645 }
1646 }
1647 return receiving_transceivers;
1648}
1649
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001650void PeerConnection::CreateAnswer(
1651 CreateSessionDescriptionObserver* observer,
1652 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001653 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001654
nisse7ce109a2017-01-31 00:57:56 -08001655 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001656 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657 return;
1658 }
deadbeefab9b2d12015-10-14 11:33:11 -07001659
zhihuang1c378ed2017-08-17 14:10:50 -07001660 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1661 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1662 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001663 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001665 PostCreateSessionDescriptionFailure(observer, error);
1666 return;
1667 }
1668
Steve Anton8d3444d2017-10-20 15:30:51 -07001669 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001670}
1671
1672void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1673 const RTCOfferAnswerOptions& options) {
1674 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001675 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001676 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001677 return;
1678 }
1679
Oleh Prypinc22d6a82018-02-02 08:42:18 +00001680 if (IsClosed()) {
1681 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001683 PostCreateSessionDescriptionFailure(observer, error);
1684 return;
1685 }
1686
Oleh Prypinc22d6a82018-02-02 08:42:18 +00001687 if (remote_description() &&
1688 remote_description()->GetType() != SdpType::kOffer) {
1689 std::string error = "CreateAnswer called without remote offer.";
1690 RTC_LOG(LS_ERROR) << error;
1691 PostCreateSessionDescriptionFailure(observer, error);
1692 return;
1693 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001694
Steve Anton22da89f2018-01-25 13:58:07 -08001695 if (IsUnifiedPlan()) {
1696 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1697 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1698 "supported with Unified Plan semantics. Use the "
1699 "RtpTransceiver API instead.";
1700 }
1701 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1702 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1703 "supported with Unified Plan semantics. Use the "
1704 "RtpTransceiver API instead.";
1705 }
1706 }
1707
htaa2a49d92016-03-04 02:51:39 -08001708 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001709 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001710
Steve Antond25da372017-11-06 14:50:29 -08001711 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001712}
1713
1714void PeerConnection::SetLocalDescription(
1715 SetSessionDescriptionObserver* observer,
1716 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001717 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001718
nisse7ce109a2017-01-31 00:57:56 -08001719 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001720 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 return;
1722 }
Steve Anton8a006912017-12-04 15:25:56 -08001723
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724 if (!desc) {
1725 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1726 return;
1727 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001728
Steve Antona3a92c22017-12-07 10:27:41 -08001729 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001730
Steve Anton8a006912017-12-04 15:25:56 -08001731 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1732 // |desc| may be destroyed at this point.
1733
1734 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001735 std::ostringstream oss;
1736 oss << "Failed to set local " << SdpTypeToString(type)
1737 << " sdp: " << error.message();
1738 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001739 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1740 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001741 return;
1742 }
Steve Anton8a006912017-12-04 15:25:56 -08001743 RTC_DCHECK(local_description());
1744
1745 PostSetSessionDescriptionSuccess(observer);
1746
1747 // According to JSEP, after setLocalDescription, changing the candidate pool
1748 // size is not allowed, and changing the set of ICE servers will not result
1749 // in new candidates being gathered.
1750 port_allocator_->FreezeCandidatePool();
1751
1752 // MaybeStartGathering needs to be called after posting
1753 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1754 // before signaling that SetLocalDescription completed.
1755 transport_controller_->MaybeStartGathering();
1756
Steve Antona3a92c22017-12-07 10:27:41 -08001757 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001758 // TODO(deadbeef): We already had to hop to the network thread for
1759 // MaybeStartGathering...
1760 network_thread()->Invoke<void>(
1761 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1762 port_allocator_.get()));
1763 }
1764}
1765
1766RTCError PeerConnection::ApplyLocalDescription(
1767 std::unique_ptr<SessionDescriptionInterface> desc) {
1768 RTC_DCHECK_RUN_ON(signaling_thread());
1769 RTC_DCHECK(desc);
1770
1771 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1772 if (!error.ok()) {
1773 return error;
1774 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001775
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776 // Update stats here so that we have the most recent stats for tracks and
1777 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001778 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001779
1780 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001781 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001782 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001783 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001784 if (*initial_offerer_) {
1785 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1786 } else {
1787 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1788 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789 }
Steve Anton8a006912017-12-04 15:25:56 -08001790
Steve Antondcc3c022017-12-22 16:02:54 -08001791 // Take a reference to the old local description since it's used below to
1792 // compare against the new local description. When setting the new local
1793 // description, grab ownership of the replaced session description in case it
1794 // is the same as |old_local_description|, to keep it alive for the duration
1795 // of the method.
1796 const SessionDescriptionInterface* old_local_description =
1797 local_description();
1798 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001799 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001800 replaced_local_description = pending_local_description_
1801 ? std::move(pending_local_description_)
1802 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001803 current_local_description_ = std::move(desc);
1804 pending_local_description_ = nullptr;
1805 current_remote_description_ = std::move(pending_remote_description_);
1806 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001807 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001808 pending_local_description_ = std::move(desc);
1809 }
1810 // The session description to apply now must be accessed by
1811 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001812 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001813
Steve Antondcc3c022017-12-22 16:02:54 -08001814 if (IsUnifiedPlan()) {
1815 RTCError error = UpdateTransceiversAndDataChannels(
1816 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001817 if (!error.ok()) {
1818 return error;
1819 }
Steve Antondcc3c022017-12-22 16:02:54 -08001820 for (auto transceiver : transceivers_) {
1821 const ContentInfo* content =
1822 FindMediaSectionForTransceiver(transceiver, local_description());
1823 if (!content) {
1824 continue;
1825 }
1826 const MediaContentDescription* media_desc = content->media_description();
1827 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1828 transceiver->internal()->set_current_direction(media_desc->direction());
1829 }
1830 if (content->rejected && !transceiver->stopped()) {
1831 transceiver->Stop();
1832 }
1833 }
1834 } else {
1835 // Transport and Media channels will be created only when offer is set.
1836 if (type == SdpType::kOffer) {
1837 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1838 // description is applied. Restore back to old description.
1839 RTCError error = CreateChannels(*local_description()->description());
1840 if (!error.ok()) {
1841 return error;
1842 }
1843 }
Steve Anton8a006912017-12-04 15:25:56 -08001844
Steve Antondcc3c022017-12-22 16:02:54 -08001845 // Remove unused channels if MediaContentDescription is rejected.
1846 RemoveUnusedChannels(local_description()->description());
1847 }
Steve Anton8a006912017-12-04 15:25:56 -08001848
Steve Anton3828c062017-12-06 10:34:51 -08001849 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001850 if (!error.ok()) {
1851 return error;
1852 }
Steve Antondcc3c022017-12-22 16:02:54 -08001853
Steve Anton8a006912017-12-04 15:25:56 -08001854 if (remote_description()) {
1855 // Now that we have a local description, we can push down remote candidates.
1856 UseCandidatesInSessionDescription(remote_description());
1857 }
1858
1859 pending_ice_restarts_.clear();
1860 if (session_error() != SessionError::kNone) {
1861 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1862 }
1863
deadbeefab9b2d12015-10-14 11:33:11 -07001864 // If setting the description decided our SSL role, allocate any necessary
1865 // SCTP sids.
1866 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001867 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001868 AllocateSctpSids(role);
1869 }
1870
Steve Antond3679212018-01-17 17:41:02 -08001871 if (IsUnifiedPlan()) {
1872 for (auto transceiver : transceivers_) {
1873 const ContentInfo* content =
1874 FindMediaSectionForTransceiver(transceiver, local_description());
1875 if (!content) {
1876 continue;
1877 }
1878 if (content->rejected && !transceiver->stopped()) {
1879 transceiver->Stop();
1880 }
Steve Anton74255ff2018-01-24 18:32:57 -08001881 const auto& streams = content->media_description()->streams();
1882 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001883 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001884 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001885 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001886 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001887 }
1888 }
1889 } else {
1890 // Plan B semantics.
1891
Steve Antondcc3c022017-12-22 16:02:54 -08001892 // Update state and SSRC of local MediaStreams and DataChannels based on the
1893 // local session description.
1894 const cricket::ContentInfo* audio_content =
1895 GetFirstAudioContent(local_description()->description());
1896 if (audio_content) {
1897 if (audio_content->rejected) {
1898 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1899 } else {
1900 const cricket::AudioContentDescription* audio_desc =
1901 audio_content->media_description()->as_audio();
1902 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1903 }
deadbeeffaac4972015-11-12 15:33:07 -08001904 }
deadbeefab9b2d12015-10-14 11:33:11 -07001905
Steve Antondcc3c022017-12-22 16:02:54 -08001906 const cricket::ContentInfo* video_content =
1907 GetFirstVideoContent(local_description()->description());
1908 if (video_content) {
1909 if (video_content->rejected) {
1910 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1911 } else {
1912 const cricket::VideoContentDescription* video_desc =
1913 video_content->media_description()->as_video();
1914 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1915 }
deadbeeffaac4972015-11-12 15:33:07 -08001916 }
deadbeefab9b2d12015-10-14 11:33:11 -07001917 }
1918
1919 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001920 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001921 if (data_content) {
1922 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001923 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001924 if (rtc::starts_with(data_desc->protocol().data(),
1925 cricket::kMediaProtocolRtpPrefix)) {
1926 UpdateLocalRtpDataChannels(data_desc->streams());
1927 }
1928 }
1929
Steve Anton8a006912017-12-04 15:25:56 -08001930 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931}
1932
1933void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001934 SetSessionDescriptionObserver* observer,
1935 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001936 SetRemoteDescription(
1937 std::unique_ptr<SessionDescriptionInterface>(desc),
1938 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1939 new SetRemoteDescriptionObserverAdapter(this, observer)));
1940}
1941
1942void PeerConnection::SetRemoteDescription(
1943 std::unique_ptr<SessionDescriptionInterface> desc,
1944 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001945 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001946
nisse7ce109a2017-01-31 00:57:56 -08001947 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001948 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 return;
1950 }
Steve Anton8a006912017-12-04 15:25:56 -08001951
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001953 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001954 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955 return;
1956 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001957
Steve Antona3a92c22017-12-07 10:27:41 -08001958 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001959
1960 RTCError error = ApplyRemoteDescription(std::move(desc));
1961 // |desc| may be destroyed at this point.
1962
1963 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001964 std::ostringstream oss;
1965 oss << "Failed to set remote " << SdpTypeToString(type)
1966 << " sdp: " << error.message();
1967 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001968 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001969 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001970 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001971 return;
1972 }
1973
Steve Antona3a92c22017-12-07 10:27:41 -08001974 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001975 // TODO(deadbeef): We already had to hop to the network thread for
1976 // MaybeStartGathering...
1977 network_thread()->Invoke<void>(
1978 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1979 port_allocator_.get()));
1980 }
1981
1982 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1983}
1984
1985RTCError PeerConnection::ApplyRemoteDescription(
1986 std::unique_ptr<SessionDescriptionInterface> desc) {
1987 RTC_DCHECK_RUN_ON(signaling_thread());
1988 RTC_DCHECK(desc);
1989
1990 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1991 if (!error.ok()) {
1992 return error;
1993 }
1994
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 // Update stats here so that we have the most recent stats for tracks and
1996 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001997 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001998
Steve Antondcc3c022017-12-22 16:02:54 -08001999 // Take a reference to the old remote description since it's used below to
2000 // compare against the new remote description. When setting the new remote
2001 // description, grab ownership of the replaced session description in case it
2002 // is the same as |old_remote_description|, to keep it alive for the duration
2003 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002004 const SessionDescriptionInterface* old_remote_description =
2005 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002006 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002007 SdpType type = desc->GetType();
2008 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002009 replaced_remote_description = pending_remote_description_
2010 ? std::move(pending_remote_description_)
2011 : std::move(current_remote_description_);
2012 current_remote_description_ = std::move(desc);
2013 pending_remote_description_ = nullptr;
2014 current_local_description_ = std::move(pending_local_description_);
2015 } else {
2016 replaced_remote_description = std::move(pending_remote_description_);
2017 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018 }
Steve Anton8a006912017-12-04 15:25:56 -08002019 // The session description to apply now must be accessed by
2020 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002021 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022
Steve Anton8a006912017-12-04 15:25:56 -08002023 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002024 if (IsUnifiedPlan()) {
2025 RTCError error = UpdateTransceiversAndDataChannels(
2026 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002027 if (!error.ok()) {
2028 return error;
2029 }
Steve Antondcc3c022017-12-22 16:02:54 -08002030 } else {
2031 if (type == SdpType::kOffer) {
2032 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2033 // description is applied. Restore back to old description.
2034 RTCError error = CreateChannels(*remote_description()->description());
2035 if (!error.ok()) {
2036 return error;
2037 }
2038 }
Steve Anton8a006912017-12-04 15:25:56 -08002039
Steve Antondcc3c022017-12-22 16:02:54 -08002040 // Remove unused channels if MediaContentDescription is rejected.
2041 RemoveUnusedChannels(remote_description()->description());
2042 }
Steve Anton8a006912017-12-04 15:25:56 -08002043
2044 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2045 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002046 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002047 if (!error.ok()) {
2048 return error;
2049 }
2050
2051 if (local_description() &&
2052 !UseCandidatesInSessionDescription(remote_description())) {
2053 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2054 }
2055
2056 if (old_remote_description) {
2057 for (const cricket::ContentInfo& content :
2058 old_remote_description->description()->contents()) {
2059 // Check if this new SessionDescription contains new ICE ufrag and
2060 // password that indicates the remote peer requests an ICE restart.
2061 // TODO(deadbeef): When we start storing both the current and pending
2062 // remote description, this should reset pending_ice_restarts and compare
2063 // against the current description.
2064 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2065 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002066 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002067 pending_ice_restarts_.insert(content.name);
2068 }
2069 } else {
2070 // We retain all received candidates only if ICE is not restarted.
2071 // When ICE is restarted, all previous candidates belong to an old
2072 // generation and should not be kept.
2073 // TODO(deadbeef): This goes against the W3C spec which says the remote
2074 // description should only contain candidates from the last set remote
2075 // description plus any candidates added since then. We should remove
2076 // this once we're sure it won't break anything.
2077 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2078 old_remote_description, content.name, mutable_remote_description());
2079 }
2080 }
2081 }
2082
2083 if (session_error() != SessionError::kNone) {
2084 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2085 }
2086
2087 // Set the the ICE connection state to connecting since the connection may
2088 // become writable with peer reflexive candidates before any remote candidate
2089 // is signaled.
2090 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2091 // is to have a new signal the indicates a change in checking state from the
2092 // transport and expose a new checking() member from transport that can be
2093 // read to determine the current checking state. The existing SignalConnecting
2094 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002095 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002096 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2097 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2098 }
2099
deadbeefab9b2d12015-10-14 11:33:11 -07002100 // If setting the description decided our SSL role, allocate any necessary
2101 // SCTP sids.
2102 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002103 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002104 AllocateSctpSids(role);
2105 }
2106
Steve Antondcc3c022017-12-22 16:02:54 -08002107 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002108 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002109 for (auto transceiver : transceivers_) {
2110 const ContentInfo* content =
2111 FindMediaSectionForTransceiver(transceiver, remote_description());
2112 if (!content) {
2113 continue;
2114 }
2115 const MediaContentDescription* media_desc = content->media_description();
2116 RtpTransceiverDirection local_direction =
2117 RtpTransceiverDirectionReversed(media_desc->direction());
2118 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2119 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2120 // transceiver's current direction is neither sendrecv nor recvonly,
2121 // process the addition of a remote track for the media description.
2122 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2123 (!transceiver->current_direction() ||
2124 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002125 *transceiver->current_direction())) &&
2126 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002127 const std::string& sync_label = media_desc->streams()[0].sync_label;
2128 rtc::scoped_refptr<MediaStreamInterface> stream =
2129 remote_streams_->find(sync_label);
2130 if (!stream) {
2131 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2132 MediaStream::Create(sync_label));
2133 remote_streams_->AddStream(stream);
2134 }
2135 transceiver->internal()->receiver_internal()->SetStreams({stream});
2136 TrackEvent track_event;
2137 track_event.receiver = transceiver->receiver();
2138 track_event.streams = transceiver->receiver()->streams();
2139 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002140 }
2141 // If direction is sendonly or inactive, and transceiver's current
2142 // direction is neither sendonly nor inactive, process the removal of a
2143 // remote track for the media description.
2144 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002145 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002146 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002147 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002148 }
2149 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2150 transceiver->internal()->set_current_direction(local_direction);
2151 }
2152 if (content->rejected && !transceiver->stopped()) {
2153 transceiver->Stop();
2154 }
Steve Anton74255ff2018-01-24 18:32:57 -08002155 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002156 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002157 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002158 }
Steve Antondcc3c022017-12-22 16:02:54 -08002159 }
Steve Antonef65ef12018-01-10 17:15:20 -08002160 for (auto event : track_events) {
2161 observer_->OnAddTrack(event.receiver, event.streams);
2162 }
Steve Antondcc3c022017-12-22 16:02:54 -08002163 }
2164
Henrik Boströmfdb92012017-11-09 19:55:44 +01002165 const cricket::ContentInfo* audio_content =
2166 GetFirstAudioContent(remote_description()->description());
2167 const cricket::ContentInfo* video_content =
2168 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002169 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002170 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002171 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002172 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002173 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002174 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002175
2176 // Check if the descriptions include streams, just in case the peer supports
2177 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002178 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002179 (audio_desc && !audio_desc->streams().empty()) ||
2180 (video_desc && !video_desc->streams().empty())) {
2181 remote_peer_supports_msid_ = true;
2182 }
deadbeefab9b2d12015-10-14 11:33:11 -07002183
2184 // We wait to signal new streams until we finish processing the description,
2185 // since only at that point will new streams have all their tracks.
2186 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2187
Steve Antondcc3c022017-12-22 16:02:54 -08002188 if (!IsUnifiedPlan()) {
2189 // TODO(steveanton): When removing RTP senders/receivers in response to a
2190 // rejected media section, there is some cleanup logic that expects the
2191 // voice/ video channel to still be set. But in this method the voice/video
2192 // channel would have been destroyed by the SetRemoteDescription caller
2193 // above so the cleanup that relies on them fails to run. The RemoveSenders
2194 // calls should be moved to right before the DestroyChannel calls to fix
2195 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002196
Steve Antondcc3c022017-12-22 16:02:54 -08002197 // Find all audio rtp streams and create corresponding remote AudioTracks
2198 // and MediaStreams.
2199 if (audio_content) {
2200 if (audio_content->rejected) {
2201 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2202 } else {
2203 bool default_audio_track_needed =
2204 !remote_peer_supports_msid_ &&
2205 RtpTransceiverDirectionHasSend(audio_desc->direction());
2206 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2207 default_audio_track_needed, audio_desc->type(),
2208 new_streams);
2209 }
deadbeeffaac4972015-11-12 15:33:07 -08002210 }
deadbeefab9b2d12015-10-14 11:33:11 -07002211
Steve Antondcc3c022017-12-22 16:02:54 -08002212 // Find all video rtp streams and create corresponding remote VideoTracks
2213 // and MediaStreams.
2214 if (video_content) {
2215 if (video_content->rejected) {
2216 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2217 } else {
2218 bool default_video_track_needed =
2219 !remote_peer_supports_msid_ &&
2220 RtpTransceiverDirectionHasSend(video_desc->direction());
2221 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2222 default_video_track_needed, video_desc->type(),
2223 new_streams);
2224 }
deadbeeffaac4972015-11-12 15:33:07 -08002225 }
deadbeefab9b2d12015-10-14 11:33:11 -07002226
Steve Antondcc3c022017-12-22 16:02:54 -08002227 // Update the DataChannels with the information from the remote peer.
2228 if (data_desc) {
2229 if (rtc::starts_with(data_desc->protocol().data(),
2230 cricket::kMediaProtocolRtpPrefix)) {
2231 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2232 }
deadbeefab9b2d12015-10-14 11:33:11 -07002233 }
deadbeefab9b2d12015-10-14 11:33:11 -07002234
Steve Antondcc3c022017-12-22 16:02:54 -08002235 // Iterate new_streams and notify the observer about new MediaStreams.
2236 for (size_t i = 0; i < new_streams->count(); ++i) {
2237 MediaStreamInterface* new_stream = new_streams->at(i);
2238 stats_->AddStream(new_stream);
2239 observer_->OnAddStream(
2240 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2241 }
deadbeefab9b2d12015-10-14 11:33:11 -07002242
Steve Antondcc3c022017-12-22 16:02:54 -08002243 UpdateEndedRemoteMediaStreams();
2244 }
deadbeefab9b2d12015-10-14 11:33:11 -07002245
Steve Anton8a006912017-12-04 15:25:56 -08002246 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002247}
2248
Steve Antondcc3c022017-12-22 16:02:54 -08002249RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2250 cricket::ContentSource source,
2251 const SessionDescriptionInterface* old_session,
2252 const SessionDescriptionInterface& new_session) {
2253 RTC_DCHECK(IsUnifiedPlan());
2254
Steve Anton7464fca2018-01-19 11:10:37 -08002255 const cricket::ContentGroup* bundle_group = nullptr;
2256 if (new_session.GetType() == SdpType::kOffer) {
2257 auto bundle_group_or_error =
2258 GetEarlyBundleGroup(*new_session.description());
2259 if (!bundle_group_or_error.ok()) {
2260 return bundle_group_or_error.MoveError();
2261 }
2262 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002263 }
Steve Antondcc3c022017-12-22 16:02:54 -08002264
2265 const ContentInfos& old_contents =
2266 (old_session ? old_session->description()->contents() : ContentInfos());
2267 const ContentInfos& new_contents = new_session.description()->contents();
2268
2269 for (size_t i = 0; i < new_contents.size(); ++i) {
2270 const cricket::ContentInfo& new_content = new_contents[i];
2271 const cricket::ContentInfo* old_content =
2272 (i < old_contents.size() ? &old_contents[i] : nullptr);
2273 cricket::MediaType media_type = new_content.media_description()->type();
2274 seen_mids_.insert(new_content.name);
2275 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2276 media_type == cricket::MEDIA_TYPE_VIDEO) {
2277 auto transceiver_or_error =
2278 AssociateTransceiver(source, i, new_content, old_content);
2279 if (!transceiver_or_error.ok()) {
2280 return transceiver_or_error.MoveError();
2281 }
2282 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002283 RTCError error =
2284 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2285 if (!error.ok()) {
2286 return error;
2287 }
2288 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002289 if (GetDataMid() && new_content.name != *GetDataMid()) {
2290 // Ignore all but the first data section.
2291 continue;
2292 }
2293 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2294 if (!error.ok()) {
2295 return error;
2296 }
Steve Antondcc3c022017-12-22 16:02:54 -08002297 } else {
2298 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2299 "Unknown section type.");
2300 }
2301 }
2302
2303 return RTCError::OK();
2304}
2305
2306RTCError PeerConnection::UpdateTransceiverChannel(
2307 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2308 transceiver,
2309 const cricket::ContentInfo& content,
2310 const cricket::ContentGroup* bundle_group) {
2311 RTC_DCHECK(IsUnifiedPlan());
2312 RTC_DCHECK(transceiver);
2313 cricket::BaseChannel* channel = transceiver->internal()->channel();
2314 if (content.rejected) {
2315 if (channel) {
2316 transceiver->internal()->SetChannel(nullptr);
2317 DestroyBaseChannel(channel);
2318 }
2319 } else {
2320 if (!channel) {
2321 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2322 channel = CreateVoiceChannel(
2323 content.name,
2324 GetTransportNameForMediaSection(content.name, bundle_group));
2325 } else {
2326 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2327 transceiver->internal()->media_type());
2328 channel = CreateVideoChannel(
2329 content.name,
2330 GetTransportNameForMediaSection(content.name, bundle_group));
2331 }
2332 if (!channel) {
2333 LOG_AND_RETURN_ERROR(
2334 RTCErrorType::INTERNAL_ERROR,
2335 "Failed to create channel for mid=" + content.name);
2336 }
2337 transceiver->internal()->SetChannel(channel);
2338 }
2339 }
2340 return RTCError::OK();
2341}
2342
Steve Antonfa2260d2017-12-28 16:38:23 -08002343RTCError PeerConnection::UpdateDataChannel(
2344 cricket::ContentSource source,
2345 const cricket::ContentInfo& content,
2346 const cricket::ContentGroup* bundle_group) {
2347 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002348 // If data channels are disabled, ignore this media section. CreateAnswer
2349 // will take care of rejecting it.
2350 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002351 }
2352 if (content.rejected) {
2353 DestroyDataChannel();
2354 } else {
2355 if (!rtp_data_channel_ && !sctp_transport_) {
2356 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2357 content.name, bundle_group))) {
2358 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2359 "Failed to create data channel.");
2360 }
2361 }
2362 if (source == cricket::CS_REMOTE) {
2363 const MediaContentDescription* data_desc = content.media_description();
2364 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2365 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2366 }
2367 }
2368 }
2369 return RTCError::OK();
2370}
2371
Steve Antondcc3c022017-12-22 16:02:54 -08002372RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2373PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2374 size_t mline_index,
2375 const ContentInfo& content,
2376 const ContentInfo* old_content) {
2377 RTC_DCHECK(IsUnifiedPlan());
2378 // If the m= section is being recycled (rejected in previous remote
2379 // description, not rejected in current description), dissociate the currently
2380 // associated RtpTransceiver by setting its mid property to null, and discard
2381 // the mapping between the transceiver and its m= section index.
2382 if (old_content && old_content->rejected && !content.rejected) {
2383 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2384 if (old_transceiver) {
2385 old_transceiver->internal()->set_mid(rtc::nullopt);
2386 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2387 }
2388 }
2389 const MediaContentDescription* media_desc = content.media_description();
2390 auto transceiver = GetAssociatedTransceiver(content.name);
2391 if (source == cricket::CS_LOCAL) {
2392 // Find the RtpTransceiver that corresponds to this m= section, using the
2393 // mapping between transceivers and m= section indices established when
2394 // creating the offer.
2395 if (!transceiver) {
2396 transceiver = GetTransceiverByMLineIndex(mline_index);
2397 }
2398 if (!transceiver) {
2399 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2400 "Unknown transceiver");
2401 }
2402 } else {
2403 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2404 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2405 // of the same type...
2406 if (!transceiver &&
2407 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2408 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2409 }
2410 // If no RtpTransceiver was found in the previous step, create one with a
2411 // recvonly direction.
2412 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002413 auto sender =
2414 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002415 std::string receiver_id;
2416 if (!media_desc->streams().empty()) {
2417 receiver_id = media_desc->streams()[0].id;
2418 } else {
2419 receiver_id = rtc::CreateRandomUuid();
2420 }
2421 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002422 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002423 transceiver->internal()->set_direction(
2424 RtpTransceiverDirection::kRecvOnly);
2425 }
2426 }
2427 RTC_DCHECK(transceiver);
2428 if (transceiver->internal()->media_type() != media_desc->type()) {
2429 LOG_AND_RETURN_ERROR(
2430 RTCErrorType::INVALID_PARAMETER,
2431 "Transceiver type does not match media description type.");
2432 }
2433 // Associate the found or created RtpTransceiver with the m= section by
2434 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2435 // section, and establish a mapping between the transceiver and the index of
2436 // the m= section.
2437 transceiver->internal()->set_mid(content.name);
2438 transceiver->internal()->set_mline_index(mline_index);
2439 return std::move(transceiver);
2440}
2441
2442rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2443PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2444 RTC_DCHECK(IsUnifiedPlan());
2445 for (auto transceiver : transceivers_) {
2446 if (transceiver->mid() == mid) {
2447 return transceiver;
2448 }
2449 }
2450 return nullptr;
2451}
2452
2453rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2454PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2455 RTC_DCHECK(IsUnifiedPlan());
2456 for (auto transceiver : transceivers_) {
2457 if (transceiver->internal()->mline_index() == mline_index) {
2458 return transceiver;
2459 }
2460 }
2461 return nullptr;
2462}
2463
2464rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2465PeerConnection::FindAvailableTransceiverToReceive(
2466 cricket::MediaType media_type) const {
2467 RTC_DCHECK(IsUnifiedPlan());
2468 // From JSEP section 5.10 (Applying a Remote Description):
2469 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2470 // the same type that were added to the PeerConnection by addTrack and are not
2471 // associated with any m= section and are not stopped, find the first such
2472 // RtpTransceiver.
2473 for (auto transceiver : transceivers_) {
2474 if (transceiver->internal()->media_type() == media_type &&
2475 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2476 !transceiver->stopped()) {
2477 return transceiver;
2478 }
2479 }
2480 return nullptr;
2481}
2482
Steve Antoned10bd92017-12-05 10:52:59 -08002483const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2484 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2485 transceiver,
2486 const SessionDescriptionInterface* sdesc) const {
2487 RTC_DCHECK(transceiver);
2488 RTC_DCHECK(sdesc);
2489 if (IsUnifiedPlan()) {
2490 if (!transceiver->internal()->mid()) {
2491 // This transceiver is not associated with a media section yet.
2492 return nullptr;
2493 }
2494 return sdesc->description()->GetContentByName(
2495 *transceiver->internal()->mid());
2496 } else {
2497 // Plan B only allows at most one audio and one video section, so use the
2498 // first media section of that type.
2499 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2500 transceiver->internal()->media_type());
2501 }
2502}
2503
deadbeef46c73892016-11-16 19:42:04 -08002504PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2505 return configuration_;
2506}
2507
deadbeef293e9262017-01-11 12:28:30 -08002508bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2509 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002510 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002511
Steve Anton75737c02017-11-06 10:37:17 -08002512 if (local_description() && configuration.ice_candidate_pool_size !=
2513 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002514 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2515 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002516 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002517 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002518
deadbeef293e9262017-01-11 12:28:30 -08002519 // The simplest (and most future-compatible) way to tell if the config was
2520 // modified in an invalid way is to copy each property we do support
2521 // modifying, then use operator==. There are far more properties we don't
2522 // support modifying than those we do, and more could be added.
2523 RTCConfiguration modified_config = configuration_;
2524 modified_config.servers = configuration.servers;
2525 modified_config.type = configuration.type;
2526 modified_config.ice_candidate_pool_size =
2527 configuration.ice_candidate_pool_size;
2528 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002529 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002530 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002531 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002532 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002533 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002534 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2535 }
2536
Steve Anton038834f2017-07-14 15:59:59 -07002537 // Validate the modified configuration.
2538 RTCError validate_error = ValidateConfiguration(modified_config);
2539 if (!validate_error.ok()) {
2540 return SafeSetError(std::move(validate_error), error);
2541 }
2542
deadbeef293e9262017-01-11 12:28:30 -08002543 // Note that this isn't possible through chromium, since it's an unsigned
2544 // short in WebIDL.
2545 if (configuration.ice_candidate_pool_size < 0 ||
2546 configuration.ice_candidate_pool_size > UINT16_MAX) {
2547 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2548 }
2549
2550 // Parse ICE servers before hopping to network thread.
2551 cricket::ServerAddresses stun_servers;
2552 std::vector<cricket::RelayServerConfig> turn_servers;
2553 RTCErrorType parse_error =
2554 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2555 if (parse_error != RTCErrorType::NONE) {
2556 return SafeSetError(parse_error, error);
2557 }
2558
2559 // In theory this shouldn't fail.
2560 if (!network_thread()->Invoke<bool>(
2561 RTC_FROM_HERE,
2562 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2563 stun_servers, turn_servers, modified_config.type,
2564 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002565 modified_config.prune_turn_ports,
2566 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002567 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002568 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2569 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002570
deadbeefd1a38b52016-12-10 13:15:33 -08002571 // As described in JSEP, calling setConfiguration with new ICE servers or
2572 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2573 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002574 if (modified_config.servers != configuration_.servers ||
2575 modified_config.type != configuration_.type ||
2576 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002577 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002578 }
skvladd1f5fda2017-02-03 16:54:05 -08002579
2580 if (modified_config.ice_check_min_interval !=
2581 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002582 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002583 }
2584
deadbeef293e9262017-01-11 12:28:30 -08002585 configuration_ = modified_config;
2586 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002587}
2588
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002589bool PeerConnection::AddIceCandidate(
2590 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002591 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002592 if (IsClosed()) {
2593 return false;
2594 }
Steve Antond25da372017-11-06 14:50:29 -08002595
2596 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002597 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2598 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002599 return false;
2600 }
2601
2602 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002603 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002604 return false;
2605 }
2606
2607 bool valid = false;
2608 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2609 if (!valid) {
2610 return false;
2611 }
2612
2613 // Add this candidate to the remote session description.
2614 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002615 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002616 return false;
2617 }
2618
2619 if (ready) {
2620 return UseCandidate(ice_candidate);
2621 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002622 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002623 return true;
2624 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002625}
2626
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002627bool PeerConnection::RemoveIceCandidates(
2628 const std::vector<cricket::Candidate>& candidates) {
2629 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002630 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002631 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2632 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002633 return false;
2634 }
2635
2636 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002637 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002638 return false;
2639 }
2640
2641 size_t number_removed =
2642 mutable_remote_description()->RemoveCandidates(candidates);
2643 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002644 RTC_LOG(LS_ERROR)
2645 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2646 << "Requested " << candidates.size() << " but only " << number_removed
2647 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002648 }
2649
2650 // Remove the candidates from the transport controller.
2651 std::string error;
2652 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2653 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002654 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002655 }
2656 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002657}
2658
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002659void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002660 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002661 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002662
Steve Anton75737c02017-11-06 10:37:17 -08002663 if (transport_controller()) {
2664 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002665 }
2666
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002667 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002668 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002669 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002670 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002671 uma_observer_->IncrementEnumCounter(
2672 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2673 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002674 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002675 uma_observer_->IncrementEnumCounter(
2676 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2677 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002678 }
2679 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002680}
2681
zstein4b979802017-06-02 14:37:37 -07002682RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002683 if (!worker_thread()->IsCurrent()) {
2684 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002685 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2686 }
2687
2688 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2689 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2690 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2691 if (has_min && *bitrate.min_bitrate_bps < 0) {
2692 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2693 "min_bitrate_bps <= 0");
2694 }
2695 if (has_current) {
2696 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2698 "current_bitrate_bps < min_bitrate_bps");
2699 } else if (*bitrate.current_bitrate_bps < 0) {
2700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2701 "curent_bitrate_bps < 0");
2702 }
2703 }
2704 if (has_max) {
2705 if (has_current &&
2706 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2708 "max_bitrate_bps < current_bitrate_bps");
2709 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2711 "max_bitrate_bps < min_bitrate_bps");
2712 } else if (*bitrate.max_bitrate_bps < 0) {
2713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2714 "max_bitrate_bps < 0");
2715 }
2716 }
2717
2718 Call::Config::BitrateConfigMask mask;
2719 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2720 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2721 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2722
2723 RTC_DCHECK(call_.get());
2724 call_->SetBitrateConfigMask(mask);
2725
2726 return RTCError::OK();
2727}
2728
Alex Narest78609d52017-10-20 10:37:47 +02002729void PeerConnection::SetBitrateAllocationStrategy(
2730 std::unique_ptr<rtc::BitrateAllocationStrategy>
2731 bitrate_allocation_strategy) {
2732 rtc::Thread* worker_thread = factory_->worker_thread();
2733 if (!worker_thread->IsCurrent()) {
2734 rtc::BitrateAllocationStrategy* strategy_raw =
2735 bitrate_allocation_strategy.release();
2736 auto functor = [this, strategy_raw]() {
2737 call_->SetBitrateAllocationStrategy(
2738 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2739 };
2740 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2741 return;
2742 }
2743 RTC_DCHECK(call_.get());
2744 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2745}
2746
henrika5f6bf242017-11-01 11:06:56 +01002747void PeerConnection::SetAudioPlayout(bool playout) {
2748 if (!worker_thread()->IsCurrent()) {
2749 worker_thread()->Invoke<void>(
2750 RTC_FROM_HERE,
2751 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2752 return;
2753 }
2754 auto audio_state =
2755 factory_->channel_manager()->media_engine()->GetAudioState();
2756 audio_state->SetPlayout(playout);
2757}
2758
2759void PeerConnection::SetAudioRecording(bool recording) {
2760 if (!worker_thread()->IsCurrent()) {
2761 worker_thread()->Invoke<void>(
2762 RTC_FROM_HERE,
2763 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2764 return;
2765 }
2766 auto audio_state =
2767 factory_->channel_manager()->media_engine()->GetAudioState();
2768 audio_state->SetRecording(recording);
2769}
2770
Steve Anton8c0f7a72017-10-03 10:03:10 -07002771std::unique_ptr<rtc::SSLCertificate>
2772PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002773 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002774 return nullptr;
2775 }
Steve Anton75737c02017-11-06 10:37:17 -08002776 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002777}
2778
Zhi Huang70b820f2018-01-27 14:16:15 -08002779std::unique_ptr<rtc::SSLCertChain>
2780PeerConnection::GetRemoteAudioSSLCertChain() {
2781 if (!voice_channel()) {
2782 return nullptr;
2783 }
2784
2785 return transport_controller_->GetRemoteSSLCertChain(
2786 voice_channel()->transport_name());
2787}
2788
ivoc14d5dbe2016-07-04 07:06:55 -07002789bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2790 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002791 // TODO(eladalon): It would be better to not allow negative values into PC.
2792 const size_t max_size = (max_size_bytes < 0)
2793 ? RtcEventLog::kUnlimitedOutput
2794 : rtc::saturated_cast<size_t>(max_size_bytes);
2795 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002796 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2797 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002798}
2799
Bjorn Tereliusde939432017-11-20 17:38:14 +01002800bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2801 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002802 // TODO(eladalon): In C++14, this can be done with a lambda.
2803 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002804 bool operator()() {
2805 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2806 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002807 PeerConnection* const pc;
2808 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002809 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002810 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002811 return worker_thread()->Invoke<bool>(
2812 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002813}
2814
2815void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002816 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002817 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2818}
2819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002821 return pending_local_description_ ? pending_local_description_.get()
2822 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002823}
2824
2825const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002826 return pending_remote_description_ ? pending_remote_description_.get()
2827 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002828}
2829
deadbeeffe4a8a42016-12-20 17:56:17 -08002830const SessionDescriptionInterface* PeerConnection::current_local_description()
2831 const {
Steve Anton75737c02017-11-06 10:37:17 -08002832 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002833}
2834
2835const SessionDescriptionInterface* PeerConnection::current_remote_description()
2836 const {
Steve Anton75737c02017-11-06 10:37:17 -08002837 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002838}
2839
2840const SessionDescriptionInterface* PeerConnection::pending_local_description()
2841 const {
Steve Anton75737c02017-11-06 10:37:17 -08002842 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002843}
2844
2845const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2846 const {
Steve Anton75737c02017-11-06 10:37:17 -08002847 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002848}
2849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002851 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 // Update stats here so that we have the most recent stats for tracks and
2853 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002854 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855
Steve Anton75737c02017-11-06 10:37:17 -08002856 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002857
Steve Anton8af21862017-12-15 11:20:13 -08002858 for (auto transceiver : transceivers_) {
2859 transceiver->Stop();
2860 }
2861 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002862
Qingsi Wang93a84392018-01-30 17:13:09 -08002863 // The event log is used in the transport controller, which must be outlived
2864 // by the former. CreateOffer by the peer connection is implemented
2865 // asynchronously and if the peer connection is closed without resetting the
2866 // WebRTC session description factory, the session description factory would
2867 // call the transport controller.
2868 webrtc_session_desc_factory_.reset();
2869 transport_controller_.reset();
2870
deadbeef42a42632017-03-10 15:18:00 -08002871 network_thread()->Invoke<void>(
2872 RTC_FROM_HERE,
2873 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2874 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002875
Steve Anton978b8762017-09-29 12:15:02 -07002876 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002877 call_.reset();
2878 // The event log must outlive call (and any other object that uses it).
2879 event_log_.reset();
2880 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002881}
2882
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002883void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002884 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002885 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2886 SetSessionDescriptionMsg* param =
2887 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2888 param->observer->OnSuccess();
2889 delete param;
2890 break;
2891 }
2892 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2893 SetSessionDescriptionMsg* param =
2894 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2895 param->observer->OnFailure(param->error);
2896 delete param;
2897 break;
2898 }
deadbeefab9b2d12015-10-14 11:33:11 -07002899 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2900 CreateSessionDescriptionMsg* param =
2901 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2902 param->observer->OnFailure(param->error);
2903 delete param;
2904 break;
2905 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002906 case MSG_GETSTATS: {
2907 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002908 StatsReports reports;
2909 stats_->GetStats(param->track, &reports);
2910 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002911 delete param;
2912 break;
2913 }
deadbeefbd292462015-12-14 18:15:29 -08002914 case MSG_FREE_DATACHANNELS: {
2915 sctp_data_channels_to_free_.clear();
2916 break;
2917 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002918 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002919 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002920 break;
2921 }
2922}
2923
Steve Anton4171afb2017-11-20 10:20:22 -08002924void PeerConnection::CreateAudioReceiver(
2925 MediaStreamInterface* stream,
2926 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002927 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2928 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002929 auto* audio_receiver = new AudioRtpReceiver(
2930 worker_thread(), remote_sender_info.sender_id, streams);
2931 audio_receiver->SetMediaChannel(voice_media_channel());
2932 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2933 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2934 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002935 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002936 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002937}
2938
Steve Anton4171afb2017-11-20 10:20:22 -08002939void PeerConnection::CreateVideoReceiver(
2940 MediaStreamInterface* stream,
2941 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002942 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2943 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002944 auto* video_receiver = new VideoRtpReceiver(
2945 worker_thread(), remote_sender_info.sender_id, streams);
2946 video_receiver->SetMediaChannel(video_media_channel());
2947 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2948 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2949 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002950 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002951 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002952}
2953
deadbeef70ab1a12015-09-28 16:53:55 -07002954// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2955// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002956rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002957 const RtpSenderInfo& remote_sender_info) {
2958 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2959 if (!receiver) {
2960 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2961 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002962 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002963 }
Steve Anton4171afb2017-11-20 10:20:22 -08002964 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2965 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2966 } else {
2967 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2968 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002969 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970}
2971
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002972void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2973 MediaStreamInterface* stream) {
2974 RTC_DCHECK(!IsClosed());
2975 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002976 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002977 // We already have a sender for this track, so just change the stream_id
2978 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002979 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002980 return;
2981 }
2982
2983 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002984 auto new_sender =
2985 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2986 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002987 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002988 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002989 // If the sender has already been configured in SDP, we call SetSsrc,
2990 // which will connect the sender to the underlying transport. This can
2991 // occur if a local session description that contains the ID of the sender
2992 // is set before AddStream is called. It can also occur if the local
2993 // session description is not changed and RemoveStream is called, and
2994 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002995 const RtpSenderInfo* sender_info =
2996 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2997 if (sender_info) {
2998 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002999 }
3000}
3001
3002// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3003// indefinitely, when we have unified plan SDP.
3004void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3005 MediaStreamInterface* stream) {
3006 RTC_DCHECK(!IsClosed());
3007 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003008 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003009 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3010 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003011 return;
3012 }
Steve Anton4171afb2017-11-20 10:20:22 -08003013 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003014}
3015
3016void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3017 MediaStreamInterface* stream) {
3018 RTC_DCHECK(!IsClosed());
3019 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003020 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003021 // We already have a sender for this track, so just change the stream_id
3022 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003023 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003024 return;
3025 }
3026
3027 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003028 auto new_sender =
3029 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3030 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003031 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003032 GetVideoTransceiver()->internal()->AddSender(new_sender);
3033 const RtpSenderInfo* sender_info =
3034 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3035 if (sender_info) {
3036 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003037 }
3038}
3039
3040void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3041 MediaStreamInterface* stream) {
3042 RTC_DCHECK(!IsClosed());
3043 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003044 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003045 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3046 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003047 return;
3048 }
Steve Anton4171afb2017-11-20 10:20:22 -08003049 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003050}
3051
Steve Antonba818672017-11-06 10:21:57 -08003052void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003053 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003054 if (ice_connection_state_ == new_state) {
3055 return;
3056 }
3057
deadbeefcbecd352015-09-23 11:50:27 -07003058 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003059 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003060 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003061 return;
3062 }
Steve Antonba818672017-11-06 10:21:57 -08003063
Mirko Bonadei675513b2017-11-09 11:09:25 +01003064 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3065 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003066 RTC_DCHECK(ice_connection_state_ !=
3067 PeerConnectionInterface::kIceConnectionClosed);
3068
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003069 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003070 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003071}
3072
3073void PeerConnection::OnIceGatheringChange(
3074 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003075 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 if (IsClosed()) {
3077 return;
3078 }
3079 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003080 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081}
3082
jbauch81bf7b02017-03-25 08:31:12 -07003083void PeerConnection::OnIceCandidate(
3084 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003085 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003086 if (IsClosed()) {
3087 return;
3088 }
jbauch81bf7b02017-03-25 08:31:12 -07003089 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090}
3091
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003092void PeerConnection::OnIceCandidatesRemoved(
3093 const std::vector<cricket::Candidate>& candidates) {
3094 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003095 if (IsClosed()) {
3096 return;
3097 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003098 observer_->OnIceCandidatesRemoved(candidates);
3099}
3100
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003101void PeerConnection::ChangeSignalingState(
3102 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003103 RTC_DCHECK(signaling_thread()->IsCurrent());
3104 if (signaling_state_ == signaling_state) {
3105 return;
3106 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003107 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3108 << GetSignalingStateString(signaling_state_)
3109 << " New state: "
3110 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 signaling_state_ = signaling_state;
3112 if (signaling_state == kClosed) {
3113 ice_connection_state_ = kIceConnectionClosed;
3114 observer_->OnIceConnectionChange(ice_connection_state_);
3115 if (ice_gathering_state_ != kIceGatheringComplete) {
3116 ice_gathering_state_ = kIceGatheringComplete;
3117 observer_->OnIceGatheringChange(ice_gathering_state_);
3118 }
3119 }
3120 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003121}
3122
deadbeefeb459812015-12-15 19:24:43 -08003123void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3124 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003125 if (IsClosed()) {
3126 return;
3127 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003128 AddAudioTrack(track, stream);
3129 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003130}
3131
deadbeefeb459812015-12-15 19:24:43 -08003132void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3133 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003134 if (IsClosed()) {
3135 return;
3136 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003137 RemoveAudioTrack(track, stream);
3138 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003139}
3140
3141void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3142 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003143 if (IsClosed()) {
3144 return;
3145 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003146 AddVideoTrack(track, stream);
3147 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003148}
3149
3150void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3151 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003152 if (IsClosed()) {
3153 return;
3154 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003155 RemoveVideoTrack(track, stream);
3156 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003157}
3158
Henrik Boström31638672017-11-23 17:48:32 +01003159void PeerConnection::PostSetSessionDescriptionSuccess(
3160 SetSessionDescriptionObserver* observer) {
3161 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3162 signaling_thread()->Post(RTC_FROM_HERE, this,
3163 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3164}
3165
deadbeefab9b2d12015-10-14 11:33:11 -07003166void PeerConnection::PostSetSessionDescriptionFailure(
3167 SetSessionDescriptionObserver* observer,
3168 const std::string& error) {
3169 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3170 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003171 signaling_thread()->Post(RTC_FROM_HERE, this,
3172 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003173}
3174
3175void PeerConnection::PostCreateSessionDescriptionFailure(
3176 CreateSessionDescriptionObserver* observer,
3177 const std::string& error) {
3178 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3179 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003180 signaling_thread()->Post(RTC_FROM_HERE, this,
3181 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003182}
3183
zhihuang1c378ed2017-08-17 14:10:50 -07003184void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003185 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003186 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003187 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003188
Steve Antondcc3c022017-12-22 16:02:54 -08003189 if (IsUnifiedPlan()) {
3190 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3191 } else {
3192 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3193 }
3194
Steve Antonfa2260d2017-12-28 16:38:23 -08003195 // Intentionally unset the data channel type for RTP data channel with the
3196 // second condition. Otherwise the RTP data channels would be successfully
3197 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3198 // when building with chromium. We want to leave RTP data channels broken, so
3199 // people won't try to use them.
3200 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3201 session_options->data_channel_type = data_channel_type();
3202 }
3203
Steve Antondcc3c022017-12-22 16:02:54 -08003204 // Apply ICE restart flag and renomination flag.
3205 for (auto& options : session_options->media_description_options) {
3206 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3207 options.transport_options.enable_ice_renomination =
3208 configuration_.enable_ice_renomination;
3209 }
3210
3211 session_options->rtcp_cname = rtcp_cname_;
3212 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003213 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003214}
3215
3216void PeerConnection::GetOptionsForPlanBOffer(
3217 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3218 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003219 // Figure out transceiver directional preferences.
3220 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3221 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3222
3223 // By default, generate sendrecv/recvonly m= sections.
3224 bool recv_audio = true;
3225 bool recv_video = true;
3226
3227 // By default, only offer a new m= section if we have media to send with it.
3228 bool offer_new_audio_description = send_audio;
3229 bool offer_new_video_description = send_video;
3230 bool offer_new_data_description = HasDataChannels();
3231
3232 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003233 if (offer_answer_options.offer_to_receive_audio !=
3234 RTCOfferAnswerOptions::kUndefined) {
3235 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003236 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003237 offer_new_audio_description ||
3238 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003239 }
Steve Antondcc3c022017-12-22 16:02:54 -08003240 if (offer_answer_options.offer_to_receive_video !=
3241 RTCOfferAnswerOptions::kUndefined) {
3242 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003243 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003244 offer_new_video_description ||
3245 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003246 }
3247
3248 rtc::Optional<size_t> audio_index;
3249 rtc::Optional<size_t> video_index;
3250 rtc::Optional<size_t> data_index;
3251 // If a current description exists, generate m= sections in the same order,
3252 // using the first audio/video/data section that appears and rejecting
3253 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003254 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003255 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003256 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003257 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3258 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3259 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003260 }
3261
zhihuang1c378ed2017-08-17 14:10:50 -07003262 // Add audio/video/data m= sections to the end if needed.
3263 if (!audio_index && offer_new_audio_description) {
3264 session_options->media_description_options.push_back(
3265 cricket::MediaDescriptionOptions(
3266 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003267 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3268 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003269 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003270 }
zhihuang1c378ed2017-08-17 14:10:50 -07003271 if (!video_index && offer_new_video_description) {
3272 session_options->media_description_options.push_back(
3273 cricket::MediaDescriptionOptions(
3274 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003275 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3276 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003277 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003278 }
zhihuang1c378ed2017-08-17 14:10:50 -07003279 if (!data_index && offer_new_data_description) {
3280 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003281 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003282 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003283 }
3284
3285 cricket::MediaDescriptionOptions* audio_media_description_options =
3286 !audio_index ? nullptr
3287 : &session_options->media_description_options[*audio_index];
3288 cricket::MediaDescriptionOptions* video_media_description_options =
3289 !video_index ? nullptr
3290 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003291
Steve Anton4171afb2017-11-20 10:20:22 -08003292 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003293 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003294}
3295
3296// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3297// and return a reference to it.
3298// Generated MIDs should be no more than 3 bytes long to take up less space in
3299// the RTP packet.
3300static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3301 RTC_DCHECK(used_mids);
3302 // We're boring: just generate MIDs 0, 1, 2, ...
3303 size_t i = 0;
3304 std::set<std::string>::iterator it;
3305 bool inserted;
3306 do {
3307 std::string mid = rtc::ToString(i++);
3308 auto insert_result = used_mids->insert(mid);
3309 it = insert_result.first;
3310 inserted = insert_result.second;
3311 } while (!inserted);
3312 return *it;
3313}
3314
3315static cricket::MediaDescriptionOptions
3316GetMediaDescriptionOptionsForTransceiver(
3317 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3318 transceiver,
3319 const std::string& mid) {
3320 cricket::MediaDescriptionOptions media_description_options(
3321 transceiver->internal()->media_type(), mid, transceiver->direction(),
3322 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003323 // This behavior is specified in JSEP. The gist is that:
3324 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3325 // sendrecv.
3326 // 2. If the MSID is included, then it must be included in any subsequent
3327 // offer/answer exactly the same until the RtpTransceiver is stopped.
3328 if (!transceiver->stopped() &&
3329 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3330 transceiver->internal()->has_ever_been_used_to_send())) {
3331 cricket::SenderOptions sender_options;
3332 sender_options.track_id = transceiver->sender()->id();
3333 sender_options.stream_ids = transceiver->sender()->stream_ids();
3334 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3335 // set in the RTP parameters when the transceiver was added.
3336 sender_options.num_sim_layers = 1;
3337 media_description_options.sender_options.push_back(sender_options);
3338 }
Steve Antondcc3c022017-12-22 16:02:54 -08003339 return media_description_options;
3340}
3341
3342void PeerConnection::GetOptionsForUnifiedPlanOffer(
3343 const RTCOfferAnswerOptions& offer_answer_options,
3344 cricket::MediaSessionOptions* session_options) {
3345 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3346 // Offers) and 5.2.2 (Subsequent Offers).
3347 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3348 const ContentInfos& local_contents =
3349 (local_description() ? local_description()->description()->contents()
3350 : ContentInfos());
3351 const ContentInfos& remote_contents =
3352 (remote_description() ? remote_description()->description()->contents()
3353 : ContentInfos());
3354 // The mline indices that can be recycled. New transceivers should reuse these
3355 // slots first.
3356 std::queue<size_t> recycleable_mline_indices;
3357 // Track the MIDs used in previous offer/answer exchanges and the current
3358 // offer so that new, unique MIDs are generated.
3359 std::set<std::string> used_mids = seen_mids_;
3360 // First, go through each media section that exists in either the local or
3361 // remote description and generate a media section in this offer for the
3362 // associated transceiver. If a media section can be recycled, generate a
3363 // default, rejected media section here that can be later overwritten.
3364 for (size_t i = 0;
3365 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3366 // Either |local_content| or |remote_content| is non-null.
3367 const ContentInfo* local_content =
3368 (i < local_contents.size() ? &local_contents[i] : nullptr);
3369 const ContentInfo* remote_content =
3370 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3371 bool had_been_rejected = (local_content && local_content->rejected) ||
3372 (remote_content && remote_content->rejected);
3373 const std::string& mid =
3374 (local_content ? local_content->name : remote_content->name);
3375 cricket::MediaType media_type =
3376 (local_content ? local_content->media_description()->type()
3377 : remote_content->media_description()->type());
3378 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3379 media_type == cricket::MEDIA_TYPE_VIDEO) {
3380 auto transceiver = GetAssociatedTransceiver(mid);
3381 RTC_CHECK(transceiver);
3382 // A media section is considered eligible for recycling if it is marked as
3383 // rejected in either the local or remote description.
3384 if (had_been_rejected) {
3385 session_options->media_description_options.push_back(
3386 cricket::MediaDescriptionOptions(
3387 transceiver->internal()->media_type(), mid,
3388 RtpTransceiverDirection::kInactive,
3389 /*stopped=*/true));
3390 recycleable_mline_indices.push(i);
3391 } else {
3392 session_options->media_description_options.push_back(
3393 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3394 // CreateOffer shouldn't really cause any state changes in
3395 // PeerConnection, but we need a way to match new transceivers to new
3396 // media sections in SetLocalDescription and JSEP specifies this is done
3397 // by recording the index of the media section generated for the
3398 // transceiver in the offer.
3399 transceiver->internal()->set_mline_index(i);
3400 }
3401 } else {
3402 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003403 RTC_CHECK(GetDataMid());
3404 if (had_been_rejected || mid != *GetDataMid()) {
3405 session_options->media_description_options.push_back(
3406 GetMediaDescriptionOptionsForRejectedData(mid));
3407 } else {
3408 session_options->media_description_options.push_back(
3409 GetMediaDescriptionOptionsForActiveData(mid));
3410 }
Steve Antondcc3c022017-12-22 16:02:54 -08003411 }
3412 }
3413 // Next, look for transceivers that are newly added (that is, are not stopped
3414 // and not associated). Reuse media sections marked as recyclable first,
3415 // otherwise append to the end of the offer. New media sections should be
3416 // added in the order they were added to the PeerConnection.
3417 for (auto transceiver : transceivers_) {
3418 if (transceiver->mid() || transceiver->stopped()) {
3419 continue;
3420 }
3421 size_t mline_index;
3422 if (!recycleable_mline_indices.empty()) {
3423 mline_index = recycleable_mline_indices.front();
3424 recycleable_mline_indices.pop();
3425 session_options->media_description_options[mline_index] =
3426 GetMediaDescriptionOptionsForTransceiver(transceiver,
3427 AllocateMid(&used_mids));
3428 } else {
3429 mline_index = session_options->media_description_options.size();
3430 session_options->media_description_options.push_back(
3431 GetMediaDescriptionOptionsForTransceiver(transceiver,
3432 AllocateMid(&used_mids)));
3433 }
3434 // See comment above for why CreateOffer changes the transceiver's state.
3435 transceiver->internal()->set_mline_index(mline_index);
3436 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003437 // Lastly, add a m-section if we have local data channels and an m section
3438 // does not already exist.
3439 if (!GetDataMid() && HasDataChannels()) {
3440 session_options->media_description_options.push_back(
3441 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3442 }
Steve Antondcc3c022017-12-22 16:02:54 -08003443}
3444
3445void PeerConnection::GetOptionsForAnswer(
3446 const RTCOfferAnswerOptions& offer_answer_options,
3447 cricket::MediaSessionOptions* session_options) {
3448 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3449
3450 if (IsUnifiedPlan()) {
3451 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3452 } else {
3453 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3454 }
3455
Steve Antonfa2260d2017-12-28 16:38:23 -08003456 // Intentionally unset the data channel type for RTP data channel. Otherwise
3457 // the RTP data channels would be successfully negotiated by default and the
3458 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3459 // We want to leave RTP data channels broken, so people won't try to use them.
3460 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3461 session_options->data_channel_type = data_channel_type();
3462 }
3463
Steve Antondcc3c022017-12-22 16:02:54 -08003464 // Apply ICE renomination flag.
3465 for (auto& options : session_options->media_description_options) {
3466 options.transport_options.enable_ice_renomination =
3467 configuration_.enable_ice_renomination;
3468 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003469
3470 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003471 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003472 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003473}
3474
Steve Antondcc3c022017-12-22 16:02:54 -08003475void PeerConnection::GetOptionsForPlanBAnswer(
3476 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003477 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003478 // Figure out transceiver directional preferences.
3479 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3480 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3481
3482 // By default, generate sendrecv/recvonly m= sections. The direction is also
3483 // restricted by the direction in the offer.
3484 bool recv_audio = true;
3485 bool recv_video = true;
3486
3487 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003488 if (offer_answer_options.offer_to_receive_audio !=
3489 RTCOfferAnswerOptions::kUndefined) {
3490 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003491 }
Steve Antondcc3c022017-12-22 16:02:54 -08003492 if (offer_answer_options.offer_to_receive_video !=
3493 RTCOfferAnswerOptions::kUndefined) {
3494 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003495 }
3496
3497 rtc::Optional<size_t> audio_index;
3498 rtc::Optional<size_t> video_index;
3499 rtc::Optional<size_t> data_index;
Oleh Prypinc22d6a82018-02-02 08:42:18 +00003500 if (remote_description()) {
3501 // The pending remote description should be an offer.
3502 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3503 // Generate m= sections that match those in the offer.
3504 // Note that mediasession.cc will handle intersection our preferred
3505 // direction with the offered direction.
3506 GenerateMediaDescriptionOptions(
3507 remote_description(),
3508 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3509 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3510 &audio_index, &video_index, &data_index, session_options);
3511 }
zhihuang1c378ed2017-08-17 14:10:50 -07003512
3513 cricket::MediaDescriptionOptions* audio_media_description_options =
3514 !audio_index ? nullptr
3515 : &session_options->media_description_options[*audio_index];
3516 cricket::MediaDescriptionOptions* video_media_description_options =
3517 !video_index ? nullptr
3518 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003519
Steve Anton4171afb2017-11-20 10:20:22 -08003520 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003521 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003522}
zhihuangaf388472016-11-02 16:49:48 -07003523
Steve Antondcc3c022017-12-22 16:02:54 -08003524void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3525 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3526 cricket::MediaSessionOptions* session_options) {
3527 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3528 // Answers) and 5.3.2 (Subsequent Answers).
3529 RTC_DCHECK(remote_description());
3530 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3531 for (const ContentInfo& content :
3532 remote_description()->description()->contents()) {
3533 cricket::MediaType media_type = content.media_description()->type();
3534 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3535 media_type == cricket::MEDIA_TYPE_VIDEO) {
3536 auto transceiver = GetAssociatedTransceiver(content.name);
3537 RTC_CHECK(transceiver);
3538 session_options->media_description_options.push_back(
3539 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3540 } else {
3541 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003542 // Reject all data sections if data channels are disabled.
3543 // Reject a data section if it has already been rejected.
3544 // Reject all data sections except for the first one.
3545 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3546 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003547 session_options->media_description_options.push_back(
3548 GetMediaDescriptionOptionsForRejectedData(content.name));
3549 } else {
3550 session_options->media_description_options.push_back(
3551 GetMediaDescriptionOptionsForActiveData(content.name));
3552 }
Steve Antondcc3c022017-12-22 16:02:54 -08003553 }
3554 }
htaa2a49d92016-03-04 02:51:39 -08003555}
3556
zhihuang1c378ed2017-08-17 14:10:50 -07003557void PeerConnection::GenerateMediaDescriptionOptions(
3558 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003559 RtpTransceiverDirection audio_direction,
3560 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003561 rtc::Optional<size_t>* audio_index,
3562 rtc::Optional<size_t>* video_index,
3563 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003564 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003565 for (const cricket::ContentInfo& content :
3566 session_desc->description()->contents()) {
3567 if (IsAudioContent(&content)) {
3568 // If we already have an audio m= section, reject this extra one.
3569 if (*audio_index) {
3570 session_options->media_description_options.push_back(
3571 cricket::MediaDescriptionOptions(
3572 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003573 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003574 } else {
3575 session_options->media_description_options.push_back(
3576 cricket::MediaDescriptionOptions(
3577 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003578 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003579 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003580 }
3581 } else if (IsVideoContent(&content)) {
3582 // If we already have an video m= section, reject this extra one.
3583 if (*video_index) {
3584 session_options->media_description_options.push_back(
3585 cricket::MediaDescriptionOptions(
3586 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003587 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003588 } else {
3589 session_options->media_description_options.push_back(
3590 cricket::MediaDescriptionOptions(
3591 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003592 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003593 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003594 }
3595 } else {
3596 RTC_DCHECK(IsDataContent(&content));
3597 // If we already have an data m= section, reject this extra one.
3598 if (*data_index) {
3599 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003600 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003601 } else {
3602 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003603 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003604 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003605 }
3606 }
htaa2a49d92016-03-04 02:51:39 -08003607 }
deadbeefab9b2d12015-10-14 11:33:11 -07003608}
3609
Steve Antonfa2260d2017-12-28 16:38:23 -08003610cricket::MediaDescriptionOptions
3611PeerConnection::GetMediaDescriptionOptionsForActiveData(
3612 const std::string& mid) const {
3613 // Direction for data sections is meaningless, but legacy endpoints might
3614 // expect sendrecv.
3615 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3616 RtpTransceiverDirection::kSendRecv,
3617 /*stopped=*/false);
3618 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3619 return options;
3620}
3621
3622cricket::MediaDescriptionOptions
3623PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3624 const std::string& mid) const {
3625 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3626 RtpTransceiverDirection::kInactive,
3627 /*stopped=*/true);
3628 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3629 return options;
3630}
3631
3632rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3633 switch (data_channel_type_) {
3634 case cricket::DCT_RTP:
3635 if (!rtp_data_channel_) {
3636 return rtc::nullopt;
3637 }
3638 return rtp_data_channel_->content_name();
3639 case cricket::DCT_SCTP:
3640 return sctp_content_name_;
3641 default:
3642 return rtc::nullopt;
3643 }
3644}
3645
Steve Anton4171afb2017-11-20 10:20:22 -08003646void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3647 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3648 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003649 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003650}
3651
Steve Anton4171afb2017-11-20 10:20:22 -08003652void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003653 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003654 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003655 cricket::MediaType media_type,
3656 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003657 std::vector<RtpSenderInfo>* current_senders =
3658 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003659
Steve Anton4171afb2017-11-20 10:20:22 -08003660 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003661 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003662 for (auto sender_it = current_senders->begin();
3663 sender_it != current_senders->end();
3664 /* incremented manually */) {
3665 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003666 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003667 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3668 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003669 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003670 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3671 sender_exists) {
3672 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003673 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003674 OnRemoteSenderRemoved(info, media_type);
3675 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003676 }
3677 }
3678
Steve Anton4171afb2017-11-20 10:20:22 -08003679 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003680 for (const cricket::StreamParams& params : streams) {
3681 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003682 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003683 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003684 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003685 uint32_t ssrc = params.first_ssrc();
3686
3687 rtc::scoped_refptr<MediaStreamInterface> stream =
3688 remote_streams_->find(stream_label);
3689 if (!stream) {
3690 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003691 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3692 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003693 remote_streams_->AddStream(stream);
3694 new_streams->AddStream(stream);
3695 }
3696
Steve Anton4171afb2017-11-20 10:20:22 -08003697 const RtpSenderInfo* sender_info =
3698 FindSenderInfo(*current_senders, stream_label, sender_id);
3699 if (!sender_info) {
3700 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3701 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003702 }
3703 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003704
Steve Anton4171afb2017-11-20 10:20:22 -08003705 // Add default sender if necessary.
3706 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003707 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3708 remote_streams_->find(kDefaultStreamLabel);
3709 if (!default_stream) {
3710 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003711 default_stream = MediaStreamProxy::Create(
3712 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003713 remote_streams_->AddStream(default_stream);
3714 new_streams->AddStream(default_stream);
3715 }
Steve Anton4171afb2017-11-20 10:20:22 -08003716 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3717 ? kDefaultAudioSenderId
3718 : kDefaultVideoSenderId;
3719 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3720 *current_senders, kDefaultStreamLabel, default_sender_id);
3721 if (!default_sender_info) {
3722 current_senders->push_back(
3723 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3724 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003725 }
3726 }
deadbeefab9b2d12015-10-14 11:33:11 -07003727}
3728
Steve Anton4171afb2017-11-20 10:20:22 -08003729void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3730 cricket::MediaType media_type) {
3731 MediaStreamInterface* stream =
3732 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003733
3734 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003735 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003736 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003737 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003738 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003739 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003740 }
3741}
3742
Steve Anton4171afb2017-11-20 10:20:22 -08003743void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3744 cricket::MediaType media_type) {
3745 MediaStreamInterface* stream =
3746 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003747
Henrik Boström933d8b02017-10-10 10:05:16 -07003748 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003749 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003750 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3751 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003752 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003753 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003754 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003755 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003756 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003757 }
3758 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003759 // Stopping or destroying a VideoRtpReceiver will end the
3760 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003761 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003762 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003763 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003764 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003765 // There's no guarantee the track is still available, e.g. the track may
3766 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003767 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003768 }
3769 } else {
nisseede5da42017-01-12 05:15:36 -08003770 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003771 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003772 if (receiver) {
3773 observer_->OnRemoveTrack(receiver);
3774 }
deadbeefab9b2d12015-10-14 11:33:11 -07003775}
3776
3777void PeerConnection::UpdateEndedRemoteMediaStreams() {
3778 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3779 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3780 MediaStreamInterface* stream = remote_streams_->at(i);
3781 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3782 streams_to_remove.push_back(stream);
3783 }
3784 }
3785
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003786 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003787 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003788 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003789 }
3790}
3791
Steve Anton4171afb2017-11-20 10:20:22 -08003792void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003793 const std::vector<cricket::StreamParams>& streams,
3794 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003795 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003796
3797 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3798 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003799 for (auto sender_it = current_senders->begin();
3800 sender_it != current_senders->end();
3801 /* incremented manually */) {
3802 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003803 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003804 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3805 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003806 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003807 OnLocalSenderRemoved(info, media_type);
3808 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003809 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003810 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003811 }
3812 }
3813
Steve Anton4171afb2017-11-20 10:20:22 -08003814 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003815 for (const cricket::StreamParams& params : streams) {
3816 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003817 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003818 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003819 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003820 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003821 const RtpSenderInfo* sender_info =
3822 FindSenderInfo(*current_senders, stream_label, sender_id);
3823 if (!sender_info) {
3824 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3825 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003826 }
3827 }
3828}
3829
Steve Anton4171afb2017-11-20 10:20:22 -08003830void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3831 cricket::MediaType media_type) {
3832 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003833 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003834 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3835 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003836 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003837 return;
3838 }
3839
deadbeeffac06552015-11-25 11:26:01 -08003840 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003841 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3842 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003843 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003844 }
deadbeeffac06552015-11-25 11:26:01 -08003845
Steve Anton4171afb2017-11-20 10:20:22 -08003846 sender->internal()->set_stream_id(sender_info.stream_label);
3847 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003848}
3849
Steve Anton4171afb2017-11-20 10:20:22 -08003850void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3851 cricket::MediaType media_type) {
3852 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003853 if (!sender) {
3854 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003855 // SessionDescriptions has been renegotiated.
3856 return;
3857 }
deadbeeffac06552015-11-25 11:26:01 -08003858
3859 // A sender has been removed from the SessionDescription but it's still
3860 // associated with the PeerConnection. This only occurs if the SDP doesn't
3861 // match with the calls to CreateSender, AddStream and RemoveStream.
3862 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003863 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3864 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003865 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003866 }
deadbeeffac06552015-11-25 11:26:01 -08003867
Steve Anton4171afb2017-11-20 10:20:22 -08003868 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003869}
3870
3871void PeerConnection::UpdateLocalRtpDataChannels(
3872 const cricket::StreamParamsVec& streams) {
3873 std::vector<std::string> existing_channels;
3874
3875 // Find new and active data channels.
3876 for (const cricket::StreamParams& params : streams) {
3877 // |it->sync_label| is actually the data channel label. The reason is that
3878 // we use the same naming of data channels as we do for
3879 // MediaStreams and Tracks.
3880 // For MediaStreams, the sync_label is the MediaStream label and the
3881 // track label is the same as |streamid|.
3882 const std::string& channel_label = params.sync_label;
3883 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003884 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003885 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003886 continue;
3887 }
3888 // Set the SSRC the data channel should use for sending.
3889 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3890 existing_channels.push_back(data_channel_it->first);
3891 }
3892
3893 UpdateClosingRtpDataChannels(existing_channels, true);
3894}
3895
3896void PeerConnection::UpdateRemoteRtpDataChannels(
3897 const cricket::StreamParamsVec& streams) {
3898 std::vector<std::string> existing_channels;
3899
3900 // Find new and active data channels.
3901 for (const cricket::StreamParams& params : streams) {
3902 // The data channel label is either the mslabel or the SSRC if the mslabel
3903 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3904 std::string label = params.sync_label.empty()
3905 ? rtc::ToString(params.first_ssrc())
3906 : params.sync_label;
3907 auto data_channel_it = rtp_data_channels_.find(label);
3908 if (data_channel_it == rtp_data_channels_.end()) {
3909 // This is a new data channel.
3910 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3911 } else {
3912 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3913 }
3914 existing_channels.push_back(label);
3915 }
3916
3917 UpdateClosingRtpDataChannels(existing_channels, false);
3918}
3919
3920void PeerConnection::UpdateClosingRtpDataChannels(
3921 const std::vector<std::string>& active_channels,
3922 bool is_local_update) {
3923 auto it = rtp_data_channels_.begin();
3924 while (it != rtp_data_channels_.end()) {
3925 DataChannel* data_channel = it->second;
3926 if (std::find(active_channels.begin(), active_channels.end(),
3927 data_channel->label()) != active_channels.end()) {
3928 ++it;
3929 continue;
3930 }
3931
3932 if (is_local_update) {
3933 data_channel->SetSendSsrc(0);
3934 } else {
3935 data_channel->RemotePeerRequestClose();
3936 }
3937
3938 if (data_channel->state() == DataChannel::kClosed) {
3939 rtp_data_channels_.erase(it);
3940 it = rtp_data_channels_.begin();
3941 } else {
3942 ++it;
3943 }
3944 }
3945}
3946
3947void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3948 uint32_t remote_ssrc) {
3949 rtc::scoped_refptr<DataChannel> channel(
3950 InternalCreateDataChannel(label, nullptr));
3951 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003952 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3953 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003954 return;
3955 }
3956 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003957 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3958 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003959 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003960}
3961
3962rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3963 const std::string& label,
3964 const InternalDataChannelInit* config) {
3965 if (IsClosed()) {
3966 return nullptr;
3967 }
Steve Anton75737c02017-11-06 10:37:17 -08003968 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003969 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003970 << "InternalCreateDataChannel: Data is not supported in this call.";
3971 return nullptr;
3972 }
3973 InternalDataChannelInit new_config =
3974 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003975 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003976 if (new_config.id < 0) {
3977 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003978 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003979 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003980 RTC_LOG(LS_ERROR)
3981 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003982 return nullptr;
3983 }
3984 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003985 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3986 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003987 return nullptr;
3988 }
3989 }
3990
Steve Anton75737c02017-11-06 10:37:17 -08003991 rtc::scoped_refptr<DataChannel> channel(
3992 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003993 if (!channel) {
3994 sid_allocator_.ReleaseSid(new_config.id);
3995 return nullptr;
3996 }
3997
3998 if (channel->data_channel_type() == cricket::DCT_RTP) {
3999 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004000 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4001 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004002 return nullptr;
4003 }
4004 rtp_data_channels_[channel->label()] = channel;
4005 } else {
4006 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4007 sctp_data_channels_.push_back(channel);
4008 channel->SignalClosed.connect(this,
4009 &PeerConnection::OnSctpDataChannelClosed);
4010 }
4011
Steve Anton2d8609c2018-01-23 16:38:46 -08004012 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004013 return channel;
4014}
4015
4016bool PeerConnection::HasDataChannels() const {
4017 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4018}
4019
4020void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4021 for (const auto& channel : sctp_data_channels_) {
4022 if (channel->id() < 0) {
4023 int sid;
4024 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004025 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004026 continue;
4027 }
4028 channel->SetSctpSid(sid);
4029 }
4030 }
4031}
4032
4033void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004034 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004035 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4036 ++it) {
4037 if (it->get() == channel) {
4038 if (channel->id() >= 0) {
4039 sid_allocator_.ReleaseSid(channel->id());
4040 }
deadbeefbd292462015-12-14 18:15:29 -08004041 // Since this method is triggered by a signal from the DataChannel,
4042 // we can't free it directly here; we need to free it asynchronously.
4043 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004044 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004045 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4046 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004047 return;
4048 }
4049 }
4050}
4051
deadbeefab9b2d12015-10-14 11:33:11 -07004052void PeerConnection::OnDataChannelDestroyed() {
4053 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4054 // DataChannel may callback to us and try to modify the list.
4055 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4056 temp_rtp_dcs.swap(rtp_data_channels_);
4057 for (const auto& kv : temp_rtp_dcs) {
4058 kv.second->OnTransportChannelDestroyed();
4059 }
4060
4061 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4062 temp_sctp_dcs.swap(sctp_data_channels_);
4063 for (const auto& channel : temp_sctp_dcs) {
4064 channel->OnTransportChannelDestroyed();
4065 }
4066}
4067
4068void PeerConnection::OnDataChannelOpenMessage(
4069 const std::string& label,
4070 const InternalDataChannelInit& config) {
4071 rtc::scoped_refptr<DataChannel> channel(
4072 InternalCreateDataChannel(label, &config));
4073 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004074 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004075 return;
4076 }
4077
deadbeefa601f5c2016-06-06 14:27:39 -07004078 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4079 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004080 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004081}
4082
Steve Anton4171afb2017-11-20 10:20:22 -08004083rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4084PeerConnection::GetAudioTransceiver() const {
4085 // This method only works with Plan B SDP, where there is a single
4086 // audio/video transceiver.
4087 RTC_DCHECK(!IsUnifiedPlan());
4088 for (auto transceiver : transceivers_) {
4089 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4090 return transceiver;
4091 }
4092 }
4093 RTC_NOTREACHED();
4094 return nullptr;
4095}
4096
4097rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4098PeerConnection::GetVideoTransceiver() const {
4099 // This method only works with Plan B SDP, where there is a single
4100 // audio/video transceiver.
4101 RTC_DCHECK(!IsUnifiedPlan());
4102 for (auto transceiver : transceivers_) {
4103 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4104 return transceiver;
4105 }
4106 }
4107 RTC_NOTREACHED();
4108 return nullptr;
4109}
4110
4111// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4112// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004113bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004114 switch (type) {
4115 case cricket::MEDIA_TYPE_AUDIO:
4116 return !GetAudioTransceiver()->internal()->senders().empty();
4117 case cricket::MEDIA_TYPE_VIDEO:
4118 return !GetVideoTransceiver()->internal()->senders().empty();
4119 case cricket::MEDIA_TYPE_DATA:
4120 return false;
4121 }
4122 RTC_NOTREACHED();
4123 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004124}
4125
Steve Anton4171afb2017-11-20 10:20:22 -08004126rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4127PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4128 for (auto transceiver : transceivers_) {
4129 for (auto sender : transceiver->internal()->senders()) {
4130 if (sender->track() == track) {
4131 return sender;
4132 }
4133 }
4134 }
4135 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004136}
4137
Steve Anton4171afb2017-11-20 10:20:22 -08004138rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4139PeerConnection::FindSenderById(const std::string& sender_id) const {
4140 for (auto transceiver : transceivers_) {
4141 for (auto sender : transceiver->internal()->senders()) {
4142 if (sender->id() == sender_id) {
4143 return sender;
4144 }
4145 }
4146 }
4147 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004148}
4149
Steve Anton4171afb2017-11-20 10:20:22 -08004150rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4151PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4152 for (auto transceiver : transceivers_) {
4153 for (auto receiver : transceiver->internal()->receivers()) {
4154 if (receiver->id() == receiver_id) {
4155 return receiver;
4156 }
4157 }
4158 }
4159 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004160}
4161
Steve Anton4171afb2017-11-20 10:20:22 -08004162std::vector<PeerConnection::RtpSenderInfo>*
4163PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4164 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4165 media_type == cricket::MEDIA_TYPE_VIDEO);
4166 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4167 ? &remote_audio_sender_infos_
4168 : &remote_video_sender_infos_;
4169}
4170
4171std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004172 cricket::MediaType media_type) {
4173 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4174 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004175 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4176 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004177}
4178
Steve Anton4171afb2017-11-20 10:20:22 -08004179const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4180 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004181 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004182 const std::string sender_id) const {
4183 for (const RtpSenderInfo& sender_info : infos) {
4184 if (sender_info.stream_label == stream_label &&
4185 sender_info.sender_id == sender_id) {
4186 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004187 }
4188 }
4189 return nullptr;
4190}
4191
4192DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4193 for (const auto& channel : sctp_data_channels_) {
4194 if (channel->id() == sid) {
4195 return channel;
4196 }
4197 }
4198 return nullptr;
4199}
4200
deadbeef91dd5672016-05-18 16:55:30 -07004201bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004202 const RTCConfiguration& configuration) {
4203 cricket::ServerAddresses stun_servers;
4204 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004205 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4206 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004207 return false;
4208 }
4209
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004210 port_allocator_->Initialize();
4211
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004212 // To handle both internal and externally created port allocator, we will
4213 // enable BUNDLE here.
4214 int portallocator_flags = port_allocator_->flags();
4215 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004216 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4217 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004218 // If the disable-IPv6 flag was specified, we'll not override it
4219 // by experiment.
4220 if (configuration.disable_ipv6) {
4221 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004222 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4223 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004224 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4225 }
4226
zhihuangb09b3f92017-03-07 14:40:51 -08004227 if (configuration.disable_ipv6_on_wifi) {
4228 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004229 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004230 }
4231
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004232 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4233 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004234 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004235 }
4236
honghaiz60347052016-05-31 18:29:12 -07004237 if (configuration.candidate_network_policy ==
4238 kCandidateNetworkPolicyLowCost) {
4239 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004240 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004241 }
4242
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004243 port_allocator_->set_flags(portallocator_flags);
4244 // No step delay is used while allocating ports.
4245 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4246 port_allocator_->set_candidate_filter(
4247 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004248 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004249
4250 // Call this last since it may create pooled allocator sessions using the
4251 // properties set above.
4252 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004253 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004254 configuration.prune_turn_ports,
4255 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004256 return true;
4257}
4258
deadbeef91dd5672016-05-18 16:55:30 -07004259bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004260 const cricket::ServerAddresses& stun_servers,
4261 const std::vector<cricket::RelayServerConfig>& turn_servers,
4262 IceTransportsType type,
4263 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004264 bool prune_turn_ports,
4265 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004266 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004267 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004268 // Call this last since it may create pooled allocator sessions using the
4269 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004270 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004271 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4272 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004273}
4274
Steve Antonba818672017-11-06 10:21:57 -08004275cricket::ChannelManager* PeerConnection::channel_manager() const {
4276 return factory_->channel_manager();
4277}
4278
4279MetricsObserverInterface* PeerConnection::metrics_observer() const {
4280 return uma_observer_;
4281}
4282
Elad Alon99c3fe52017-10-13 16:29:40 +02004283bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004284 std::unique_ptr<RtcEventLogOutput> output,
4285 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004286 if (!event_log_) {
4287 return false;
4288 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004289 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004290}
4291
4292void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004293 if (event_log_) {
4294 event_log_->StopLogging();
4295 }
ivoc14d5dbe2016-07-04 07:06:55 -07004296}
nisseeaabdf62017-05-05 02:23:02 -07004297
Steve Anton75737c02017-11-06 10:37:17 -08004298cricket::BaseChannel* PeerConnection::GetChannel(
4299 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004300 for (auto transceiver : transceivers_) {
4301 cricket::BaseChannel* channel = transceiver->internal()->channel();
4302 if (channel && channel->content_name() == content_name) {
4303 return channel;
4304 }
Steve Anton75737c02017-11-06 10:37:17 -08004305 }
4306 if (rtp_data_channel() &&
4307 rtp_data_channel()->content_name() == content_name) {
4308 return rtp_data_channel();
4309 }
4310 return nullptr;
4311}
4312
4313bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4314 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_INFO)
4316 << "Local and Remote descriptions must be applied to get the "
4317 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004318 return false;
4319 }
4320 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004321 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4322 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004323 return false;
4324 }
4325
4326 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4327}
4328
4329bool PeerConnection::GetSslRole(const std::string& content_name,
4330 rtc::SSLRole* role) {
4331 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004332 RTC_LOG(LS_INFO)
4333 << "Local and Remote descriptions must be applied to get the "
4334 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004335 return false;
4336 }
4337
4338 return transport_controller_->GetSslRole(GetTransportName(content_name),
4339 role);
4340}
4341
Steve Anton75737c02017-11-06 10:37:17 -08004342// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4343// vector of BaseChannel pointers instead of separate voice and video channel
4344// vectors. At that point, this will become a simple getter.
4345std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4346 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004347 if (voice_channel()) {
4348 channels.push_back(voice_channel());
4349 }
4350 if (video_channel()) {
4351 channels.push_back(video_channel());
4352 }
Steve Anton75737c02017-11-06 10:37:17 -08004353 if (rtp_data_channel_) {
4354 channels.push_back(rtp_data_channel_);
4355 }
4356 return channels;
4357}
4358
Steve Antonf8470812017-12-04 10:46:21 -08004359void PeerConnection::SetSessionError(SessionError error,
4360 const std::string& error_desc) {
4361 RTC_DCHECK_RUN_ON(signaling_thread());
4362 if (error != session_error_) {
4363 session_error_ = error;
4364 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004365 }
4366}
4367
Steve Anton3828c062017-12-06 10:34:51 -08004368RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004369 cricket::ContentSource source) {
4370 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004371
4372 // If there's already a pending error then no state transition should happen.
4373 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004374 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004375
4376 // If this is an answer then we know whether to BUNDLE or not. If both the
4377 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004378 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004379 const cricket::ContentGroup* local_bundle =
4380 local_description()->description()->GetGroupByName(
4381 cricket::GROUP_TYPE_BUNDLE);
4382 const cricket::ContentGroup* remote_bundle =
4383 remote_description()->description()->GetGroupByName(
4384 cricket::GROUP_TYPE_BUNDLE);
4385 if (local_bundle && remote_bundle) {
4386 // The answerer decides the transport to bundle on.
4387 const cricket::ContentGroup* answer_bundle =
4388 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4389 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4391 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004392 }
4393 }
Steve Anton75737c02017-11-06 10:37:17 -08004394 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004395
4396 // Only push down the transport description after potentially enabling BUNDLE;
4397 // we don't want to push down a description on a transport about to be
4398 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004399 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004400 if (!error.ok()) {
4401 return error;
4402 }
4403
4404 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004405 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004406 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004407 }
4408
4409 // Update the signaling state according to the specified state machine (see
4410 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004411 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004412 ChangeSignalingState(source == cricket::CS_LOCAL
4413 ? PeerConnectionInterface::kHaveLocalOffer
4414 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004415 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004416 ChangeSignalingState(source == cricket::CS_LOCAL
4417 ? PeerConnectionInterface::kHaveLocalPrAnswer
4418 : PeerConnectionInterface::kHaveRemotePrAnswer);
4419 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004420 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004421 ChangeSignalingState(PeerConnectionInterface::kStable);
4422 }
4423
4424 // Update internal objects according to the session description's media
4425 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004426 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004427 if (!error.ok()) {
4428 SetSessionError(SessionError::kContent, error.message());
4429 }
4430 if (session_error() != SessionError::kNone) {
4431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4432 }
4433
Steve Anton8a006912017-12-04 15:25:56 -08004434 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004435}
4436
Steve Anton8a006912017-12-04 15:25:56 -08004437RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004438 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004439 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004440 const SessionDescriptionInterface* sdesc =
4441 (source == cricket::CS_LOCAL ? local_description()
4442 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004443 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004444
4445 // Push down the new SDP media section for each audio/video transceiver.
4446 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004447 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004448 FindMediaSectionForTransceiver(transceiver, sdesc);
4449 cricket::BaseChannel* channel = transceiver->internal()->channel();
4450 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004451 continue;
4452 }
4453 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004454 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004455 if (!content_desc) {
4456 continue;
4457 }
4458 std::string error;
4459 bool success =
4460 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004461 ? channel->SetLocalContent(content_desc, type, &error)
4462 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004463 if (!success) {
4464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4465 }
4466 }
4467
4468 // If using the RtpDataChannel, push down the new SDP section for it too.
4469 if (rtp_data_channel_) {
4470 const ContentInfo* data_content =
4471 cricket::GetFirstDataContent(sdesc->description());
4472 if (data_content && !data_content->rejected) {
4473 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004474 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004475 if (data_desc) {
4476 std::string error;
4477 bool success =
4478 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004479 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4480 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004481 &error);
4482 if (!success) {
4483 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4484 std::move(error));
4485 }
Steve Anton75737c02017-11-06 10:37:17 -08004486 }
4487 }
4488 }
Steve Antoned10bd92017-12-05 10:52:59 -08004489
Steve Anton75737c02017-11-06 10:37:17 -08004490 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4491 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4492 if (sctp_transport_ && local_description() && remote_description() &&
4493 cricket::GetFirstDataContent(local_description()->description()) &&
4494 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004495 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004496 RTC_FROM_HERE,
4497 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004498 if (!success) {
4499 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4500 "Failed to push down SCTP parameters.");
4501 }
Steve Anton75737c02017-11-06 10:37:17 -08004502 }
Steve Antoned10bd92017-12-05 10:52:59 -08004503
Steve Anton8a006912017-12-04 15:25:56 -08004504 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004505}
4506
4507bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4508 RTC_DCHECK(network_thread()->IsCurrent());
4509 RTC_DCHECK(local_description());
4510 RTC_DCHECK(remote_description());
4511 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4512 // When we support "max-message-size", that would also be pushed down here.
4513 return sctp_transport_->Start(
4514 GetSctpPort(local_description()->description()),
4515 GetSctpPort(remote_description()->description()));
4516}
4517
Steve Anton8a006912017-12-04 15:25:56 -08004518RTCError PeerConnection::PushdownTransportDescription(
4519 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004520 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004521 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004522
Steve Anton8a006912017-12-04 15:25:56 -08004523 const SessionDescriptionInterface* sdesc =
4524 (source == cricket::CS_LOCAL ? local_description()
4525 : remote_description());
4526 RTC_DCHECK(sdesc);
4527 for (const cricket::TransportInfo& tinfo :
4528 sdesc->description()->transport_infos()) {
4529 std::string error;
4530 bool success;
4531 if (source == cricket::CS_LOCAL) {
4532 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004533 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004534 } else {
4535 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004536 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004537 }
4538 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004539 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4540 "Failed to push down transport description for " +
4541 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004542 }
4543 }
4544
Steve Anton8a006912017-12-04 15:25:56 -08004545 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004546}
4547
4548bool PeerConnection::GetTransportDescription(
4549 const SessionDescription* description,
4550 const std::string& content_name,
4551 cricket::TransportDescription* tdesc) {
4552 if (!description || !tdesc) {
4553 return false;
4554 }
4555 const TransportInfo* transport_info =
4556 description->GetTransportInfoByName(content_name);
4557 if (!transport_info) {
4558 return false;
4559 }
4560 *tdesc = transport_info->description;
4561 return true;
4562}
4563
4564bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4565 const std::string* first_content_name = bundle.FirstContentName();
4566 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004567 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004568 return false;
4569 }
4570 const std::string& transport_name = *first_content_name;
4571
4572 auto maybe_set_transport = [this, bundle,
4573 transport_name](cricket::BaseChannel* ch) {
4574 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004575 return;
Steve Anton75737c02017-11-06 10:37:17 -08004576 }
4577
4578 std::string old_transport_name = ch->transport_name();
4579 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004580 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4581 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004582 return;
Steve Anton75737c02017-11-06 10:37:17 -08004583 }
4584
4585 cricket::DtlsTransportInternal* rtp_dtls_transport =
4586 transport_controller_->CreateDtlsTransport(
4587 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4588 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4589 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4590 if (need_rtcp) {
4591 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4592 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4593 }
4594
4595 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004596 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4597 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004598 transport_controller_->DestroyDtlsTransport(
4599 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4600 // If the channel needs rtcp, it means that the channel used to have a
4601 // rtcp transport which needs to be deleted now.
4602 if (need_rtcp) {
4603 transport_controller_->DestroyDtlsTransport(
4604 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4605 }
Steve Anton75737c02017-11-06 10:37:17 -08004606 };
4607
Steve Antoned10bd92017-12-05 10:52:59 -08004608 for (auto transceiver : transceivers_) {
4609 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004610 }
Steve Antoned10bd92017-12-05 10:52:59 -08004611 maybe_set_transport(rtp_data_channel_);
4612
Steve Anton75737c02017-11-06 10:37:17 -08004613 // For SCTP, transport creation/deletion happens here instead of in the
4614 // object itself.
4615 if (sctp_transport_) {
4616 RTC_DCHECK(sctp_transport_name_);
4617 RTC_DCHECK(sctp_content_name_);
4618 if (transport_name != *sctp_transport_name_ &&
4619 bundle.HasContentName(*sctp_content_name_)) {
4620 network_thread()->Invoke<void>(
4621 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4622 transport_name));
4623 }
4624 }
4625
4626 return true;
4627}
4628
Steve Anton75737c02017-11-06 10:37:17 -08004629cricket::IceConfig PeerConnection::ParseIceConfig(
4630 const PeerConnectionInterface::RTCConfiguration& config) const {
4631 cricket::ContinualGatheringPolicy gathering_policy;
4632 // TODO(honghaiz): Add the third continual gathering policy in
4633 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4634 switch (config.continual_gathering_policy) {
4635 case PeerConnectionInterface::GATHER_ONCE:
4636 gathering_policy = cricket::GATHER_ONCE;
4637 break;
4638 case PeerConnectionInterface::GATHER_CONTINUALLY:
4639 gathering_policy = cricket::GATHER_CONTINUALLY;
4640 break;
4641 default:
4642 RTC_NOTREACHED();
4643 gathering_policy = cricket::GATHER_ONCE;
4644 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004645
Steve Anton75737c02017-11-06 10:37:17 -08004646 cricket::IceConfig ice_config;
4647 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4648 ice_config.prioritize_most_likely_candidate_pairs =
4649 config.prioritize_most_likely_ice_candidate_pairs;
4650 ice_config.backup_connection_ping_interval =
4651 config.ice_backup_candidate_pair_ping_interval;
4652 ice_config.continual_gathering_policy = gathering_policy;
4653 ice_config.presume_writable_when_fully_relayed =
4654 config.presume_writable_when_fully_relayed;
4655 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4656 ice_config.regather_all_networks_interval_range =
4657 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004658 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004659 return ice_config;
4660}
4661
Steve Anton75737c02017-11-06 10:37:17 -08004662bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4663 std::string* track_id) {
4664 if (!local_description()) {
4665 return false;
4666 }
4667 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4668 track_id);
4669}
4670
4671bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4672 std::string* track_id) {
4673 if (!remote_description()) {
4674 return false;
4675 }
4676 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4677 track_id);
4678}
4679
4680bool PeerConnection::SendData(const cricket::SendDataParams& params,
4681 const rtc::CopyOnWriteBuffer& payload,
4682 cricket::SendDataResult* result) {
4683 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004684 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4685 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004686 return false;
4687 }
4688 return rtp_data_channel_
4689 ? rtp_data_channel_->SendData(params, payload, result)
4690 : network_thread()->Invoke<bool>(
4691 RTC_FROM_HERE,
4692 Bind(&cricket::SctpTransportInternal::SendData,
4693 sctp_transport_.get(), params, payload, result));
4694}
4695
4696bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4697 if (!rtp_data_channel_ && !sctp_transport_) {
4698 // Don't log an error here, because DataChannels are expected to call
4699 // ConnectDataChannel in this state. It's the only way to initially tell
4700 // whether or not the underlying transport is ready.
4701 return false;
4702 }
4703 if (rtp_data_channel_) {
4704 rtp_data_channel_->SignalReadyToSendData.connect(
4705 webrtc_data_channel, &DataChannel::OnChannelReady);
4706 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4707 &DataChannel::OnDataReceived);
4708 } else {
4709 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4710 &DataChannel::OnChannelReady);
4711 SignalSctpDataReceived.connect(webrtc_data_channel,
4712 &DataChannel::OnDataReceived);
4713 SignalSctpStreamClosedRemotely.connect(
4714 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4715 }
4716 return true;
4717}
4718
4719void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4720 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004721 RTC_LOG(LS_ERROR)
4722 << "DisconnectDataChannel called when rtp_data_channel_ and "
4723 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004724 return;
4725 }
4726 if (rtp_data_channel_) {
4727 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4728 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4729 } else {
4730 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4731 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4732 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4733 }
4734}
4735
4736void PeerConnection::AddSctpDataStream(int sid) {
4737 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004738 RTC_LOG(LS_ERROR)
4739 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004740 return;
4741 }
4742 network_thread()->Invoke<void>(
4743 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4744 sctp_transport_.get(), sid));
4745}
4746
4747void PeerConnection::RemoveSctpDataStream(int sid) {
4748 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004749 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4750 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004751 return;
4752 }
4753 network_thread()->Invoke<void>(
4754 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4755 sctp_transport_.get(), sid));
4756}
4757
4758bool PeerConnection::ReadyToSendData() const {
4759 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4760 sctp_ready_to_send_data_;
4761}
4762
Steve Anton5dfde182018-02-06 10:34:40 -08004763std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4764 const {
4765 std::map<std::string, std::string> transport_names_by_mid;
4766 for (auto transceiver : transceivers_) {
4767 cricket::BaseChannel* channel = transceiver->internal()->channel();
4768 if (channel) {
4769 transport_names_by_mid[channel->content_name()] =
4770 channel->transport_name();
4771 }
Steve Anton75737c02017-11-06 10:37:17 -08004772 }
Steve Anton5dfde182018-02-06 10:34:40 -08004773 if (rtp_data_channel_) {
4774 transport_names_by_mid[rtp_data_channel_->content_name()] =
4775 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004776 }
4777 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004778 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004779 }
Steve Anton5dfde182018-02-06 10:34:40 -08004780 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004781}
4782
Steve Anton5dfde182018-02-06 10:34:40 -08004783std::map<std::string, cricket::TransportStats>
4784PeerConnection::GetTransportStatsByNames(
4785 const std::set<std::string>& transport_names) {
4786 if (!network_thread()->IsCurrent()) {
4787 return network_thread()
4788 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4789 RTC_FROM_HERE,
4790 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004791 }
Steve Anton5dfde182018-02-06 10:34:40 -08004792 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4793 for (const std::string& transport_name : transport_names) {
4794 cricket::TransportStats transport_stats;
4795 bool success =
4796 transport_controller_->GetStats(transport_name, &transport_stats);
4797 if (success) {
4798 transport_stats_by_name[transport_name] = std::move(transport_stats);
4799 } else {
4800 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4801 << transport_name;
4802 }
4803 }
4804 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004805}
4806
4807bool PeerConnection::GetLocalCertificate(
4808 const std::string& transport_name,
4809 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4810 return transport_controller_->GetLocalCertificate(transport_name,
4811 certificate);
4812}
4813
4814std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4815 const std::string& transport_name) {
4816 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4817}
4818
4819cricket::DataChannelType PeerConnection::data_channel_type() const {
4820 return data_channel_type_;
4821}
4822
4823bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4824 return pending_ice_restarts_.find(content_name) !=
4825 pending_ice_restarts_.end();
4826}
4827
Steve Anton75737c02017-11-06 10:37:17 -08004828bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4829 return transport_controller_->NeedsIceRestart(content_name);
4830}
4831
4832void PeerConnection::OnCertificateReady(
4833 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4834 transport_controller_->SetLocalCertificate(certificate);
4835}
4836
4837void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004838 SetSessionError(SessionError::kTransport,
4839 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004840}
4841
4842void PeerConnection::OnTransportControllerConnectionState(
4843 cricket::IceConnectionState state) {
4844 switch (state) {
4845 case cricket::kIceConnectionConnecting:
4846 // If the current state is Connected or Completed, then there were
4847 // writable channels but now there are not, so the next state must
4848 // be Disconnected.
4849 // kIceConnectionConnecting is currently used as the default,
4850 // un-connected state by the TransportController, so its only use is
4851 // detecting disconnections.
4852 if (ice_connection_state_ ==
4853 PeerConnectionInterface::kIceConnectionConnected ||
4854 ice_connection_state_ ==
4855 PeerConnectionInterface::kIceConnectionCompleted) {
4856 SetIceConnectionState(
4857 PeerConnectionInterface::kIceConnectionDisconnected);
4858 }
4859 break;
4860 case cricket::kIceConnectionFailed:
4861 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4862 break;
4863 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004864 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4865 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004866 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4867 break;
4868 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004869 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4870 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004871 if (ice_connection_state_ !=
4872 PeerConnectionInterface::kIceConnectionConnected) {
4873 // If jumping directly from "checking" to "connected",
4874 // signal "connected" first.
4875 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4876 }
4877 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4878 if (metrics_observer()) {
4879 ReportTransportStats();
4880 }
4881 break;
4882 default:
4883 RTC_NOTREACHED();
4884 }
4885}
4886
4887void PeerConnection::OnTransportControllerCandidatesGathered(
4888 const std::string& transport_name,
4889 const cricket::Candidates& candidates) {
4890 RTC_DCHECK(signaling_thread()->IsCurrent());
4891 int sdp_mline_index;
4892 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004893 RTC_LOG(LS_ERROR)
4894 << "OnTransportControllerCandidatesGathered: content name "
4895 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004896 return;
4897 }
4898
4899 for (cricket::Candidates::const_iterator citer = candidates.begin();
4900 citer != candidates.end(); ++citer) {
4901 // Use transport_name as the candidate media id.
4902 std::unique_ptr<JsepIceCandidate> candidate(
4903 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4904 if (local_description()) {
4905 mutable_local_description()->AddCandidate(candidate.get());
4906 }
4907 OnIceCandidate(std::move(candidate));
4908 }
4909}
4910
4911void PeerConnection::OnTransportControllerCandidatesRemoved(
4912 const std::vector<cricket::Candidate>& candidates) {
4913 RTC_DCHECK(signaling_thread()->IsCurrent());
4914 // Sanity check.
4915 for (const cricket::Candidate& candidate : candidates) {
4916 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004917 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4918 << "empty content name in candidate "
4919 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004920 return;
4921 }
4922 }
4923
4924 if (local_description()) {
4925 mutable_local_description()->RemoveCandidates(candidates);
4926 }
4927 OnIceCandidatesRemoved(candidates);
4928}
4929
4930void PeerConnection::OnTransportControllerDtlsHandshakeError(
4931 rtc::SSLHandshakeError error) {
4932 if (metrics_observer()) {
4933 metrics_observer()->IncrementEnumCounter(
4934 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4935 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4936 }
4937}
4938
Steve Antoned10bd92017-12-05 10:52:59 -08004939void PeerConnection::EnableSending() {
4940 for (auto transceiver : transceivers_) {
4941 cricket::BaseChannel* channel = transceiver->internal()->channel();
4942 if (channel && !channel->enabled()) {
4943 channel->Enable(true);
4944 }
Steve Anton75737c02017-11-06 10:37:17 -08004945 }
4946
Steve Anton4171afb2017-11-20 10:20:22 -08004947 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004948 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004949 }
Steve Anton75737c02017-11-06 10:37:17 -08004950}
4951
4952// Returns the media index for a local ice candidate given the content name.
4953bool PeerConnection::GetLocalCandidateMediaIndex(
4954 const std::string& content_name,
4955 int* sdp_mline_index) {
4956 if (!local_description() || !sdp_mline_index) {
4957 return false;
4958 }
4959
4960 bool content_found = false;
4961 const ContentInfos& contents = local_description()->description()->contents();
4962 for (size_t index = 0; index < contents.size(); ++index) {
4963 if (contents[index].name == content_name) {
4964 *sdp_mline_index = static_cast<int>(index);
4965 content_found = true;
4966 break;
4967 }
4968 }
4969 return content_found;
4970}
4971
4972bool PeerConnection::UseCandidatesInSessionDescription(
4973 const SessionDescriptionInterface* remote_desc) {
4974 if (!remote_desc) {
4975 return true;
4976 }
4977 bool ret = true;
4978
4979 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4980 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4981 for (size_t n = 0; n < candidates->count(); ++n) {
4982 const IceCandidateInterface* candidate = candidates->at(n);
4983 bool valid = false;
4984 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4985 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_INFO)
4987 << "UseCandidatesInSessionDescription: Not ready to use "
4988 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004989 }
4990 continue;
4991 }
4992 ret = UseCandidate(candidate);
4993 if (!ret) {
4994 break;
4995 }
4996 }
4997 }
4998 return ret;
4999}
5000
5001bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5002 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5003 size_t remote_content_size =
5004 remote_description()->description()->contents().size();
5005 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005006 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005007 return false;
5008 }
5009
5010 cricket::ContentInfo content =
5011 remote_description()->description()->contents()[mediacontent_index];
5012 std::vector<cricket::Candidate> candidates;
5013 candidates.push_back(candidate->candidate());
5014 // Invoking BaseSession method to handle remote candidates.
5015 std::string error;
5016 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5017 &error)) {
5018 // Candidates successfully submitted for checking.
5019 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5020 ice_connection_state_ ==
5021 PeerConnectionInterface::kIceConnectionDisconnected) {
5022 // If state is New, then the session has just gotten its first remote ICE
5023 // candidates, so go to Checking.
5024 // If state is Disconnected, the session is re-using old candidates or
5025 // receiving additional ones, so go to Checking.
5026 // If state is Connected, stay Connected.
5027 // TODO(bemasc): If state is Connected, and the new candidates are for a
5028 // newly added transport, then the state actually _should_ move to
5029 // checking. Add a way to distinguish that case.
5030 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5031 }
5032 // TODO(bemasc): If state is Completed, go back to Connected.
5033 } else {
5034 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005035 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005036 }
5037 }
5038 return true;
5039}
5040
5041void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005042 // Destroy video channel first since it may have a pointer to the
5043 // voice channel.
5044 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005045 if (!video_info || video_info->rejected) {
5046 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005047 }
5048
Steve Anton6fec8802017-12-04 10:37:29 -08005049 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5050 if (!audio_info || audio_info->rejected) {
5051 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005052 }
5053
5054 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5055 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005056 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005057 }
5058}
5059
Steve Antoneda6ccd2017-12-04 10:21:55 -08005060std::string PeerConnection::GetTransportNameForMediaSection(
5061 const std::string& mid,
5062 const cricket::ContentGroup* bundle_group) const {
5063 if (!bundle_group) {
5064 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005065 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005066 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005067 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005068 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005069 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005070 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005071 if (!bundle_group->HasContentName(mid)) {
5072 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5073 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005074 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005075 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5076 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005077}
5078
Steve Antondcc3c022017-12-22 16:02:54 -08005079RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5080 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005081 const cricket::ContentGroup* bundle_group = nullptr;
5082 if (configuration_.bundle_policy ==
5083 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005084 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005085 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5087 "max-bundle configured but session description "
5088 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005089 }
5090 }
Steve Antondcc3c022017-12-22 16:02:54 -08005091 return std::move(bundle_group);
5092}
5093
5094RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5095 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5096 if (!bundle_group_or_error.ok()) {
5097 return bundle_group_or_error.MoveError();
5098 }
5099 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005100
Steve Antoneda6ccd2017-12-04 10:21:55 -08005101 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005102 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005103 if (voice && !voice->rejected &&
5104 !GetAudioTransceiver()->internal()->channel()) {
5105 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5106 voice->name,
5107 GetTransportNameForMediaSection(voice->name, bundle_group));
5108 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005109 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5110 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005111 }
5112 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5113 }
5114
Steve Antondcc3c022017-12-22 16:02:54 -08005115 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005116 if (video && !video->rejected &&
5117 !GetVideoTransceiver()->internal()->channel()) {
5118 cricket::VideoChannel* video_channel = CreateVideoChannel(
5119 video->name,
5120 GetTransportNameForMediaSection(video->name, bundle_group));
5121 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005122 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5123 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005124 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005125 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005126 }
5127
Steve Antondcc3c022017-12-22 16:02:54 -08005128 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005129 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5130 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005131 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5132 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005133 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5134 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005135 }
5136 }
5137
Steve Anton8a006912017-12-04 15:25:56 -08005138 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005139}
5140
Steve Anton4171afb2017-11-20 10:20:22 -08005141// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005142cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5143 const std::string& mid,
5144 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005145 cricket::DtlsTransportInternal* rtp_dtls_transport =
5146 transport_controller_->CreateDtlsTransport(
5147 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5148 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5149 if (configuration_.rtcp_mux_policy !=
5150 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5151 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5152 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5153 }
5154
5155 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5156 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005157 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5158 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005159 if (!voice_channel) {
5160 transport_controller_->DestroyDtlsTransport(
5161 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5162 if (rtcp_dtls_transport) {
5163 transport_controller_->DestroyDtlsTransport(
5164 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5165 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005166 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005167 }
Steve Anton75737c02017-11-06 10:37:17 -08005168 voice_channel->SignalRtcpMuxFullyActive.connect(
5169 this, &PeerConnection::DestroyRtcpTransport_n);
5170 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5171 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005172 voice_channel->SignalSentPacket.connect(this,
5173 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005174
Steve Antoneda6ccd2017-12-04 10:21:55 -08005175 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005176}
5177
Steve Anton4171afb2017-11-20 10:20:22 -08005178// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005179cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5180 const std::string& mid,
5181 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005182 cricket::DtlsTransportInternal* rtp_dtls_transport =
5183 transport_controller_->CreateDtlsTransport(
5184 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5185 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5186 if (configuration_.rtcp_mux_policy !=
5187 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5188 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5189 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5190 }
5191
5192 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5193 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005194 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5195 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005196
5197 if (!video_channel) {
5198 transport_controller_->DestroyDtlsTransport(
5199 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5200 if (rtcp_dtls_transport) {
5201 transport_controller_->DestroyDtlsTransport(
5202 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5203 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005204 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005205 }
Steve Anton75737c02017-11-06 10:37:17 -08005206 video_channel->SignalRtcpMuxFullyActive.connect(
5207 this, &PeerConnection::DestroyRtcpTransport_n);
5208 video_channel->SignalDtlsSrtpSetupFailure.connect(
5209 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005210 video_channel->SignalSentPacket.connect(this,
5211 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005212
Steve Antoneda6ccd2017-12-04 10:21:55 -08005213 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005214}
5215
Steve Antoneda6ccd2017-12-04 10:21:55 -08005216bool PeerConnection::CreateDataChannel(const std::string& mid,
5217 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005218 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5219 if (sctp) {
5220 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005221 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005222 << "Trying to create SCTP transport, but didn't compile with "
5223 "SCTP support (HAVE_SCTP)";
5224 return false;
5225 }
5226 if (!network_thread()->Invoke<bool>(
5227 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005228 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005229 return false;
5230 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005231 for (const auto& channel : sctp_data_channels_) {
5232 channel->OnTransportChannelCreated();
5233 }
Steve Anton75737c02017-11-06 10:37:17 -08005234 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005235 cricket::DtlsTransportInternal* rtp_dtls_transport =
5236 transport_controller_->CreateDtlsTransport(
5237 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5238 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5239 if (configuration_.rtcp_mux_policy !=
5240 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5241 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5242 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5243 }
5244
5245 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5246 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005247 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005248
5249 if (!rtp_data_channel_) {
5250 transport_controller_->DestroyDtlsTransport(
5251 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5252 if (rtcp_dtls_transport) {
5253 transport_controller_->DestroyDtlsTransport(
5254 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5255 }
5256 return false;
5257 }
5258
5259 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5260 this, &PeerConnection::DestroyRtcpTransport_n);
5261 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5262 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5263 rtp_data_channel_->SignalSentPacket.connect(
5264 this, &PeerConnection::OnSentPacket_w);
5265 }
5266
Steve Anton75737c02017-11-06 10:37:17 -08005267 return true;
5268}
5269
5270Call::Stats PeerConnection::GetCallStats() {
5271 if (!worker_thread()->IsCurrent()) {
5272 return worker_thread()->Invoke<Call::Stats>(
5273 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5274 }
5275 if (call_) {
5276 return call_->GetStats();
5277 } else {
5278 return Call::Stats();
5279 }
5280}
5281
Steve Anton75737c02017-11-06 10:37:17 -08005282bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5283 const std::string& transport_name) {
5284 RTC_DCHECK(network_thread()->IsCurrent());
5285 RTC_DCHECK(sctp_factory_);
5286 cricket::DtlsTransportInternal* tc =
5287 transport_controller_->CreateDtlsTransport_n(
5288 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5289 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5290 RTC_DCHECK(sctp_transport_);
5291 sctp_invoker_.reset(new rtc::AsyncInvoker());
5292 sctp_transport_->SignalReadyToSendData.connect(
5293 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5294 sctp_transport_->SignalDataReceived.connect(
5295 this, &PeerConnection::OnSctpTransportDataReceived_n);
5296 sctp_transport_->SignalStreamClosedRemotely.connect(
5297 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005298 sctp_transport_name_ = transport_name;
5299 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005300 return true;
5301}
5302
5303void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5304 RTC_DCHECK(network_thread()->IsCurrent());
5305 RTC_DCHECK(sctp_transport_);
5306 RTC_DCHECK(sctp_transport_name_);
5307 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005308 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005309 cricket::DtlsTransportInternal* tc =
5310 transport_controller_->CreateDtlsTransport_n(
5311 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5312 sctp_transport_->SetTransportChannel(tc);
5313 transport_controller_->DestroyDtlsTransport_n(
5314 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5315}
5316
5317void PeerConnection::DestroySctpTransport_n() {
5318 RTC_DCHECK(network_thread()->IsCurrent());
5319 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005320 transport_controller_->DestroyDtlsTransport_n(
5321 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005322 sctp_content_name_.reset();
5323 sctp_transport_name_.reset();
5324 sctp_invoker_.reset(nullptr);
5325 sctp_ready_to_send_data_ = false;
5326}
5327
5328void PeerConnection::OnSctpTransportReadyToSendData_n() {
5329 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5330 RTC_DCHECK(network_thread()->IsCurrent());
5331 // Note: Cannot use rtc::Bind here because it will grab a reference to
5332 // PeerConnection and potentially cause PeerConnection to live longer than
5333 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5334 // be destroyed before PeerConnection is destroyed, and at that point all
5335 // pending tasks will be cleared.
5336 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5337 OnSctpTransportReadyToSendData_s(true);
5338 });
5339}
5340
5341void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5342 RTC_DCHECK(signaling_thread()->IsCurrent());
5343 sctp_ready_to_send_data_ = ready;
5344 SignalSctpReadyToSendData(ready);
5345}
5346
5347void PeerConnection::OnSctpTransportDataReceived_n(
5348 const cricket::ReceiveDataParams& params,
5349 const rtc::CopyOnWriteBuffer& payload) {
5350 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5351 RTC_DCHECK(network_thread()->IsCurrent());
5352 // Note: Cannot use rtc::Bind here because it will grab a reference to
5353 // PeerConnection and potentially cause PeerConnection to live longer than
5354 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5355 // be destroyed before PeerConnection is destroyed, and at that point all
5356 // pending tasks will be cleared.
5357 sctp_invoker_->AsyncInvoke<void>(
5358 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5359 OnSctpTransportDataReceived_s(params, payload);
5360 });
5361}
5362
5363void PeerConnection::OnSctpTransportDataReceived_s(
5364 const cricket::ReceiveDataParams& params,
5365 const rtc::CopyOnWriteBuffer& payload) {
5366 RTC_DCHECK(signaling_thread()->IsCurrent());
5367 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5368 // Received OPEN message; parse and signal that a new data channel should
5369 // be created.
5370 std::string label;
5371 InternalDataChannelInit config;
5372 config.id = params.ssrc;
5373 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005374 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5375 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005376 return;
5377 }
5378 config.open_handshake_role = InternalDataChannelInit::kAcker;
5379 OnDataChannelOpenMessage(label, config);
5380 } else {
5381 // Otherwise just forward the signal.
5382 SignalSctpDataReceived(params, payload);
5383 }
5384}
5385
5386void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5387 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5388 RTC_DCHECK(network_thread()->IsCurrent());
5389 sctp_invoker_->AsyncInvoke<void>(
5390 RTC_FROM_HERE, signaling_thread(),
5391 rtc::Bind(&sigslot::signal1<int>::operator(),
5392 &SignalSctpStreamClosedRemotely, sid));
5393}
5394
5395// Returns false if bundle is enabled and rtcp_mux is disabled.
5396bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5397 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5398 if (!bundle_enabled)
5399 return true;
5400
5401 const cricket::ContentGroup* bundle_group =
5402 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5403 RTC_DCHECK(bundle_group != NULL);
5404
5405 const cricket::ContentInfos& contents = desc->contents();
5406 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5407 citer != contents.end(); ++citer) {
5408 const cricket::ContentInfo* content = (&*citer);
5409 RTC_DCHECK(content != NULL);
5410 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005411 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005412 if (!HasRtcpMuxEnabled(content))
5413 return false;
5414 }
5415 }
5416 // RTCP-MUX is enabled in all the contents.
5417 return true;
5418}
5419
5420bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005421 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005422}
5423
Steve Anton8a006912017-12-04 15:25:56 -08005424RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005425 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005426 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005427 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005428 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005429 }
5430
5431 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
5434
Steve Anton3828c062017-12-06 10:34:51 -08005435 SdpType type = sdesc->GetType();
5436 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5437 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005438 LOG_AND_RETURN_ERROR(
5439 RTCErrorType::INVALID_PARAMETER,
5440 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005441 }
5442
5443 // Verify crypto settings.
5444 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005445 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5446 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005447 RTCError crypto_error =
5448 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005449 if (!crypto_error.ok()) {
5450 return crypto_error;
5451 }
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
5453
5454 // Verify ice-ufrag and ice-pwd.
5455 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005456 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5457 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005458 }
5459
5460 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005461 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5462 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464
5465 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5466 // m-lines that do not rtcp-mux enabled.
5467
5468 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005469 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005470 const cricket::SessionDescription* offer_desc =
5471 (source == cricket::CS_LOCAL) ? remote_description()->description()
5472 : local_description()->description();
5473 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5474 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005475 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5476 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478 } else {
5479 const cricket::SessionDescription* current_desc = nullptr;
5480 if (source == cricket::CS_LOCAL && local_description()) {
5481 current_desc = local_description()->description();
5482 } else if (source == cricket::CS_REMOTE && remote_description()) {
5483 current_desc = remote_description()->description();
5484 }
5485 // The re-offers should respect the order of m= sections in current
5486 // description. See RFC3264 Section 8 paragraph 4 for more details.
5487 if (current_desc &&
5488 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5490 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492 }
5493
Steve Anton8a006912017-12-04 15:25:56 -08005494 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
Steve Anton3828c062017-12-06 10:34:51 -08005497bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005498 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005499 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005500 return (state == PeerConnectionInterface::kStable) ||
5501 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005502 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005503 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005504 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5505 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5506 }
5507}
5508
Steve Anton3828c062017-12-06 10:34:51 -08005509bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005510 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005511 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005512 return (state == PeerConnectionInterface::kStable) ||
5513 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005514 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005515 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005516 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5517 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5518 }
5519}
5520
Steve Antonf8470812017-12-04 10:46:21 -08005521const char* PeerConnection::SessionErrorToString(SessionError error) const {
5522 switch (error) {
5523 case SessionError::kNone:
5524 return "ERROR_NONE";
5525 case SessionError::kContent:
5526 return "ERROR_CONTENT";
5527 case SessionError::kTransport:
5528 return "ERROR_TRANSPORT";
5529 }
5530 RTC_NOTREACHED();
5531 return "";
5532}
5533
Steve Anton75737c02017-11-06 10:37:17 -08005534std::string PeerConnection::GetSessionErrorMsg() {
5535 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005536 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5537 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005538 return desc.str();
5539}
5540
5541// We need to check the local/remote description for the Transport instead of
5542// the session, because a new Transport added during renegotiation may have
5543// them unset while the session has them set from the previous negotiation.
5544// Not doing so may trigger the auto generation of transport description and
5545// mess up DTLS identity information, ICE credential, etc.
5546bool PeerConnection::ReadyToUseRemoteCandidate(
5547 const IceCandidateInterface* candidate,
5548 const SessionDescriptionInterface* remote_desc,
5549 bool* valid) {
5550 *valid = true;
5551
5552 const SessionDescriptionInterface* current_remote_desc =
5553 remote_desc ? remote_desc : remote_description();
5554
5555 if (!current_remote_desc) {
5556 return false;
5557 }
5558
5559 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5560 size_t remote_content_size =
5561 current_remote_desc->description()->contents().size();
5562 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005563 RTC_LOG(LS_ERROR)
5564 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5565 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005566
5567 *valid = false;
5568 return false;
5569 }
5570
5571 cricket::ContentInfo content =
5572 current_remote_desc->description()->contents()[mediacontent_index];
5573
5574 const std::string transport_name = GetTransportName(content.name);
5575 if (transport_name.empty()) {
5576 return false;
5577 }
5578 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5579}
5580
5581bool PeerConnection::SrtpRequired() const {
5582 return dtls_enabled_ ||
5583 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5584}
5585
5586void PeerConnection::OnTransportControllerGatheringState(
5587 cricket::IceGatheringState state) {
5588 RTC_DCHECK(signaling_thread()->IsCurrent());
5589 if (state == cricket::kIceGatheringGathering) {
5590 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5591 } else if (state == cricket::kIceGatheringComplete) {
5592 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5593 }
5594}
5595
5596void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005597 std::map<std::string, std::set<cricket::MediaType>>
5598 media_types_by_transport_name;
5599 for (auto transceiver : transceivers_) {
5600 if (transceiver->internal()->channel()) {
5601 const std::string& transport_name =
5602 transceiver->internal()->channel()->transport_name();
5603 media_types_by_transport_name[transport_name].insert(
5604 transceiver->internal()->media_type());
5605 }
Steve Anton75737c02017-11-06 10:37:17 -08005606 }
5607 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005608 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5609 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005610 }
5611 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005612 media_types_by_transport_name[*sctp_transport_name_].insert(
5613 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005614 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005615 for (const auto& entry : media_types_by_transport_name) {
5616 const std::string& transport_name = entry.first;
5617 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005618 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005619 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005620 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005621 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005622 }
5623 }
5624}
5625// Walk through the ConnectionInfos to gather best connection usage
5626// for IPv4 and IPv6.
5627void PeerConnection::ReportBestConnectionState(
5628 const cricket::TransportStats& stats) {
5629 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005630 for (const cricket::TransportChannelStats& channel_stats :
5631 stats.channel_stats) {
5632 for (const cricket::ConnectionInfo& connection_info :
5633 channel_stats.connection_infos) {
5634 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005635 continue;
5636 }
5637
5638 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005639 const cricket::Candidate& local = connection_info.local_candidate;
5640 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005641
5642 // Increment the counter for IceCandidatePairType.
5643 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5644 (local.type() == RELAY_PORT_TYPE &&
5645 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5646 type = kEnumCounterIceCandidatePairTypeTcp;
5647 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5648 type = kEnumCounterIceCandidatePairTypeUdp;
5649 } else {
5650 RTC_CHECK(0);
5651 }
5652 metrics_observer()->IncrementEnumCounter(
5653 type, GetIceCandidatePairCounter(local, remote),
5654 kIceCandidatePairMax);
5655
5656 // Increment the counter for IP type.
5657 if (local.address().family() == AF_INET) {
5658 metrics_observer()->IncrementEnumCounter(
5659 kEnumCounterAddressFamily, kBestConnections_IPv4,
5660 kPeerConnectionAddressFamilyCounter_Max);
5661
5662 } else if (local.address().family() == AF_INET6) {
5663 metrics_observer()->IncrementEnumCounter(
5664 kEnumCounterAddressFamily, kBestConnections_IPv6,
5665 kPeerConnectionAddressFamilyCounter_Max);
5666 } else {
5667 RTC_CHECK(0);
5668 }
5669
5670 return;
5671 }
5672 }
5673}
5674
5675void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005676 const cricket::TransportStats& stats,
5677 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005678 RTC_DCHECK(metrics_observer());
5679 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5680 return;
5681 }
5682
5683 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5684 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5685 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5686 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5687 return;
5688 }
5689
Steve Antonc7b964c2018-02-01 14:39:45 -08005690 for (cricket::MediaType media_type : media_types) {
5691 PeerConnectionEnumCounterType srtp_counter_type;
5692 PeerConnectionEnumCounterType ssl_counter_type;
5693 switch (media_type) {
5694 case cricket::MEDIA_TYPE_AUDIO:
5695 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5696 ssl_counter_type = kEnumCounterAudioSslCipher;
5697 break;
5698 case cricket::MEDIA_TYPE_VIDEO:
5699 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5700 ssl_counter_type = kEnumCounterVideoSslCipher;
5701 break;
5702 case cricket::MEDIA_TYPE_DATA:
5703 srtp_counter_type = kEnumCounterDataSrtpCipher;
5704 ssl_counter_type = kEnumCounterDataSslCipher;
5705 break;
5706 default:
5707 RTC_NOTREACHED();
5708 continue;
5709 }
5710 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5711 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5712 srtp_crypto_suite);
5713 }
5714 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5715 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5716 ssl_cipher_suite);
5717 }
Steve Anton75737c02017-11-06 10:37:17 -08005718 }
5719}
5720
5721void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5722 RTC_DCHECK(worker_thread()->IsCurrent());
5723 RTC_DCHECK(call_);
5724 call_->OnSentPacket(sent_packet);
5725}
5726
5727const std::string PeerConnection::GetTransportName(
5728 const std::string& content_name) {
5729 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005730 if (channel) {
5731 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005732 }
Steve Anton6fec8802017-12-04 10:37:29 -08005733 if (sctp_transport_) {
5734 RTC_DCHECK(sctp_content_name_);
5735 RTC_DCHECK(sctp_transport_name_);
5736 if (content_name == *sctp_content_name_) {
5737 return *sctp_transport_name_;
5738 }
5739 }
5740 // Return an empty string if failed to retrieve the transport name.
5741 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005742}
5743
5744void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5745 RTC_DCHECK(network_thread()->IsCurrent());
5746 transport_controller_->DestroyDtlsTransport_n(
5747 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5748}
5749
Steve Anton6fec8802017-12-04 10:37:29 -08005750void PeerConnection::DestroyTransceiverChannel(
5751 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5752 transceiver) {
5753 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005754
Steve Anton6fec8802017-12-04 10:37:29 -08005755 cricket::BaseChannel* channel = transceiver->internal()->channel();
5756 if (channel) {
5757 transceiver->internal()->SetChannel(nullptr);
5758 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005759 }
5760}
5761
5762void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005763 if (rtp_data_channel_) {
5764 OnDataChannelDestroyed();
5765 DestroyBaseChannel(rtp_data_channel_);
5766 rtp_data_channel_ = nullptr;
5767 }
5768
5769 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5770 // grab a reference to this PeerConnection. If this is called from the
5771 // PeerConnection destructor, the RefCountedObject vtable will have already
5772 // been destroyed (since it is a subclass of PeerConnection) and using
5773 // rtc::Bind will cause "Pure virtual function called" error to appear.
5774
5775 if (sctp_transport_) {
5776 OnDataChannelDestroyed();
5777 network_thread()->Invoke<void>(RTC_FROM_HERE,
5778 [this] { DestroySctpTransport_n(); });
5779 }
5780}
5781
5782void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5783 RTC_DCHECK(channel);
5784 RTC_DCHECK(channel->rtp_dtls_transport());
5785
5786 // Need to cache these before destroying the base channel so that we do not
5787 // access uninitialized memory.
5788 const std::string transport_name =
5789 channel->rtp_dtls_transport()->transport_name();
5790 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5791
5792 switch (channel->media_type()) {
5793 case cricket::MEDIA_TYPE_AUDIO:
5794 channel_manager()->DestroyVoiceChannel(
5795 static_cast<cricket::VoiceChannel*>(channel));
5796 break;
5797 case cricket::MEDIA_TYPE_VIDEO:
5798 channel_manager()->DestroyVideoChannel(
5799 static_cast<cricket::VideoChannel*>(channel));
5800 break;
5801 case cricket::MEDIA_TYPE_DATA:
5802 channel_manager()->DestroyRtpDataChannel(
5803 static_cast<cricket::RtpDataChannel*>(channel));
5804 break;
5805 default:
5806 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5807 break;
5808 }
5809
5810 // |channel| can no longer be used.
5811
Steve Anton75737c02017-11-06 10:37:17 -08005812 transport_controller_->DestroyDtlsTransport(
5813 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5814 if (need_to_delete_rtcp) {
5815 transport_controller_->DestroyDtlsTransport(
5816 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5817 }
5818}
5819
Harald Alvestrand89061872018-01-02 14:08:34 +01005820void PeerConnection::ClearStatsCache() {
5821 if (stats_collector_) {
5822 stats_collector_->ClearCachedStatsReport();
5823 }
5824}
5825
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005826} // namespace webrtc