blob: 74fe0300088004c28fd080a4a36ec422a6a2a78e [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
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "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
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 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 crypto attributes, since only the crypto attributes
438 // from the first section actually get used.
439 continue;
440 }
441
442 // If the content isn't rejected or bundled into another m= section, crypto
443 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800444 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800445 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800446 if (!media || !tinfo) {
447 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800449 }
450 if (dtls_enabled) {
451 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 RTC_LOG(LS_WARNING)
453 << "Session description must have DTLS fingerprint if "
454 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800455 return RTCError(RTCErrorType::INVALID_PARAMETER,
456 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800457 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458 NoteKeyProtocolAndMedia(webrtc::kEnumCounterKeyProtocolDtls,
459 media->type(), uma_observer);
Steve Anton75737c02017-11-06 10:37:17 -0800460 } else {
461 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100462 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800463 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800464 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100466 NoteKeyProtocolAndMedia(webrtc::kEnumCounterKeyProtocolSdes,
467 media->type(), uma_observer);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800471}
472
473// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
474// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
475// media section/description in the BUNDLE group) needs a ufrag and pwd.
476bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have ufrag/password, since only the ufrag/password from
488 // the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section,
493 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800503 return false;
504 }
505 }
506 return true;
507}
508
509bool GetTrackIdBySsrc(const SessionDescription* session_description,
510 uint32_t ssrc,
511 std::string* track_id) {
512 RTC_DCHECK(track_id != NULL);
513
Steve Antonb1c1de12017-12-21 15:14:30 -0800514 const cricket::AudioContentDescription* audio_desc =
515 cricket::GetFirstAudioContentDescription(session_description);
516 if (audio_desc) {
517 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::VideoContentDescription* video_desc =
525 cricket::GetFirstVideoContentDescription(session_description);
526 if (video_desc) {
527 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800528 if (found) {
529 *track_id = found->id;
530 return true;
531 }
532 }
533 return false;
534}
535
536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
596 std::ostringstream oss;
597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
599 return oss.str();
600}
601
Steve Anton75737c02017-11-06 10:37:17 -0800602} // namespace
603
Henrik Boström31638672017-11-23 17:48:32 +0100604// Upon completion, posts a task to execute the callback of the
605// SetSessionDescriptionObserver asynchronously on the same thread. At this
606// point, the state of the peer connection might no longer reflect the effects
607// of the SetRemoteDescription operation, as the peer connection could have been
608// modified during the post.
609// TODO(hbos): Remove this class once we remove the version of
610// PeerConnectionInterface::SetRemoteDescription() that takes a
611// SetSessionDescriptionObserver as an argument.
612class PeerConnection::SetRemoteDescriptionObserverAdapter
613 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
614 public:
615 SetRemoteDescriptionObserverAdapter(
616 rtc::scoped_refptr<PeerConnection> pc,
617 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
618 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
619
620 // SetRemoteDescriptionObserverInterface implementation.
621 void OnSetRemoteDescriptionComplete(RTCError error) override {
622 if (error.ok())
623 pc_->PostSetSessionDescriptionSuccess(wrapper_);
624 else
625 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
626 }
627
628 private:
629 rtc::scoped_refptr<PeerConnection> pc_;
630 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
631};
632
deadbeef293e9262017-01-11 12:28:30 -0800633bool PeerConnectionInterface::RTCConfiguration::operator==(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700636 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800637 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000638 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800640 BundlePolicy bundle_policy;
641 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700642 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
643 int ice_candidate_pool_size;
644 bool disable_ipv6;
645 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700646 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100647 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700648 bool enable_rtp_data_channel;
649 rtc::Optional<int> screencast_min_bitrate;
650 rtc::Optional<bool> combined_audio_video_bwe;
651 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800652 TcpCandidatePolicy tcp_candidate_policy;
653 CandidateNetworkPolicy candidate_network_policy;
654 int audio_jitter_buffer_max_packets;
655 bool audio_jitter_buffer_fast_accelerate;
656 int ice_connection_receiving_timeout;
657 int ice_backup_candidate_pair_ping_interval;
658 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800659 bool prioritize_most_likely_ice_candidate_pairs;
660 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800661 bool prune_turn_ports;
662 bool presume_writable_when_fully_relayed;
663 bool enable_ice_renomination;
664 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800665 rtc::Optional<int> ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800666 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200668 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800669 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800670 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800671 };
672 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
673 "Did you add something to RTCConfiguration and forget to "
674 "update operator==?");
675 return type == o.type && servers == o.servers &&
676 bundle_policy == o.bundle_policy &&
677 rtcp_mux_policy == o.rtcp_mux_policy &&
678 tcp_candidate_policy == o.tcp_candidate_policy &&
679 candidate_network_policy == o.candidate_network_policy &&
680 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
681 audio_jitter_buffer_fast_accelerate ==
682 o.audio_jitter_buffer_fast_accelerate &&
683 ice_connection_receiving_timeout ==
684 o.ice_connection_receiving_timeout &&
685 ice_backup_candidate_pair_ping_interval ==
686 o.ice_backup_candidate_pair_ping_interval &&
687 continual_gathering_policy == o.continual_gathering_policy &&
688 certificates == o.certificates &&
689 prioritize_most_likely_ice_candidate_pairs ==
690 o.prioritize_most_likely_ice_candidate_pairs &&
691 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800692 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700693 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100694 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800695 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800696 screencast_min_bitrate == o.screencast_min_bitrate &&
697 combined_audio_video_bwe == o.combined_audio_video_bwe &&
698 enable_dtls_srtp == o.enable_dtls_srtp &&
699 ice_candidate_pool_size == o.ice_candidate_pool_size &&
700 prune_turn_ports == o.prune_turn_ports &&
701 presume_writable_when_fully_relayed ==
702 o.presume_writable_when_fully_relayed &&
703 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800704 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800706 stun_candidate_keepalive_interval ==
707 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200708 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800709 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800710 sdp_semantics == o.sdp_semantics &&
711 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800712}
713
714bool PeerConnectionInterface::RTCConfiguration::operator!=(
715 const PeerConnectionInterface::RTCConfiguration& o) const {
716 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800717}
718
zhihuang8f65cdf2016-05-06 18:40:30 -0700719// Generate a RTCP CNAME when a PeerConnection is created.
720std::string GenerateRtcpCname() {
721 std::string cname;
722 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100723 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800724 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700725 }
726 return cname;
727}
728
zhihuang1c378ed2017-08-17 14:10:50 -0700729bool ValidateOfferAnswerOptions(
730 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
731 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
732 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700733}
734
zhihuang1c378ed2017-08-17 14:10:50 -0700735// From |rtc_options|, fill parts of |session_options| shared by all generated
736// m= sections (in other words, nothing that involves a map/array).
737void ExtractSharedMediaSessionOptions(
738 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
739 cricket::MediaSessionOptions* session_options) {
740 session_options->vad_enabled = rtc_options.voice_activity_detection;
741 session_options->bundle_enabled = rtc_options.use_rtp_mux;
742}
zhihuanga77e6bb2017-08-14 18:17:48 -0700743
zhihuang1c378ed2017-08-17 14:10:50 -0700744bool ConvertConstraintsToOfferAnswerOptions(
745 const MediaConstraintsInterface* constraints,
746 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700747 if (!constraints) {
748 return true;
749 }
zhihuang1c378ed2017-08-17 14:10:50 -0700750
751 bool value = false;
752 size_t mandatory_constraints_satisfied = 0;
753
754 if (FindConstraint(constraints,
755 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
756 &mandatory_constraints_satisfied)) {
757 offer_answer_options->offer_to_receive_audio =
758 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
759 kOfferToReceiveMediaTrue
760 : 0;
761 }
762
763 if (FindConstraint(constraints,
764 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
765 &mandatory_constraints_satisfied)) {
766 offer_answer_options->offer_to_receive_video =
767 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
768 kOfferToReceiveMediaTrue
769 : 0;
770 }
771 if (FindConstraint(constraints,
772 MediaConstraintsInterface::kVoiceActivityDetection, &value,
773 &mandatory_constraints_satisfied)) {
774 offer_answer_options->voice_activity_detection = value;
775 }
776 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
777 &mandatory_constraints_satisfied)) {
778 offer_answer_options->use_rtp_mux = value;
779 }
780 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
781 &value, &mandatory_constraints_satisfied)) {
782 offer_answer_options->ice_restart = value;
783 }
784
deadbeefab9b2d12015-10-14 11:33:11 -0700785 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
786}
787
zhihuang38ede132017-06-15 12:52:32 -0700788PeerConnection::PeerConnection(PeerConnectionFactory* factory,
789 std::unique_ptr<RtcEventLog> event_log,
790 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700792 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700793 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700794 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700795 remote_streams_(StreamCollection::Create()),
796 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797
798PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800800 RTC_DCHECK_RUN_ON(signaling_thread());
801
Steve Anton8af21862017-12-15 11:20:13 -0800802 // Need to stop transceivers before destroying the stats collector because
803 // AudioRtpSender has a reference to the StatsCollector it will update when
804 // stopping.
805 for (auto transceiver : transceivers_) {
806 transceiver->Stop();
807 }
Steve Anton4171afb2017-11-20 10:20:22 -0800808
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700809 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800810 if (stats_collector_) {
811 stats_collector_->WaitForPendingRequest();
812 stats_collector_ = nullptr;
813 }
Steve Anton75737c02017-11-06 10:37:17 -0800814
Steve Anton8af21862017-12-15 11:20:13 -0800815 // Don't destroy BaseChannels until after stats has been cleaned up so that
816 // the last stats request can still read from the channels.
817 DestroyAllChannels();
818
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800820
821 webrtc_session_desc_factory_.reset();
822 sctp_invoker_.reset();
823 sctp_factory_.reset();
824 transport_controller_.reset();
825
deadbeef91dd5672016-05-18 16:55:30 -0700826 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700827 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700828 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700829 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700830 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700831 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800832 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700833 event_log_.reset();
834 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835}
836
Steve Anton8af21862017-12-15 11:20:13 -0800837void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800838 // Destroy video channels first since they may have a pointer to a voice
839 // channel.
840 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800841 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800842 DestroyTransceiverChannel(transceiver);
843 }
844 }
845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800846 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800847 DestroyTransceiverChannel(transceiver);
848 }
849 }
850 DestroyDataChannel();
851}
852
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000854 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700855 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200856 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800857 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100858 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700859
860 RTCError config_error = ValidateConfiguration(configuration);
861 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700863 return false;
864 }
865
deadbeef293e9262017-01-11 12:28:30 -0800866 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_ERROR)
868 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100869 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800870 return false;
871 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200872
deadbeef653b8e02015-11-11 12:55:10 -0800873 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800874 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100875 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100876 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800877 return false;
878 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000879 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800880 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800881
deadbeef91dd5672016-05-18 16:55:30 -0700882 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700883 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700884 if (!network_thread()->Invoke<bool>(
885 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
886 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 return false;
888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889
Steve Anton75737c02017-11-06 10:37:17 -0800890 // RFC 3264: The numeric value of the session id and version in the
891 // o line MUST be representable with a "64 bit signed integer".
892 // Due to this constraint session id |session_id_| is max limited to
893 // LLONG_MAX.
894 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
895 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800896 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
897 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800898 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
899 transport_controller_->SignalConnectionState.connect(
900 this, &PeerConnection::OnTransportControllerConnectionState);
901 transport_controller_->SignalGatheringState.connect(
902 this, &PeerConnection::OnTransportControllerGatheringState);
903 transport_controller_->SignalCandidatesGathered.connect(
904 this, &PeerConnection::OnTransportControllerCandidatesGathered);
905 transport_controller_->SignalCandidatesRemoved.connect(
906 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
907 transport_controller_->SignalDtlsHandshakeError.connect(
908 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
909
910 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700911
deadbeefab9b2d12015-10-14 11:33:11 -0700912 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700913 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914
Steve Antonba818672017-11-06 10:21:57 -0800915 configuration_ = configuration;
916
Steve Anton75737c02017-11-06 10:37:17 -0800917 const PeerConnectionFactoryInterface::Options& options = factory_->options();
918
919 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
920
921 // Obtain a certificate from RTCConfiguration if any were provided (optional).
922 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
923 if (!configuration.certificates.empty()) {
924 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
925 // just picking the first one. The decision should be made based on the DTLS
926 // handshake. The DTLS negotiations need to know about all certificates.
927 certificate = configuration.certificates[0];
928 }
929
Steve Antond25da372017-11-06 14:50:29 -0800930 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800931
932 if (options.disable_encryption) {
933 dtls_enabled_ = false;
934 } else {
935 // Enable DTLS by default if we have an identity store or a certificate.
936 dtls_enabled_ = (cert_generator || certificate);
937 // |configuration| can override the default |dtls_enabled_| value.
938 if (configuration.enable_dtls_srtp) {
939 dtls_enabled_ = *(configuration.enable_dtls_srtp);
940 }
941 }
942
943 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
944 // It takes precendence over the disable_sctp_data_channels
945 // PeerConnectionFactoryInterface::Options.
946 if (configuration.enable_rtp_data_channel) {
947 data_channel_type_ = cricket::DCT_RTP;
948 } else {
949 // DTLS has to be enabled to use SCTP.
950 if (!options.disable_sctp_data_channels && dtls_enabled_) {
951 data_channel_type_ = cricket::DCT_SCTP;
952 }
953 }
954
955 video_options_.screencast_min_bitrate_kbps =
956 configuration.screencast_min_bitrate;
957 audio_options_.combined_audio_video_bwe =
958 configuration.combined_audio_video_bwe;
959
960 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100961 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800962
963 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100964 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800965
966 // Whether the certificate generator/certificate is null or not determines
967 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
968 // the right instructions by clearing the variables if needed.
969 if (!dtls_enabled_) {
970 cert_generator.reset();
971 certificate = nullptr;
972 } else if (certificate) {
973 // Favor generated certificate over the certificate generator.
974 cert_generator.reset();
975 }
976
977 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
978 signaling_thread(), channel_manager(), this, session_id(),
979 std::move(cert_generator), certificate));
980 webrtc_session_desc_factory_->SignalCertificateReady.connect(
981 this, &PeerConnection::OnCertificateReady);
982
983 if (options.disable_encryption) {
984 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
985 }
986
987 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
988 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989
Steve Anton4171afb2017-11-20 10:20:22 -0800990 // Add default audio/video transceivers for Plan B SDP.
991 if (!IsUnifiedPlan()) {
992 transceivers_.push_back(
993 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
994 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
995 transceivers_.push_back(
996 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
997 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
998 }
999
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 return true;
1001}
1002
Steve Anton038834f2017-07-14 15:59:59 -07001003RTCError PeerConnection::ValidateConfiguration(
1004 const RTCConfiguration& config) const {
1005 if (config.ice_regather_interval_range &&
1006 config.continual_gathering_policy == GATHER_ONCE) {
1007 return RTCError(RTCErrorType::INVALID_PARAMETER,
1008 "ice_regather_interval_range specified but continual "
1009 "gathering policy is GATHER_ONCE");
1010 }
1011 return RTCError::OK();
1012}
1013
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001014rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001016 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1017 "Plan SdpSemantics. Please use GetSenders "
1018 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001019 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020}
1021
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001022rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001024 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1025 "Plan SdpSemantics. Please use GetReceivers "
1026 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001027 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028}
1029
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001030bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001031 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1032 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001033 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 if (IsClosed()) {
1035 return false;
1036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 return false;
1039 }
deadbeefab9b2d12015-10-14 11:33:11 -07001040
1041 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001042 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1043 observer->SignalAudioTrackAdded.connect(this,
1044 &PeerConnection::OnAudioTrackAdded);
1045 observer->SignalAudioTrackRemoved.connect(
1046 this, &PeerConnection::OnAudioTrackRemoved);
1047 observer->SignalVideoTrackAdded.connect(this,
1048 &PeerConnection::OnVideoTrackAdded);
1049 observer->SignalVideoTrackRemoved.connect(
1050 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001051 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001052
deadbeefab9b2d12015-10-14 11:33:11 -07001053 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001054 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001055 }
1056 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001057 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001058 }
1059
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001060 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 observer_->OnRenegotiationNeeded();
1062 return true;
1063}
1064
1065void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001066 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1067 "Plan SdpSemantics. Please use RemoveTrack "
1068 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001069 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001070 if (!IsClosed()) {
1071 for (const auto& track : local_stream->GetAudioTracks()) {
1072 RemoveAudioTrack(track.get(), local_stream);
1073 }
1074 for (const auto& track : local_stream->GetVideoTracks()) {
1075 RemoveVideoTrack(track.get(), local_stream);
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 }
deadbeefab9b2d12015-10-14 11:33:11 -07001078 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001079 stream_observers_.erase(
1080 std::remove_if(
1081 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001082 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001083 return observer->stream()->label().compare(local_stream->label()) ==
1084 0;
1085 }),
1086 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 if (IsClosed()) {
1089 return;
1090 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 observer_->OnRenegotiationNeeded();
1092}
1093
deadbeefe1f9d832016-01-14 15:35:42 -08001094rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1095 MediaStreamTrackInterface* track,
1096 std::vector<MediaStreamInterface*> streams) {
1097 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001098 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001099 for (auto* stream : streams) {
1100 if (!stream) {
1101 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1102 return nullptr;
1103 }
Seth Hampson845e8782018-03-02 11:34:10 -08001104 stream_ids.push_back(stream->label());
Steve Antonf9381f02017-12-14 10:23:57 -08001105 }
Seth Hampson845e8782018-03-02 11:34:10 -08001106 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001107 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001108 return nullptr;
1109 }
Steve Antonf9381f02017-12-14 10:23:57 -08001110 return sender_or_error.MoveValue();
1111}
1112
Steve Anton2d6c76a2018-01-05 17:10:52 -08001113RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001114 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001115 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001116 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001117 if (!track) {
1118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1119 }
1120 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1121 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1122 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1123 "Track has invalid kind: " + track->kind());
1124 }
1125 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
Seth Hampson845e8782018-03-02 11:34:10 -08001126 if (stream_ids.size() > 1u) {
Steve Antonf9381f02017-12-14 10:23:57 -08001127 LOG_AND_RETURN_ERROR(
1128 RTCErrorType::UNSUPPORTED_OPERATION,
1129 "AddTrack with more than one stream is not currently supported.");
1130 }
1131 if (IsClosed()) {
1132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1133 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001134 }
Steve Anton4171afb2017-11-20 10:20:22 -08001135 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001136 LOG_AND_RETURN_ERROR(
1137 RTCErrorType::INVALID_PARAMETER,
1138 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001139 }
Steve Antonf9381f02017-12-14 10:23:57 -08001140 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1141 // one stream. AddTrackInternal will return an error if there is more than one
1142 // stream, but if the caller specifies none then we need to generate a random
Seth Hampson845e8782018-03-02 11:34:10 -08001143 // stream id.
1144 std::vector<std::string> adjusted_stream_ids = stream_ids;
1145 if (stream_ids.empty()) {
1146 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
Steve Antonf9381f02017-12-14 10:23:57 -08001147 }
Seth Hampson845e8782018-03-02 11:34:10 -08001148 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001149 auto sender_or_error =
Seth Hampson845e8782018-03-02 11:34:10 -08001150 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1151 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001152 if (sender_or_error.ok()) {
1153 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001154 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001155 }
1156 return sender_or_error;
1157}
deadbeefe1f9d832016-01-14 15:35:42 -08001158
Steve Antonf9381f02017-12-14 10:23:57 -08001159RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1160PeerConnection::AddTrackPlanB(
1161 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001162 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001163 cricket::MediaType media_type =
1164 (track->kind() == MediaStreamTrackInterface::kAudioKind
1165 ? cricket::MEDIA_TYPE_AUDIO
1166 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001167 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001168 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001169 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001170 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001171 const RtpSenderInfo* sender_info =
1172 FindSenderInfo(local_audio_sender_infos_,
1173 new_sender->internal()->stream_id(), track->id());
1174 if (sender_info) {
1175 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 } else {
1178 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001179 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001180 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001181 const RtpSenderInfo* sender_info =
1182 FindSenderInfo(local_video_sender_infos_,
1183 new_sender->internal()->stream_id(), track->id());
1184 if (sender_info) {
1185 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001186 }
deadbeefe1f9d832016-01-14 15:35:42 -08001187 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001188 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001189}
deadbeefe1f9d832016-01-14 15:35:42 -08001190
Steve Antonf9381f02017-12-14 10:23:57 -08001191RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1192PeerConnection::AddTrackUnifiedPlan(
1193 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001194 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001195 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1196 if (transceiver) {
1197 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001198 transceiver->internal()->set_direction(
1199 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001200 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001201 transceiver->internal()->set_direction(
1202 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001203 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001204 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001205 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001206 } else {
1207 cricket::MediaType media_type =
1208 (track->kind() == MediaStreamTrackInterface::kAudioKind
1209 ? cricket::MEDIA_TYPE_AUDIO
1210 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001211 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001212 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1213 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001215 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 return transceiver->sender();
1218}
1219
1220rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1221PeerConnection::FindFirstTransceiverForAddedTrack(
1222 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1223 RTC_DCHECK(track);
1224 for (auto transceiver : transceivers_) {
1225 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001226 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001227 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001228 !transceiver->internal()->has_ever_been_used_to_send() &&
1229 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001230 return transceiver;
1231 }
1232 }
1233 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001234}
1235
1236bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1237 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001238 return RemoveTrackInternal(sender).ok();
1239}
1240
1241RTCError PeerConnection::RemoveTrackInternal(
1242 rtc::scoped_refptr<RtpSenderInterface> sender) {
1243 if (!sender) {
1244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1245 }
deadbeefe1f9d832016-01-14 15:35:42 -08001246 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001247 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1248 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001249 }
Steve Antonf9381f02017-12-14 10:23:57 -08001250 if (IsUnifiedPlan()) {
1251 auto transceiver = FindTransceiverBySender(sender);
1252 if (!transceiver || !sender->track()) {
1253 return RTCError::OK();
1254 }
1255 sender->SetTrack(nullptr);
1256 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001257 transceiver->internal()->set_direction(
1258 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001259 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001260 transceiver->internal()->set_direction(
1261 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001262 }
Steve Anton4171afb2017-11-20 10:20:22 -08001263 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001264 bool removed;
1265 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1266 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1267 } else {
1268 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1269 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1270 }
1271 if (!removed) {
1272 LOG_AND_RETURN_ERROR(
1273 RTCErrorType::INVALID_PARAMETER,
1274 "Couldn't find sender " + sender->id() + " to remove.");
1275 }
Steve Anton4171afb2017-11-20 10:20:22 -08001276 }
deadbeefe1f9d832016-01-14 15:35:42 -08001277 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001278 return RTCError::OK();
1279}
1280
1281rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1282PeerConnection::FindTransceiverBySender(
1283 rtc::scoped_refptr<RtpSenderInterface> sender) {
1284 for (auto transceiver : transceivers_) {
1285 if (transceiver->sender() == sender) {
1286 return transceiver;
1287 }
1288 }
1289 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001290}
1291
Steve Anton9158ef62017-11-27 13:01:52 -08001292RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1293PeerConnection::AddTransceiver(
1294 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1295 return AddTransceiver(track, RtpTransceiverInit());
1296}
1297
1298RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1299PeerConnection::AddTransceiver(
1300 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1301 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001302 RTC_CHECK(IsUnifiedPlan())
1303 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001304 if (!track) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1306 }
1307 cricket::MediaType media_type;
1308 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1309 media_type = cricket::MEDIA_TYPE_AUDIO;
1310 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1311 media_type = cricket::MEDIA_TYPE_VIDEO;
1312 } else {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1314 "Track kind is not audio or video");
1315 }
1316 return AddTransceiver(media_type, track, init);
1317}
1318
1319RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1320PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1321 return AddTransceiver(media_type, RtpTransceiverInit());
1322}
1323
1324RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1325PeerConnection::AddTransceiver(cricket::MediaType media_type,
1326 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001327 RTC_CHECK(IsUnifiedPlan())
1328 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001329 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1330 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1331 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1332 "media type is not audio or video");
1333 }
1334 return AddTransceiver(media_type, nullptr, init);
1335}
1336
1337RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1338PeerConnection::AddTransceiver(
1339 cricket::MediaType media_type,
1340 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001341 const RtpTransceiverInit& init,
1342 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001343 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1344 media_type == cricket::MEDIA_TYPE_VIDEO));
1345 if (track) {
1346 RTC_DCHECK_EQ(media_type,
1347 (track->kind() == MediaStreamTrackInterface::kAudioKind
1348 ? cricket::MEDIA_TYPE_AUDIO
1349 : cricket::MEDIA_TYPE_VIDEO));
1350 }
1351
1352 // TODO(bugs.webrtc.org/7600): Verify init.
1353
Steve Anton02ee47c2018-01-10 16:26:06 -08001354 if (init.stream_labels.size() > 1u) {
1355 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1356 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001357 }
1358
Seth Hampson845e8782018-03-02 11:34:10 -08001359 std::vector<std::string> stream_ids = {!init.stream_labels.empty()
1360 ? init.stream_labels[0]
1361 : rtc::CreateRandomUuid()};
Steve Anton02ee47c2018-01-10 16:26:06 -08001362
Seth Hampson845e8782018-03-02 11:34:10 -08001363 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001364 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1365 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1366 transceiver->internal()->set_direction(init.direction);
1367
Steve Anton22da89f2018-01-25 13:58:07 -08001368 if (fire_callback) {
1369 observer_->OnRenegotiationNeeded();
1370 }
Steve Antonf9381f02017-12-14 10:23:57 -08001371
1372 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1373}
1374
Steve Anton02ee47c2018-01-10 16:26:06 -08001375rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1376PeerConnection::CreateSender(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001379 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001380 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1382 RTC_DCHECK(!track ||
1383 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1384 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1385 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001386 new AudioRtpSender(worker_thread(),
1387 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001388 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001389 } else {
1390 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1391 RTC_DCHECK(!track ||
1392 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1393 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1394 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001395 new VideoRtpSender(worker_thread(),
1396 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001397 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 }
Seth Hampson845e8782018-03-02 11:34:10 -08001399 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001400 return sender;
1401}
1402
1403rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1404PeerConnection::CreateReceiver(cricket::MediaType media_type,
1405 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001406 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1407 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001408 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001409 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001410 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001411 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001412 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001413 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001414 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1415 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001416 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001417 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001418 return receiver;
1419}
1420
1421rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1422PeerConnection::CreateAndAddTransceiver(
1423 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1425 receiver) {
1426 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1427 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001428 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001429 transceiver->internal()->SignalNegotiationNeeded.connect(
1430 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001431 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001432}
1433
Steve Anton52d86772018-02-20 15:48:12 -08001434void PeerConnection::OnNegotiationNeeded() {
1435 RTC_DCHECK_RUN_ON(signaling_thread());
1436 RTC_DCHECK(!IsClosed());
1437 observer_->OnRenegotiationNeeded();
1438}
1439
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001440rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001442 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001443 if (IsClosed()) {
1444 return nullptr;
1445 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001448 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001449 }
Steve Anton4171afb2017-11-20 10:20:22 -08001450 auto track_sender = FindSenderForTrack(track);
1451 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001452 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001453 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 }
1455
Steve Anton4171afb2017-11-20 10:20:22 -08001456 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457}
1458
deadbeeffac06552015-11-25 11:26:01 -08001459rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001460 const std::string& kind,
1461 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001462 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1463 "Plan SdpSemantics. Please use AddTransceiver "
1464 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001465 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001466 if (IsClosed()) {
1467 return nullptr;
1468 }
Steve Anton4171afb2017-11-20 10:20:22 -08001469
Seth Hampson845e8782018-03-02 11:34:10 -08001470 std::vector<std::string> stream_ids;
Steve Anton02ee47c2018-01-10 16:26:06 -08001471 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001472 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001473 }
1474
Steve Anton4171afb2017-11-20 10:20:22 -08001475 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001476 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001477 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001478 auto* audio_sender =
1479 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001480 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001481 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001482 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001483 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001484 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001485 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001486 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001487 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001488 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001490 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001491 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001492 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001493 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001494 }
Steve Anton4171afb2017-11-20 10:20:22 -08001495
deadbeefe1f9d832016-01-14 15:35:42 -08001496 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001497}
1498
deadbeef70ab1a12015-09-28 16:53:55 -07001499std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1500 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001501 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001502 for (auto sender : GetSendersInternal()) {
1503 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001504 }
1505 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001506}
1507
Steve Anton4171afb2017-11-20 10:20:22 -08001508std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1509PeerConnection::GetSendersInternal() const {
1510 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1511 all_senders;
1512 for (auto transceiver : transceivers_) {
1513 auto senders = transceiver->internal()->senders();
1514 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1515 }
1516 return all_senders;
1517}
1518
deadbeef70ab1a12015-09-28 16:53:55 -07001519std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1520PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001521 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001522 for (const auto& receiver : GetReceiversInternal()) {
1523 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001524 }
1525 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001526}
1527
Steve Anton4171afb2017-11-20 10:20:22 -08001528std::vector<
1529 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1530PeerConnection::GetReceiversInternal() const {
1531 std::vector<
1532 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1533 all_receivers;
1534 for (auto transceiver : transceivers_) {
1535 auto receivers = transceiver->internal()->receivers();
1536 all_receivers.insert(all_receivers.end(), receivers.begin(),
1537 receivers.end());
1538 }
1539 return all_receivers;
1540}
1541
Steve Anton9158ef62017-11-27 13:01:52 -08001542std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1543PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001544 RTC_CHECK(IsUnifiedPlan())
1545 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001546 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1547 for (auto transceiver : transceivers_) {
1548 all_transceivers.push_back(transceiver);
1549 }
1550 return all_transceivers;
1551}
1552
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001553bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001554 MediaStreamTrackInterface* track,
1555 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001556 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001557 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001558 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001559 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560 return false;
1561 }
1562
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001563 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001564 // The StatsCollector is used to tell if a track is valid because it may
1565 // remember tracks that the PeerConnection previously removed.
1566 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001567 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1568 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001569 return false;
1570 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001571 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001572 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 return true;
1574}
1575
hbos74e1a4f2016-09-15 23:33:01 -07001576void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1577 RTC_DCHECK(stats_collector_);
1578 stats_collector_->GetStatsReport(callback);
1579}
1580
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001581PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1582 return signaling_state_;
1583}
1584
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585PeerConnectionInterface::IceConnectionState
1586PeerConnection::ice_connection_state() {
1587 return ice_connection_state_;
1588}
1589
1590PeerConnectionInterface::IceGatheringState
1591PeerConnection::ice_gathering_state() {
1592 return ice_gathering_state_;
1593}
1594
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001595rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001596PeerConnection::CreateDataChannel(
1597 const std::string& label,
1598 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001599 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001600
deadbeefab9b2d12015-10-14 11:33:11 -07001601 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001602
kwibergd1fe2812016-04-27 06:47:29 -07001603 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001604 if (config) {
1605 internal_config.reset(new InternalDataChannelInit(*config));
1606 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001607 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001608 InternalCreateDataChannel(label, internal_config.get()));
1609 if (!channel.get()) {
1610 return nullptr;
1611 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001612
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001613 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1614 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001615 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001616 observer_->OnRenegotiationNeeded();
1617 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619 return DataChannelProxy::Create(signaling_thread(), channel.get());
1620}
1621
1622void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1623 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001624 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001625
zhihuang1c378ed2017-08-17 14:10:50 -07001626 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1627 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1628 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1629 // compares the mandatory fields parsed with the mandatory fields added in the
1630 // |constraints| and some downstream applications might create offers with
1631 // mandatory fields which would not be parsed in the helper method. For
1632 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1633 // |constraints| as a mandatory field but it is not parsed.
1634 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001635
zhihuang1c378ed2017-08-17 14:10:50 -07001636 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001637}
1638
1639void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1640 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001641 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001642
nisse7ce109a2017-01-31 00:57:56 -08001643 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001644 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001645 return;
1646 }
deadbeefab9b2d12015-10-14 11:33:11 -07001647
Steve Anton8d3444d2017-10-20 15:30:51 -07001648 if (IsClosed()) {
1649 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001650 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001651 PostCreateSessionDescriptionFailure(observer, error);
1652 return;
1653 }
1654
zhihuang1c378ed2017-08-17 14:10:50 -07001655 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001656 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001657 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001658 PostCreateSessionDescriptionFailure(observer, error);
1659 return;
1660 }
1661
Steve Anton22da89f2018-01-25 13:58:07 -08001662 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1663 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1664 if (IsUnifiedPlan()) {
1665 RTCError error = HandleLegacyOfferOptions(options);
1666 if (!error.ok()) {
1667 PostCreateSessionDescriptionFailure(observer, error.message());
1668 return;
1669 }
1670 }
1671
zhihuang1c378ed2017-08-17 14:10:50 -07001672 cricket::MediaSessionOptions session_options;
1673 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001674 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675}
1676
Steve Anton22da89f2018-01-25 13:58:07 -08001677RTCError PeerConnection::HandleLegacyOfferOptions(
1678 const RTCOfferAnswerOptions& options) {
1679 RTC_DCHECK(IsUnifiedPlan());
1680
1681 if (options.offer_to_receive_audio == 0) {
1682 RemoveRecvDirectionFromReceivingTransceiversOfType(
1683 cricket::MEDIA_TYPE_AUDIO);
1684 } else if (options.offer_to_receive_audio == 1) {
1685 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1686 } else if (options.offer_to_receive_audio > 1) {
1687 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1688 "offer_to_receive_audio > 1 is not supported.");
1689 }
1690
1691 if (options.offer_to_receive_video == 0) {
1692 RemoveRecvDirectionFromReceivingTransceiversOfType(
1693 cricket::MEDIA_TYPE_VIDEO);
1694 } else if (options.offer_to_receive_video == 1) {
1695 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1696 } else if (options.offer_to_receive_video > 1) {
1697 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1698 "offer_to_receive_video > 1 is not supported.");
1699 }
1700
1701 return RTCError::OK();
1702}
1703
1704void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1705 cricket::MediaType media_type) {
1706 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1707 transceiver->internal()->set_direction(
1708 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1709 }
1710}
1711
1712void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1713 cricket::MediaType media_type) {
1714 if (GetReceivingTransceiversOfType(media_type).empty()) {
1715 RtpTransceiverInit init;
1716 init.direction = RtpTransceiverDirection::kRecvOnly;
1717 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1718 }
1719}
1720
1721std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1722PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1723 std::vector<
1724 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1725 receiving_transceivers;
1726 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001727 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001728 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1729 receiving_transceivers.push_back(transceiver);
1730 }
1731 }
1732 return receiving_transceivers;
1733}
1734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001735void PeerConnection::CreateAnswer(
1736 CreateSessionDescriptionObserver* observer,
1737 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001738 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001739
nisse7ce109a2017-01-31 00:57:56 -08001740 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001741 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 return;
1743 }
deadbeefab9b2d12015-10-14 11:33:11 -07001744
zhihuang1c378ed2017-08-17 14:10:50 -07001745 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1746 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1747 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001748 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001750 PostCreateSessionDescriptionFailure(observer, error);
1751 return;
1752 }
1753
Steve Anton8d3444d2017-10-20 15:30:51 -07001754 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001755}
1756
1757void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1758 const RTCOfferAnswerOptions& options) {
1759 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001760 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001762 return;
1763 }
1764
Steve Antondffead82018-02-06 10:31:29 -08001765 if (!(signaling_state_ == kHaveRemoteOffer ||
1766 signaling_state_ == kHaveLocalPrAnswer)) {
1767 std::string error =
1768 "PeerConnection cannot create an answer in a state other than "
1769 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001770 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001771 PostCreateSessionDescriptionFailure(observer, error);
1772 return;
1773 }
1774
Steve Antondffead82018-02-06 10:31:29 -08001775 // The remote description should be set if we're in the right state.
1776 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001777
Steve Anton22da89f2018-01-25 13:58:07 -08001778 if (IsUnifiedPlan()) {
1779 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1780 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1781 "supported with Unified Plan semantics. Use the "
1782 "RtpTransceiver API instead.";
1783 }
1784 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1785 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1786 "supported with Unified Plan semantics. Use the "
1787 "RtpTransceiver API instead.";
1788 }
1789 }
1790
htaa2a49d92016-03-04 02:51:39 -08001791 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001792 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001793
Steve Antond25da372017-11-06 14:50:29 -08001794 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795}
1796
1797void PeerConnection::SetLocalDescription(
1798 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001799 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001800 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001801
Steve Anton80dd7b52018-02-16 17:08:42 -08001802 // The SetLocalDescription contract is that we take ownership of the session
1803 // description regardless of the outcome, so wrap it in a unique_ptr right
1804 // away. Ideally, SetLocalDescription's signature will be changed to take the
1805 // description as a unique_ptr argument to formalize this agreement.
1806 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1807
nisse7ce109a2017-01-31 00:57:56 -08001808 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001809 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810 return;
1811 }
Steve Anton8a006912017-12-04 15:25:56 -08001812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813 if (!desc) {
1814 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1815 return;
1816 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001817
Steve Anton80dd7b52018-02-16 17:08:42 -08001818 // If a session error has occurred the PeerConnection is in a possibly
1819 // inconsistent state so fail right away.
1820 if (session_error() != SessionError::kNone) {
1821 std::string error_message = GetSessionErrorMsg();
1822 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1823 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1824 return;
1825 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001826
Steve Anton80dd7b52018-02-16 17:08:42 -08001827 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1828 if (!error.ok()) {
1829 std::string error_message = GetSetDescriptionErrorMessage(
1830 cricket::CS_LOCAL, desc->GetType(), error);
1831 RTC_LOG(LS_ERROR) << error_message;
1832 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1833 return;
1834 }
1835
1836 // Grab the description type before moving ownership to ApplyLocalDescription,
1837 // which may destroy it before returning.
1838 const SdpType type = desc->GetType();
1839
1840 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001841 // |desc| may be destroyed at this point.
1842
1843 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001844 // If ApplyLocalDescription fails, the PeerConnection could be in an
1845 // inconsistent state, so act conservatively here and set the session error
1846 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1847 SetSessionError(SessionError::kContent, error.message());
1848 std::string error_message =
1849 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1850 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001851 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001852 return;
1853 }
Steve Anton8a006912017-12-04 15:25:56 -08001854 RTC_DCHECK(local_description());
1855
1856 PostSetSessionDescriptionSuccess(observer);
1857
1858 // According to JSEP, after setLocalDescription, changing the candidate pool
1859 // size is not allowed, and changing the set of ICE servers will not result
1860 // in new candidates being gathered.
1861 port_allocator_->FreezeCandidatePool();
1862
1863 // MaybeStartGathering needs to be called after posting
1864 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1865 // before signaling that SetLocalDescription completed.
1866 transport_controller_->MaybeStartGathering();
1867
Steve Antona3a92c22017-12-07 10:27:41 -08001868 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001869 // TODO(deadbeef): We already had to hop to the network thread for
1870 // MaybeStartGathering...
1871 network_thread()->Invoke<void>(
1872 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1873 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001874 // Make UMA notes about what was agreed to.
1875 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001876 }
1877}
1878
1879RTCError PeerConnection::ApplyLocalDescription(
1880 std::unique_ptr<SessionDescriptionInterface> desc) {
1881 RTC_DCHECK_RUN_ON(signaling_thread());
1882 RTC_DCHECK(desc);
1883
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 // Update stats here so that we have the most recent stats for tracks and
1885 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001886 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001887
1888 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001889 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001890 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001891 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001892 if (*initial_offerer_) {
1893 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1894 } else {
1895 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1896 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 }
Steve Anton8a006912017-12-04 15:25:56 -08001898
Steve Antondcc3c022017-12-22 16:02:54 -08001899 // Take a reference to the old local description since it's used below to
1900 // compare against the new local description. When setting the new local
1901 // description, grab ownership of the replaced session description in case it
1902 // is the same as |old_local_description|, to keep it alive for the duration
1903 // of the method.
1904 const SessionDescriptionInterface* old_local_description =
1905 local_description();
1906 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001907 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001908 replaced_local_description = pending_local_description_
1909 ? std::move(pending_local_description_)
1910 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001911 current_local_description_ = std::move(desc);
1912 pending_local_description_ = nullptr;
1913 current_remote_description_ = std::move(pending_remote_description_);
1914 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001915 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001916 pending_local_description_ = std::move(desc);
1917 }
1918 // The session description to apply now must be accessed by
1919 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001920 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001921
Steve Antondcc3c022017-12-22 16:02:54 -08001922 if (IsUnifiedPlan()) {
1923 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001924 cricket::CS_LOCAL, *local_description(), old_local_description,
1925 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001926 if (!error.ok()) {
1927 return error;
1928 }
Steve Antondcc3c022017-12-22 16:02:54 -08001929 for (auto transceiver : transceivers_) {
1930 const ContentInfo* content =
1931 FindMediaSectionForTransceiver(transceiver, local_description());
1932 if (!content) {
1933 continue;
1934 }
1935 const MediaContentDescription* media_desc = content->media_description();
1936 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1937 transceiver->internal()->set_current_direction(media_desc->direction());
1938 }
1939 if (content->rejected && !transceiver->stopped()) {
1940 transceiver->Stop();
1941 }
1942 }
1943 } else {
1944 // Transport and Media channels will be created only when offer is set.
1945 if (type == SdpType::kOffer) {
1946 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1947 // description is applied. Restore back to old description.
1948 RTCError error = CreateChannels(*local_description()->description());
1949 if (!error.ok()) {
1950 return error;
1951 }
1952 }
Steve Anton8a006912017-12-04 15:25:56 -08001953
Steve Antondcc3c022017-12-22 16:02:54 -08001954 // Remove unused channels if MediaContentDescription is rejected.
1955 RemoveUnusedChannels(local_description()->description());
1956 }
Steve Anton8a006912017-12-04 15:25:56 -08001957
Steve Anton80dd7b52018-02-16 17:08:42 -08001958 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001959 if (!error.ok()) {
1960 return error;
1961 }
Steve Antondcc3c022017-12-22 16:02:54 -08001962
Steve Anton8a006912017-12-04 15:25:56 -08001963 if (remote_description()) {
1964 // Now that we have a local description, we can push down remote candidates.
1965 UseCandidatesInSessionDescription(remote_description());
1966 }
1967
1968 pending_ice_restarts_.clear();
1969 if (session_error() != SessionError::kNone) {
1970 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1971 }
1972
deadbeefab9b2d12015-10-14 11:33:11 -07001973 // If setting the description decided our SSL role, allocate any necessary
1974 // SCTP sids.
1975 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001976 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001977 AllocateSctpSids(role);
1978 }
1979
Steve Antond3679212018-01-17 17:41:02 -08001980 if (IsUnifiedPlan()) {
1981 for (auto transceiver : transceivers_) {
1982 const ContentInfo* content =
1983 FindMediaSectionForTransceiver(transceiver, local_description());
1984 if (!content) {
1985 continue;
1986 }
1987 if (content->rejected && !transceiver->stopped()) {
1988 transceiver->Stop();
1989 }
Steve Anton74255ff2018-01-24 18:32:57 -08001990 const auto& streams = content->media_description()->streams();
1991 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001992 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08001993 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08001994 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001995 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001996 }
1997 }
1998 } else {
1999 // Plan B semantics.
2000
Steve Antondcc3c022017-12-22 16:02:54 -08002001 // Update state and SSRC of local MediaStreams and DataChannels based on the
2002 // local session description.
2003 const cricket::ContentInfo* audio_content =
2004 GetFirstAudioContent(local_description()->description());
2005 if (audio_content) {
2006 if (audio_content->rejected) {
2007 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2008 } else {
2009 const cricket::AudioContentDescription* audio_desc =
2010 audio_content->media_description()->as_audio();
2011 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2012 }
deadbeeffaac4972015-11-12 15:33:07 -08002013 }
deadbeefab9b2d12015-10-14 11:33:11 -07002014
Steve Antondcc3c022017-12-22 16:02:54 -08002015 const cricket::ContentInfo* video_content =
2016 GetFirstVideoContent(local_description()->description());
2017 if (video_content) {
2018 if (video_content->rejected) {
2019 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2020 } else {
2021 const cricket::VideoContentDescription* video_desc =
2022 video_content->media_description()->as_video();
2023 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2024 }
deadbeeffaac4972015-11-12 15:33:07 -08002025 }
deadbeefab9b2d12015-10-14 11:33:11 -07002026 }
2027
2028 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002029 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002030 if (data_content) {
2031 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002032 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002033 if (rtc::starts_with(data_desc->protocol().data(),
2034 cricket::kMediaProtocolRtpPrefix)) {
2035 UpdateLocalRtpDataChannels(data_desc->streams());
2036 }
2037 }
2038
Steve Anton8a006912017-12-04 15:25:56 -08002039 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040}
2041
2042void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002043 SetSessionDescriptionObserver* observer,
2044 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002045 SetRemoteDescription(
2046 std::unique_ptr<SessionDescriptionInterface>(desc),
2047 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2048 new SetRemoteDescriptionObserverAdapter(this, observer)));
2049}
2050
2051void PeerConnection::SetRemoteDescription(
2052 std::unique_ptr<SessionDescriptionInterface> desc,
2053 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002054 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002055
nisse7ce109a2017-01-31 00:57:56 -08002056 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002057 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058 return;
2059 }
Steve Anton8a006912017-12-04 15:25:56 -08002060
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002062 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002063 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064 return;
2065 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002066
Steve Anton80dd7b52018-02-16 17:08:42 -08002067 // If a session error has occurred the PeerConnection is in a possibly
2068 // inconsistent state so fail right away.
2069 if (session_error() != SessionError::kNone) {
2070 std::string error_message = GetSessionErrorMsg();
2071 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2072 observer->OnSetRemoteDescriptionComplete(
2073 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2074 return;
2075 }
Steve Anton71439a62018-02-15 11:53:06 -08002076
Steve Anton80dd7b52018-02-16 17:08:42 -08002077 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002078 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002079 std::string error_message = GetSetDescriptionErrorMessage(
2080 cricket::CS_REMOTE, desc->GetType(), error);
2081 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002082 observer->OnSetRemoteDescriptionComplete(
2083 RTCError(error.type(), std::move(error_message)));
2084 return;
2085 }
Steve Anton71439a62018-02-15 11:53:06 -08002086
Steve Anton80dd7b52018-02-16 17:08:42 -08002087 // Grab the description type before moving ownership to
2088 // ApplyRemoteDescription, which may destroy it before returning.
2089 const SdpType type = desc->GetType();
2090
2091 error = ApplyRemoteDescription(std::move(desc));
2092 // |desc| may be destroyed at this point.
2093
2094 if (!error.ok()) {
2095 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2096 // inconsistent state, so act conservatively here and set the session error
2097 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2098 SetSessionError(SessionError::kContent, error.message());
2099 std::string error_message =
2100 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2101 RTC_LOG(LS_ERROR) << error_message;
2102 observer->OnSetRemoteDescriptionComplete(
2103 RTCError(error.type(), std::move(error_message)));
2104 return;
2105 }
2106 RTC_DCHECK(remote_description());
2107
2108 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002109 // TODO(deadbeef): We already had to hop to the network thread for
2110 // MaybeStartGathering...
2111 network_thread()->Invoke<void>(
2112 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2113 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002114 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002115 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002116 }
2117
2118 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2119}
2120
2121RTCError PeerConnection::ApplyRemoteDescription(
2122 std::unique_ptr<SessionDescriptionInterface> desc) {
2123 RTC_DCHECK_RUN_ON(signaling_thread());
2124 RTC_DCHECK(desc);
2125
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 // Update stats here so that we have the most recent stats for tracks and
2127 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002128 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002129
Steve Antondcc3c022017-12-22 16:02:54 -08002130 // Take a reference to the old remote description since it's used below to
2131 // compare against the new remote description. When setting the new remote
2132 // description, grab ownership of the replaced session description in case it
2133 // is the same as |old_remote_description|, to keep it alive for the duration
2134 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002135 const SessionDescriptionInterface* old_remote_description =
2136 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002137 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002138 SdpType type = desc->GetType();
2139 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002140 replaced_remote_description = pending_remote_description_
2141 ? std::move(pending_remote_description_)
2142 : std::move(current_remote_description_);
2143 current_remote_description_ = std::move(desc);
2144 pending_remote_description_ = nullptr;
2145 current_local_description_ = std::move(pending_local_description_);
2146 } else {
2147 replaced_remote_description = std::move(pending_remote_description_);
2148 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 }
Steve Anton8a006912017-12-04 15:25:56 -08002150 // The session description to apply now must be accessed by
2151 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002152 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153
Steve Anton8a006912017-12-04 15:25:56 -08002154 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002155 if (IsUnifiedPlan()) {
2156 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002157 cricket::CS_REMOTE, *remote_description(), local_description(),
2158 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002159 if (!error.ok()) {
2160 return error;
2161 }
Steve Antondcc3c022017-12-22 16:02:54 -08002162 } else {
2163 if (type == SdpType::kOffer) {
2164 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2165 // description is applied. Restore back to old description.
2166 RTCError error = CreateChannels(*remote_description()->description());
2167 if (!error.ok()) {
2168 return error;
2169 }
2170 }
Steve Anton8a006912017-12-04 15:25:56 -08002171
Steve Antondcc3c022017-12-22 16:02:54 -08002172 // Remove unused channels if MediaContentDescription is rejected.
2173 RemoveUnusedChannels(remote_description()->description());
2174 }
Steve Anton8a006912017-12-04 15:25:56 -08002175
2176 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2177 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002178 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002179 if (!error.ok()) {
2180 return error;
2181 }
2182
2183 if (local_description() &&
2184 !UseCandidatesInSessionDescription(remote_description())) {
2185 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2186 }
2187
2188 if (old_remote_description) {
2189 for (const cricket::ContentInfo& content :
2190 old_remote_description->description()->contents()) {
2191 // Check if this new SessionDescription contains new ICE ufrag and
2192 // password that indicates the remote peer requests an ICE restart.
2193 // TODO(deadbeef): When we start storing both the current and pending
2194 // remote description, this should reset pending_ice_restarts and compare
2195 // against the current description.
2196 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2197 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002198 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002199 pending_ice_restarts_.insert(content.name);
2200 }
2201 } else {
2202 // We retain all received candidates only if ICE is not restarted.
2203 // When ICE is restarted, all previous candidates belong to an old
2204 // generation and should not be kept.
2205 // TODO(deadbeef): This goes against the W3C spec which says the remote
2206 // description should only contain candidates from the last set remote
2207 // description plus any candidates added since then. We should remove
2208 // this once we're sure it won't break anything.
2209 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2210 old_remote_description, content.name, mutable_remote_description());
2211 }
2212 }
2213 }
2214
2215 if (session_error() != SessionError::kNone) {
2216 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2217 }
2218
2219 // Set the the ICE connection state to connecting since the connection may
2220 // become writable with peer reflexive candidates before any remote candidate
2221 // is signaled.
2222 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2223 // is to have a new signal the indicates a change in checking state from the
2224 // transport and expose a new checking() member from transport that can be
2225 // read to determine the current checking state. The existing SignalConnecting
2226 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002227 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002228 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2229 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2230 }
2231
deadbeefab9b2d12015-10-14 11:33:11 -07002232 // If setting the description decided our SSL role, allocate any necessary
2233 // SCTP sids.
2234 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002235 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002236 AllocateSctpSids(role);
2237 }
2238
Steve Antondcc3c022017-12-22 16:02:54 -08002239 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002240 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2241 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002242 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002243 for (auto transceiver : transceivers_) {
2244 const ContentInfo* content =
2245 FindMediaSectionForTransceiver(transceiver, remote_description());
2246 if (!content) {
2247 continue;
2248 }
2249 const MediaContentDescription* media_desc = content->media_description();
2250 RtpTransceiverDirection local_direction =
2251 RtpTransceiverDirectionReversed(media_desc->direction());
2252 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2253 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2254 // transceiver's current direction is neither sendrecv nor recvonly,
2255 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002256 //
2257 // Create a sync label in the case of an unsignalled msid.
2258 std::string sync_label = rtc::CreateRandomUuid();
2259 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002260 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002261 if (!stream_params.stream_ids().empty()) {
2262 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002263 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002264 }
Steve Antondcc3c022017-12-22 16:02:54 -08002265 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2266 (!transceiver->current_direction() ||
2267 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002268 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002269 rtc::scoped_refptr<MediaStreamInterface> stream =
2270 remote_streams_->find(sync_label);
2271 if (!stream) {
2272 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2273 MediaStream::Create(sync_label));
2274 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002275 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002276 }
2277 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002278 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002279 }
2280 // If direction is sendonly or inactive, and transceiver's current
2281 // direction is neither sendonly nor inactive, process the removal of a
2282 // remote track for the media description.
2283 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002284 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002285 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002286 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002287 }
2288 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2289 transceiver->internal()->set_current_direction(local_direction);
2290 }
2291 if (content->rejected && !transceiver->stopped()) {
2292 transceiver->Stop();
2293 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294 if (!content->rejected &&
2295 RtpTransceiverDirectionHasRecv(local_direction)) {
2296 // Set ssrc to 0 in the case of an unsignalled ssrc.
2297 uint32_t ssrc = 0;
2298 if (!media_desc->streams().empty()) {
2299 ssrc = media_desc->streams()[0].first_ssrc();
2300 }
2301 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002302 }
Steve Antondcc3c022017-12-22 16:02:54 -08002303 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002304 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002305 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002306 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002307 observer_->OnTrack(transceiver);
2308 observer_->OnAddTrack(transceiver->receiver(),
2309 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002310 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002311 for (auto stream : added_streams) {
2312 observer_->OnAddStream(stream);
2313 }
Steve Antondcc3c022017-12-22 16:02:54 -08002314 }
2315
Henrik Boströmfdb92012017-11-09 19:55:44 +01002316 const cricket::ContentInfo* audio_content =
2317 GetFirstAudioContent(remote_description()->description());
2318 const cricket::ContentInfo* video_content =
2319 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002320 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002321 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002322 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002323 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002324 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002325 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002326
2327 // Check if the descriptions include streams, just in case the peer supports
2328 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002329 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002330 (audio_desc && !audio_desc->streams().empty()) ||
2331 (video_desc && !video_desc->streams().empty())) {
2332 remote_peer_supports_msid_ = true;
2333 }
deadbeefab9b2d12015-10-14 11:33:11 -07002334
2335 // We wait to signal new streams until we finish processing the description,
2336 // since only at that point will new streams have all their tracks.
2337 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2338
Steve Antondcc3c022017-12-22 16:02:54 -08002339 if (!IsUnifiedPlan()) {
2340 // TODO(steveanton): When removing RTP senders/receivers in response to a
2341 // rejected media section, there is some cleanup logic that expects the
2342 // voice/ video channel to still be set. But in this method the voice/video
2343 // channel would have been destroyed by the SetRemoteDescription caller
2344 // above so the cleanup that relies on them fails to run. The RemoveSenders
2345 // calls should be moved to right before the DestroyChannel calls to fix
2346 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002347
Steve Antondcc3c022017-12-22 16:02:54 -08002348 // Find all audio rtp streams and create corresponding remote AudioTracks
2349 // and MediaStreams.
2350 if (audio_content) {
2351 if (audio_content->rejected) {
2352 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2353 } else {
2354 bool default_audio_track_needed =
2355 !remote_peer_supports_msid_ &&
2356 RtpTransceiverDirectionHasSend(audio_desc->direction());
2357 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2358 default_audio_track_needed, audio_desc->type(),
2359 new_streams);
2360 }
deadbeeffaac4972015-11-12 15:33:07 -08002361 }
deadbeefab9b2d12015-10-14 11:33:11 -07002362
Steve Antondcc3c022017-12-22 16:02:54 -08002363 // Find all video rtp streams and create corresponding remote VideoTracks
2364 // and MediaStreams.
2365 if (video_content) {
2366 if (video_content->rejected) {
2367 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2368 } else {
2369 bool default_video_track_needed =
2370 !remote_peer_supports_msid_ &&
2371 RtpTransceiverDirectionHasSend(video_desc->direction());
2372 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2373 default_video_track_needed, video_desc->type(),
2374 new_streams);
2375 }
deadbeeffaac4972015-11-12 15:33:07 -08002376 }
deadbeefab9b2d12015-10-14 11:33:11 -07002377
Steve Antondcc3c022017-12-22 16:02:54 -08002378 // Update the DataChannels with the information from the remote peer.
2379 if (data_desc) {
2380 if (rtc::starts_with(data_desc->protocol().data(),
2381 cricket::kMediaProtocolRtpPrefix)) {
2382 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2383 }
deadbeefab9b2d12015-10-14 11:33:11 -07002384 }
deadbeefab9b2d12015-10-14 11:33:11 -07002385
Steve Antondcc3c022017-12-22 16:02:54 -08002386 // Iterate new_streams and notify the observer about new MediaStreams.
2387 for (size_t i = 0; i < new_streams->count(); ++i) {
2388 MediaStreamInterface* new_stream = new_streams->at(i);
2389 stats_->AddStream(new_stream);
2390 observer_->OnAddStream(
2391 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2392 }
deadbeefab9b2d12015-10-14 11:33:11 -07002393
Steve Antondcc3c022017-12-22 16:02:54 -08002394 UpdateEndedRemoteMediaStreams();
2395 }
deadbeefab9b2d12015-10-14 11:33:11 -07002396
Steve Anton8a006912017-12-04 15:25:56 -08002397 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002398}
2399
Steve Antondcc3c022017-12-22 16:02:54 -08002400RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2401 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002402 const SessionDescriptionInterface& new_session,
2403 const SessionDescriptionInterface* old_local_description,
2404 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002405 RTC_DCHECK(IsUnifiedPlan());
2406
Steve Anton7464fca2018-01-19 11:10:37 -08002407 const cricket::ContentGroup* bundle_group = nullptr;
2408 if (new_session.GetType() == SdpType::kOffer) {
2409 auto bundle_group_or_error =
2410 GetEarlyBundleGroup(*new_session.description());
2411 if (!bundle_group_or_error.ok()) {
2412 return bundle_group_or_error.MoveError();
2413 }
2414 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002415 }
Steve Antondcc3c022017-12-22 16:02:54 -08002416
Steve Antondcc3c022017-12-22 16:02:54 -08002417 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002418 for (size_t i = 0; i < new_contents.size(); ++i) {
2419 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002420 cricket::MediaType media_type = new_content.media_description()->type();
2421 seen_mids_.insert(new_content.name);
2422 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2423 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002424 const cricket::ContentInfo* old_local_content = nullptr;
2425 if (old_local_description &&
2426 i < old_local_description->description()->contents().size()) {
2427 old_local_content =
2428 &old_local_description->description()->contents()[i];
2429 }
2430 const cricket::ContentInfo* old_remote_content = nullptr;
2431 if (old_remote_description &&
2432 i < old_remote_description->description()->contents().size()) {
2433 old_remote_content =
2434 &old_remote_description->description()->contents()[i];
2435 }
Steve Antondcc3c022017-12-22 16:02:54 -08002436 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002437 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2438 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002439 if (!transceiver_or_error.ok()) {
2440 return transceiver_or_error.MoveError();
2441 }
2442 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002443 RTCError error =
2444 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2445 if (!error.ok()) {
2446 return error;
2447 }
2448 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002449 if (GetDataMid() && new_content.name != *GetDataMid()) {
2450 // Ignore all but the first data section.
2451 continue;
2452 }
2453 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2454 if (!error.ok()) {
2455 return error;
2456 }
Steve Antondcc3c022017-12-22 16:02:54 -08002457 } else {
2458 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2459 "Unknown section type.");
2460 }
2461 }
2462
2463 return RTCError::OK();
2464}
2465
2466RTCError PeerConnection::UpdateTransceiverChannel(
2467 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2468 transceiver,
2469 const cricket::ContentInfo& content,
2470 const cricket::ContentGroup* bundle_group) {
2471 RTC_DCHECK(IsUnifiedPlan());
2472 RTC_DCHECK(transceiver);
2473 cricket::BaseChannel* channel = transceiver->internal()->channel();
2474 if (content.rejected) {
2475 if (channel) {
2476 transceiver->internal()->SetChannel(nullptr);
2477 DestroyBaseChannel(channel);
2478 }
2479 } else {
2480 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002481 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002482 channel = CreateVoiceChannel(
2483 content.name,
2484 GetTransportNameForMediaSection(content.name, bundle_group));
2485 } else {
Steve Anton69470252018-02-09 11:43:08 -08002486 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002487 channel = CreateVideoChannel(
2488 content.name,
2489 GetTransportNameForMediaSection(content.name, bundle_group));
2490 }
2491 if (!channel) {
2492 LOG_AND_RETURN_ERROR(
2493 RTCErrorType::INTERNAL_ERROR,
2494 "Failed to create channel for mid=" + content.name);
2495 }
2496 transceiver->internal()->SetChannel(channel);
2497 }
2498 }
2499 return RTCError::OK();
2500}
2501
Steve Antonfa2260d2017-12-28 16:38:23 -08002502RTCError PeerConnection::UpdateDataChannel(
2503 cricket::ContentSource source,
2504 const cricket::ContentInfo& content,
2505 const cricket::ContentGroup* bundle_group) {
2506 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002507 // If data channels are disabled, ignore this media section. CreateAnswer
2508 // will take care of rejecting it.
2509 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002510 }
2511 if (content.rejected) {
2512 DestroyDataChannel();
2513 } else {
2514 if (!rtp_data_channel_ && !sctp_transport_) {
2515 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2516 content.name, bundle_group))) {
2517 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2518 "Failed to create data channel.");
2519 }
2520 }
2521 if (source == cricket::CS_REMOTE) {
2522 const MediaContentDescription* data_desc = content.media_description();
2523 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2524 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2525 }
2526 }
2527 }
2528 return RTCError::OK();
2529}
2530
Steve Antondcc3c022017-12-22 16:02:54 -08002531RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2532PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002533 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002534 size_t mline_index,
2535 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002536 const ContentInfo* old_local_content,
2537 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002538 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002539 // If this is an offer then the m= section might be recycled. If the m=
2540 // section is being recycled (defined as: rejected in the current local or
2541 // remote description and not rejected in new description), dissociate the
2542 // currently associated RtpTransceiver by setting its mid property to null,
2543 // and discard the mapping between the transceiver and its m= section index.
2544 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2545 old_remote_content)) {
2546 // We want to dissociate the transceiver that has the rejected mid.
2547 const std::string& old_mid =
2548 (old_local_content && old_local_content->rejected)
2549 ? old_local_content->name
2550 : old_remote_content->name;
2551 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002552 if (old_transceiver) {
2553 old_transceiver->internal()->set_mid(rtc::nullopt);
2554 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2555 }
2556 }
2557 const MediaContentDescription* media_desc = content.media_description();
2558 auto transceiver = GetAssociatedTransceiver(content.name);
2559 if (source == cricket::CS_LOCAL) {
2560 // Find the RtpTransceiver that corresponds to this m= section, using the
2561 // mapping between transceivers and m= section indices established when
2562 // creating the offer.
2563 if (!transceiver) {
2564 transceiver = GetTransceiverByMLineIndex(mline_index);
2565 }
2566 if (!transceiver) {
2567 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2568 "Unknown transceiver");
2569 }
2570 } else {
2571 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2572 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2573 // of the same type...
2574 if (!transceiver &&
2575 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2576 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2577 }
2578 // If no RtpTransceiver was found in the previous step, create one with a
2579 // recvonly direction.
2580 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002581 auto sender =
2582 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002583 std::string receiver_id;
2584 if (!media_desc->streams().empty()) {
2585 receiver_id = media_desc->streams()[0].id;
2586 } else {
2587 receiver_id = rtc::CreateRandomUuid();
2588 }
2589 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002590 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002591 transceiver->internal()->set_direction(
2592 RtpTransceiverDirection::kRecvOnly);
2593 }
2594 }
2595 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002596 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002597 LOG_AND_RETURN_ERROR(
2598 RTCErrorType::INVALID_PARAMETER,
2599 "Transceiver type does not match media description type.");
2600 }
2601 // Associate the found or created RtpTransceiver with the m= section by
2602 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2603 // section, and establish a mapping between the transceiver and the index of
2604 // the m= section.
2605 transceiver->internal()->set_mid(content.name);
2606 transceiver->internal()->set_mline_index(mline_index);
2607 return std::move(transceiver);
2608}
2609
2610rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2611PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2612 RTC_DCHECK(IsUnifiedPlan());
2613 for (auto transceiver : transceivers_) {
2614 if (transceiver->mid() == mid) {
2615 return transceiver;
2616 }
2617 }
2618 return nullptr;
2619}
2620
2621rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2622PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2623 RTC_DCHECK(IsUnifiedPlan());
2624 for (auto transceiver : transceivers_) {
2625 if (transceiver->internal()->mline_index() == mline_index) {
2626 return transceiver;
2627 }
2628 }
2629 return nullptr;
2630}
2631
2632rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2633PeerConnection::FindAvailableTransceiverToReceive(
2634 cricket::MediaType media_type) const {
2635 RTC_DCHECK(IsUnifiedPlan());
2636 // From JSEP section 5.10 (Applying a Remote Description):
2637 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2638 // the same type that were added to the PeerConnection by addTrack and are not
2639 // associated with any m= section and are not stopped, find the first such
2640 // RtpTransceiver.
2641 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002642 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002643 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2644 !transceiver->stopped()) {
2645 return transceiver;
2646 }
2647 }
2648 return nullptr;
2649}
2650
Steve Antoned10bd92017-12-05 10:52:59 -08002651const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2652 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2653 transceiver,
2654 const SessionDescriptionInterface* sdesc) const {
2655 RTC_DCHECK(transceiver);
2656 RTC_DCHECK(sdesc);
2657 if (IsUnifiedPlan()) {
2658 if (!transceiver->internal()->mid()) {
2659 // This transceiver is not associated with a media section yet.
2660 return nullptr;
2661 }
2662 return sdesc->description()->GetContentByName(
2663 *transceiver->internal()->mid());
2664 } else {
2665 // Plan B only allows at most one audio and one video section, so use the
2666 // first media section of that type.
2667 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002668 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002669 }
2670}
2671
deadbeef46c73892016-11-16 19:42:04 -08002672PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2673 return configuration_;
2674}
2675
deadbeef293e9262017-01-11 12:28:30 -08002676bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2677 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002678 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002679
Steve Anton75737c02017-11-06 10:37:17 -08002680 if (local_description() && configuration.ice_candidate_pool_size !=
2681 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002682 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2683 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002684 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002685 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002686
deadbeef293e9262017-01-11 12:28:30 -08002687 // The simplest (and most future-compatible) way to tell if the config was
2688 // modified in an invalid way is to copy each property we do support
2689 // modifying, then use operator==. There are far more properties we don't
2690 // support modifying than those we do, and more could be added.
2691 RTCConfiguration modified_config = configuration_;
2692 modified_config.servers = configuration.servers;
2693 modified_config.type = configuration.type;
2694 modified_config.ice_candidate_pool_size =
2695 configuration.ice_candidate_pool_size;
2696 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002697 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002698 modified_config.stun_candidate_keepalive_interval =
2699 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002700 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002701 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002702 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002703 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002704 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2705 }
2706
Steve Anton038834f2017-07-14 15:59:59 -07002707 // Validate the modified configuration.
2708 RTCError validate_error = ValidateConfiguration(modified_config);
2709 if (!validate_error.ok()) {
2710 return SafeSetError(std::move(validate_error), error);
2711 }
2712
deadbeef293e9262017-01-11 12:28:30 -08002713 // Note that this isn't possible through chromium, since it's an unsigned
2714 // short in WebIDL.
2715 if (configuration.ice_candidate_pool_size < 0 ||
2716 configuration.ice_candidate_pool_size > UINT16_MAX) {
2717 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2718 }
2719
2720 // Parse ICE servers before hopping to network thread.
2721 cricket::ServerAddresses stun_servers;
2722 std::vector<cricket::RelayServerConfig> turn_servers;
2723 RTCErrorType parse_error =
2724 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2725 if (parse_error != RTCErrorType::NONE) {
2726 return SafeSetError(parse_error, error);
2727 }
2728
2729 // In theory this shouldn't fail.
2730 if (!network_thread()->Invoke<bool>(
2731 RTC_FROM_HERE,
2732 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2733 stun_servers, turn_servers, modified_config.type,
2734 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002735 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002736 modified_config.turn_customizer,
2737 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002738 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002739 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2740 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002741
deadbeefd1a38b52016-12-10 13:15:33 -08002742 // As described in JSEP, calling setConfiguration with new ICE servers or
2743 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2744 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002745 if (modified_config.servers != configuration_.servers ||
2746 modified_config.type != configuration_.type ||
2747 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002748 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002749 }
skvladd1f5fda2017-02-03 16:54:05 -08002750
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002751 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002752
deadbeef293e9262017-01-11 12:28:30 -08002753 configuration_ = modified_config;
2754 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002755}
2756
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002757bool PeerConnection::AddIceCandidate(
2758 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002759 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002760 if (IsClosed()) {
2761 return false;
2762 }
Steve Antond25da372017-11-06 14:50:29 -08002763
2764 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002765 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002766 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002767 return false;
2768 }
2769
2770 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002771 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002772 return false;
2773 }
2774
2775 bool valid = false;
2776 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2777 if (!valid) {
2778 return false;
2779 }
2780
2781 // Add this candidate to the remote session description.
2782 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002783 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002784 return false;
2785 }
2786
2787 if (ready) {
2788 return UseCandidate(ice_candidate);
2789 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002790 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002791 return true;
2792 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793}
2794
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002795bool PeerConnection::RemoveIceCandidates(
2796 const std::vector<cricket::Candidate>& candidates) {
2797 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002798 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002799 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002800 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002801 return false;
2802 }
2803
2804 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002805 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002806 return false;
2807 }
2808
2809 size_t number_removed =
2810 mutable_remote_description()->RemoveCandidates(candidates);
2811 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002812 RTC_LOG(LS_ERROR)
2813 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002814 "Requested "
2815 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002816 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002817 }
2818
2819 // Remove the candidates from the transport controller.
2820 std::string error;
2821 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2822 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002823 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002824 }
2825 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002826}
2827
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002828void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002829 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002830 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002831
Steve Anton75737c02017-11-06 10:37:17 -08002832 if (transport_controller()) {
2833 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002834 }
2835
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002836 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002837 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002838 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002839 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002840 uma_observer_->IncrementEnumCounter(
2841 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2842 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002843 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002844 uma_observer_->IncrementEnumCounter(
2845 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2846 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002847 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002848 // Send information about the requested SDP semantics.
2849 switch (configuration_.sdp_semantics) {
2850 case SdpSemantics::kDefault:
2851 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2852 kSdpSemanticRequestDefault,
2853 kSdpSemanticRequestMax);
2854
2855 break;
2856 case SdpSemantics::kPlanB:
2857 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2858 kSdpSemanticRequestPlanB,
2859 kSdpSemanticRequestMax);
2860 break;
2861 case SdpSemantics::kUnifiedPlan:
2862 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2863 kSdpSemanticRequestUnifiedPlan,
2864 kSdpSemanticRequestMax);
2865 break;
2866 default:
2867 RTC_NOTREACHED();
2868 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002869 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002870}
2871
zstein4b979802017-06-02 14:37:37 -07002872RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002873 if (!worker_thread()->IsCurrent()) {
2874 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002875 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2876 }
2877
2878 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2879 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2880 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2881 if (has_min && *bitrate.min_bitrate_bps < 0) {
2882 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2883 "min_bitrate_bps <= 0");
2884 }
2885 if (has_current) {
2886 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2887 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2888 "current_bitrate_bps < min_bitrate_bps");
2889 } else if (*bitrate.current_bitrate_bps < 0) {
2890 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2891 "curent_bitrate_bps < 0");
2892 }
2893 }
2894 if (has_max) {
2895 if (has_current &&
2896 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2897 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2898 "max_bitrate_bps < current_bitrate_bps");
2899 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2900 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2901 "max_bitrate_bps < min_bitrate_bps");
2902 } else if (*bitrate.max_bitrate_bps < 0) {
2903 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2904 "max_bitrate_bps < 0");
2905 }
2906 }
2907
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002908 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002909 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2910 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2911 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2912
2913 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002914 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002915
2916 return RTCError::OK();
2917}
2918
Alex Narest78609d52017-10-20 10:37:47 +02002919void PeerConnection::SetBitrateAllocationStrategy(
2920 std::unique_ptr<rtc::BitrateAllocationStrategy>
2921 bitrate_allocation_strategy) {
2922 rtc::Thread* worker_thread = factory_->worker_thread();
2923 if (!worker_thread->IsCurrent()) {
2924 rtc::BitrateAllocationStrategy* strategy_raw =
2925 bitrate_allocation_strategy.release();
2926 auto functor = [this, strategy_raw]() {
2927 call_->SetBitrateAllocationStrategy(
2928 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2929 };
2930 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2931 return;
2932 }
2933 RTC_DCHECK(call_.get());
2934 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2935}
2936
henrika5f6bf242017-11-01 11:06:56 +01002937void PeerConnection::SetAudioPlayout(bool playout) {
2938 if (!worker_thread()->IsCurrent()) {
2939 worker_thread()->Invoke<void>(
2940 RTC_FROM_HERE,
2941 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2942 return;
2943 }
2944 auto audio_state =
2945 factory_->channel_manager()->media_engine()->GetAudioState();
2946 audio_state->SetPlayout(playout);
2947}
2948
2949void PeerConnection::SetAudioRecording(bool recording) {
2950 if (!worker_thread()->IsCurrent()) {
2951 worker_thread()->Invoke<void>(
2952 RTC_FROM_HERE,
2953 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2954 return;
2955 }
2956 auto audio_state =
2957 factory_->channel_manager()->media_engine()->GetAudioState();
2958 audio_state->SetRecording(recording);
2959}
2960
Steve Anton8c0f7a72017-10-03 10:03:10 -07002961std::unique_ptr<rtc::SSLCertificate>
2962PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002963 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2964 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002965 return nullptr;
2966 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002967 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002968}
2969
Zhi Huang70b820f2018-01-27 14:16:15 -08002970std::unique_ptr<rtc::SSLCertChain>
2971PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002972 auto audio_transceiver = GetFirstAudioTransceiver();
2973 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002974 return nullptr;
2975 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002976 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002977 audio_transceiver->internal()->channel()->transport_name());
2978}
2979
2980rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2981PeerConnection::GetFirstAudioTransceiver() const {
2982 for (auto transceiver : transceivers_) {
2983 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2984 return transceiver;
2985 }
2986 }
2987 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002988}
2989
ivoc14d5dbe2016-07-04 07:06:55 -07002990bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2991 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002992 // TODO(eladalon): It would be better to not allow negative values into PC.
2993 const size_t max_size = (max_size_bytes < 0)
2994 ? RtcEventLog::kUnlimitedOutput
2995 : rtc::saturated_cast<size_t>(max_size_bytes);
2996 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002997 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2998 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002999}
3000
Bjorn Tereliusde939432017-11-20 17:38:14 +01003001bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3002 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003003 // TODO(eladalon): In C++14, this can be done with a lambda.
3004 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003005 bool operator()() {
3006 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3007 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003008 PeerConnection* const pc;
3009 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003010 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003011 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003012 return worker_thread()->Invoke<bool>(
3013 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003014}
3015
3016void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003017 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003018 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3019}
3020
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003021const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003022 return pending_local_description_ ? pending_local_description_.get()
3023 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024}
3025
3026const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003027 return pending_remote_description_ ? pending_remote_description_.get()
3028 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029}
3030
deadbeeffe4a8a42016-12-20 17:56:17 -08003031const SessionDescriptionInterface* PeerConnection::current_local_description()
3032 const {
Steve Anton75737c02017-11-06 10:37:17 -08003033 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003034}
3035
3036const SessionDescriptionInterface* PeerConnection::current_remote_description()
3037 const {
Steve Anton75737c02017-11-06 10:37:17 -08003038 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003039}
3040
3041const SessionDescriptionInterface* PeerConnection::pending_local_description()
3042 const {
Steve Anton75737c02017-11-06 10:37:17 -08003043 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003044}
3045
3046const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3047 const {
Steve Anton75737c02017-11-06 10:37:17 -08003048 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003049}
3050
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003051void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003052 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053 // Update stats here so that we have the most recent stats for tracks and
3054 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003055 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056
Steve Anton75737c02017-11-06 10:37:17 -08003057 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003058
Steve Anton8af21862017-12-15 11:20:13 -08003059 for (auto transceiver : transceivers_) {
3060 transceiver->Stop();
3061 }
3062 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003063
Qingsi Wang93a84392018-01-30 17:13:09 -08003064 // The event log is used in the transport controller, which must be outlived
3065 // by the former. CreateOffer by the peer connection is implemented
3066 // asynchronously and if the peer connection is closed without resetting the
3067 // WebRTC session description factory, the session description factory would
3068 // call the transport controller.
3069 webrtc_session_desc_factory_.reset();
3070 transport_controller_.reset();
3071
deadbeef42a42632017-03-10 15:18:00 -08003072 network_thread()->Invoke<void>(
3073 RTC_FROM_HERE,
3074 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3075 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003076
Steve Anton978b8762017-09-29 12:15:02 -07003077 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003078 call_.reset();
3079 // The event log must outlive call (and any other object that uses it).
3080 event_log_.reset();
3081 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082}
3083
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003084void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3087 SetSessionDescriptionMsg* param =
3088 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3089 param->observer->OnSuccess();
3090 delete param;
3091 break;
3092 }
3093 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3094 SetSessionDescriptionMsg* param =
3095 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3096 param->observer->OnFailure(param->error);
3097 delete param;
3098 break;
3099 }
deadbeefab9b2d12015-10-14 11:33:11 -07003100 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3101 CreateSessionDescriptionMsg* param =
3102 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3103 param->observer->OnFailure(param->error);
3104 delete param;
3105 break;
3106 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 case MSG_GETSTATS: {
3108 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003109 StatsReports reports;
3110 stats_->GetStats(param->track, &reports);
3111 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112 delete param;
3113 break;
3114 }
deadbeefbd292462015-12-14 18:15:29 -08003115 case MSG_FREE_DATACHANNELS: {
3116 sctp_data_channels_to_free_.clear();
3117 break;
3118 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003120 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003121 break;
3122 }
3123}
3124
Steve Antonafb0bb72018-02-20 11:35:37 -08003125cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3126 RTC_DCHECK(!IsUnifiedPlan());
3127 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3128 GetAudioTransceiver()->internal()->channel());
3129 if (voice_channel) {
3130 return voice_channel->media_channel();
3131 } else {
3132 return nullptr;
3133 }
3134}
3135
3136cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3137 RTC_DCHECK(!IsUnifiedPlan());
3138 auto* video_channel = static_cast<cricket::VideoChannel*>(
3139 GetVideoTransceiver()->internal()->channel());
3140 if (video_channel) {
3141 return video_channel->media_channel();
3142 } else {
3143 return nullptr;
3144 }
3145}
3146
Steve Anton4171afb2017-11-20 10:20:22 -08003147void PeerConnection::CreateAudioReceiver(
3148 MediaStreamInterface* stream,
3149 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003150 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3151 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003152 auto* audio_receiver = new AudioRtpReceiver(
3153 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003154 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003155 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3156 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3157 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003158 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003159 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160}
3161
Steve Anton4171afb2017-11-20 10:20:22 -08003162void PeerConnection::CreateVideoReceiver(
3163 MediaStreamInterface* stream,
3164 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003165 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3166 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003167 auto* video_receiver = new VideoRtpReceiver(
3168 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003169 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003170 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3171 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3172 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003173 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003174 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003175}
3176
deadbeef70ab1a12015-09-28 16:53:55 -07003177// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3178// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003179rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003180 const RtpSenderInfo& remote_sender_info) {
3181 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3182 if (!receiver) {
3183 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3184 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003185 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003186 }
Steve Anton4171afb2017-11-20 10:20:22 -08003187 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3188 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3189 } else {
3190 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3191 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003192 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193}
3194
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003195void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3196 MediaStreamInterface* stream) {
3197 RTC_DCHECK(!IsClosed());
3198 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003199 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003200 // We already have a sender for this track, so just change the stream_id
3201 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003202 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003203 return;
3204 }
3205
3206 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003207 auto new_sender =
3208 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003209 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003210 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003211 // If the sender has already been configured in SDP, we call SetSsrc,
3212 // which will connect the sender to the underlying transport. This can
3213 // occur if a local session description that contains the ID of the sender
3214 // is set before AddStream is called. It can also occur if the local
3215 // session description is not changed and RemoveStream is called, and
3216 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003217 const RtpSenderInfo* sender_info =
3218 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3219 if (sender_info) {
3220 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003221 }
3222}
3223
3224// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3225// indefinitely, when we have unified plan SDP.
3226void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3227 MediaStreamInterface* stream) {
3228 RTC_DCHECK(!IsClosed());
3229 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003230 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003231 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3232 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003233 return;
3234 }
Steve Anton4171afb2017-11-20 10:20:22 -08003235 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003236}
3237
3238void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3239 MediaStreamInterface* stream) {
3240 RTC_DCHECK(!IsClosed());
3241 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003242 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003243 // We already have a sender for this track, so just change the stream_id
3244 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003245 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003246 return;
3247 }
3248
3249 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003250 auto new_sender =
3251 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003252 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003253 GetVideoTransceiver()->internal()->AddSender(new_sender);
3254 const RtpSenderInfo* sender_info =
3255 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3256 if (sender_info) {
3257 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003258 }
3259}
3260
3261void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3262 MediaStreamInterface* stream) {
3263 RTC_DCHECK(!IsClosed());
3264 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003265 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003266 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3267 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003268 return;
3269 }
Steve Anton4171afb2017-11-20 10:20:22 -08003270 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003271}
3272
Steve Antonba818672017-11-06 10:21:57 -08003273void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003274 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003275 if (ice_connection_state_ == new_state) {
3276 return;
3277 }
3278
deadbeefcbecd352015-09-23 11:50:27 -07003279 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003280 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003281 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003282 return;
3283 }
Steve Antonba818672017-11-06 10:21:57 -08003284
Mirko Bonadei675513b2017-11-09 11:09:25 +01003285 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3286 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003287 RTC_DCHECK(ice_connection_state_ !=
3288 PeerConnectionInterface::kIceConnectionClosed);
3289
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003291 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292}
3293
3294void PeerConnection::OnIceGatheringChange(
3295 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003296 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 if (IsClosed()) {
3298 return;
3299 }
3300 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003301 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302}
3303
jbauch81bf7b02017-03-25 08:31:12 -07003304void PeerConnection::OnIceCandidate(
3305 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003306 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003307 if (IsClosed()) {
3308 return;
3309 }
jbauch81bf7b02017-03-25 08:31:12 -07003310 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003311}
3312
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003313void PeerConnection::OnIceCandidatesRemoved(
3314 const std::vector<cricket::Candidate>& candidates) {
3315 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003316 if (IsClosed()) {
3317 return;
3318 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003319 observer_->OnIceCandidatesRemoved(candidates);
3320}
3321
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322void PeerConnection::ChangeSignalingState(
3323 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003324 RTC_DCHECK(signaling_thread()->IsCurrent());
3325 if (signaling_state_ == signaling_state) {
3326 return;
3327 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003328 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3329 << GetSignalingStateString(signaling_state_)
3330 << " New state: "
3331 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332 signaling_state_ = signaling_state;
3333 if (signaling_state == kClosed) {
3334 ice_connection_state_ = kIceConnectionClosed;
3335 observer_->OnIceConnectionChange(ice_connection_state_);
3336 if (ice_gathering_state_ != kIceGatheringComplete) {
3337 ice_gathering_state_ = kIceGatheringComplete;
3338 observer_->OnIceGatheringChange(ice_gathering_state_);
3339 }
3340 }
3341 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342}
3343
deadbeefeb459812015-12-15 19:24:43 -08003344void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3345 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003346 if (IsClosed()) {
3347 return;
3348 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003349 AddAudioTrack(track, stream);
3350 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003351}
3352
deadbeefeb459812015-12-15 19:24:43 -08003353void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3354 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003355 if (IsClosed()) {
3356 return;
3357 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003358 RemoveAudioTrack(track, stream);
3359 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003360}
3361
3362void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3363 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003364 if (IsClosed()) {
3365 return;
3366 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003367 AddVideoTrack(track, stream);
3368 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003369}
3370
3371void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3372 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003373 if (IsClosed()) {
3374 return;
3375 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003376 RemoveVideoTrack(track, stream);
3377 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003378}
3379
Henrik Boström31638672017-11-23 17:48:32 +01003380void PeerConnection::PostSetSessionDescriptionSuccess(
3381 SetSessionDescriptionObserver* observer) {
3382 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3383 signaling_thread()->Post(RTC_FROM_HERE, this,
3384 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3385}
3386
deadbeefab9b2d12015-10-14 11:33:11 -07003387void PeerConnection::PostSetSessionDescriptionFailure(
3388 SetSessionDescriptionObserver* observer,
3389 const std::string& error) {
3390 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3391 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003392 signaling_thread()->Post(RTC_FROM_HERE, this,
3393 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003394}
3395
3396void PeerConnection::PostCreateSessionDescriptionFailure(
3397 CreateSessionDescriptionObserver* observer,
3398 const std::string& error) {
3399 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3400 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003401 signaling_thread()->Post(RTC_FROM_HERE, this,
3402 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003403}
3404
zhihuang1c378ed2017-08-17 14:10:50 -07003405void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003406 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003407 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003408 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003409
Steve Antondcc3c022017-12-22 16:02:54 -08003410 if (IsUnifiedPlan()) {
3411 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3412 } else {
3413 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3414 }
3415
Steve Antonfa2260d2017-12-28 16:38:23 -08003416 // Intentionally unset the data channel type for RTP data channel with the
3417 // second condition. Otherwise the RTP data channels would be successfully
3418 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3419 // when building with chromium. We want to leave RTP data channels broken, so
3420 // people won't try to use them.
3421 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3422 session_options->data_channel_type = data_channel_type();
3423 }
3424
Steve Antondcc3c022017-12-22 16:02:54 -08003425 // Apply ICE restart flag and renomination flag.
3426 for (auto& options : session_options->media_description_options) {
3427 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3428 options.transport_options.enable_ice_renomination =
3429 configuration_.enable_ice_renomination;
3430 }
3431
3432 session_options->rtcp_cname = rtcp_cname_;
3433 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003434 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003435}
3436
3437void PeerConnection::GetOptionsForPlanBOffer(
3438 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3439 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003440 // Figure out transceiver directional preferences.
3441 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3442 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3443
3444 // By default, generate sendrecv/recvonly m= sections.
3445 bool recv_audio = true;
3446 bool recv_video = true;
3447
3448 // By default, only offer a new m= section if we have media to send with it.
3449 bool offer_new_audio_description = send_audio;
3450 bool offer_new_video_description = send_video;
3451 bool offer_new_data_description = HasDataChannels();
3452
3453 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003454 if (offer_answer_options.offer_to_receive_audio !=
3455 RTCOfferAnswerOptions::kUndefined) {
3456 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003457 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003458 offer_new_audio_description ||
3459 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003460 }
Steve Antondcc3c022017-12-22 16:02:54 -08003461 if (offer_answer_options.offer_to_receive_video !=
3462 RTCOfferAnswerOptions::kUndefined) {
3463 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003464 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003465 offer_new_video_description ||
3466 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003467 }
3468
3469 rtc::Optional<size_t> audio_index;
3470 rtc::Optional<size_t> video_index;
3471 rtc::Optional<size_t> data_index;
3472 // If a current description exists, generate m= sections in the same order,
3473 // using the first audio/video/data section that appears and rejecting
3474 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003475 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003476 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003477 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003478 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3479 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3480 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003481 }
3482
zhihuang1c378ed2017-08-17 14:10:50 -07003483 // Add audio/video/data m= sections to the end if needed.
3484 if (!audio_index && offer_new_audio_description) {
3485 session_options->media_description_options.push_back(
3486 cricket::MediaDescriptionOptions(
3487 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003488 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3489 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003490 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003491 }
zhihuang1c378ed2017-08-17 14:10:50 -07003492 if (!video_index && offer_new_video_description) {
3493 session_options->media_description_options.push_back(
3494 cricket::MediaDescriptionOptions(
3495 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003496 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3497 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003498 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003499 }
zhihuang1c378ed2017-08-17 14:10:50 -07003500 if (!data_index && offer_new_data_description) {
3501 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003502 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003503 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003504 }
3505
3506 cricket::MediaDescriptionOptions* audio_media_description_options =
3507 !audio_index ? nullptr
3508 : &session_options->media_description_options[*audio_index];
3509 cricket::MediaDescriptionOptions* video_media_description_options =
3510 !video_index ? nullptr
3511 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003512
Steve Anton4171afb2017-11-20 10:20:22 -08003513 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003514 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003515}
3516
3517// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3518// and return a reference to it.
3519// Generated MIDs should be no more than 3 bytes long to take up less space in
3520// the RTP packet.
3521static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3522 RTC_DCHECK(used_mids);
3523 // We're boring: just generate MIDs 0, 1, 2, ...
3524 size_t i = 0;
3525 std::set<std::string>::iterator it;
3526 bool inserted;
3527 do {
3528 std::string mid = rtc::ToString(i++);
3529 auto insert_result = used_mids->insert(mid);
3530 it = insert_result.first;
3531 inserted = insert_result.second;
3532 } while (!inserted);
3533 return *it;
3534}
3535
3536static cricket::MediaDescriptionOptions
3537GetMediaDescriptionOptionsForTransceiver(
3538 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3539 transceiver,
3540 const std::string& mid) {
3541 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003542 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003543 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003544 // This behavior is specified in JSEP. The gist is that:
3545 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3546 // sendrecv.
3547 // 2. If the MSID is included, then it must be included in any subsequent
3548 // offer/answer exactly the same until the RtpTransceiver is stopped.
3549 if (!transceiver->stopped() &&
3550 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3551 transceiver->internal()->has_ever_been_used_to_send())) {
3552 cricket::SenderOptions sender_options;
3553 sender_options.track_id = transceiver->sender()->id();
3554 sender_options.stream_ids = transceiver->sender()->stream_ids();
3555 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3556 // set in the RTP parameters when the transceiver was added.
3557 sender_options.num_sim_layers = 1;
3558 media_description_options.sender_options.push_back(sender_options);
3559 }
Steve Antondcc3c022017-12-22 16:02:54 -08003560 return media_description_options;
3561}
3562
3563void PeerConnection::GetOptionsForUnifiedPlanOffer(
3564 const RTCOfferAnswerOptions& offer_answer_options,
3565 cricket::MediaSessionOptions* session_options) {
3566 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3567 // Offers) and 5.2.2 (Subsequent Offers).
3568 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3569 const ContentInfos& local_contents =
3570 (local_description() ? local_description()->description()->contents()
3571 : ContentInfos());
3572 const ContentInfos& remote_contents =
3573 (remote_description() ? remote_description()->description()->contents()
3574 : ContentInfos());
3575 // The mline indices that can be recycled. New transceivers should reuse these
3576 // slots first.
3577 std::queue<size_t> recycleable_mline_indices;
3578 // Track the MIDs used in previous offer/answer exchanges and the current
3579 // offer so that new, unique MIDs are generated.
3580 std::set<std::string> used_mids = seen_mids_;
3581 // First, go through each media section that exists in either the local or
3582 // remote description and generate a media section in this offer for the
3583 // associated transceiver. If a media section can be recycled, generate a
3584 // default, rejected media section here that can be later overwritten.
3585 for (size_t i = 0;
3586 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3587 // Either |local_content| or |remote_content| is non-null.
3588 const ContentInfo* local_content =
3589 (i < local_contents.size() ? &local_contents[i] : nullptr);
3590 const ContentInfo* remote_content =
3591 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3592 bool had_been_rejected = (local_content && local_content->rejected) ||
3593 (remote_content && remote_content->rejected);
3594 const std::string& mid =
3595 (local_content ? local_content->name : remote_content->name);
3596 cricket::MediaType media_type =
3597 (local_content ? local_content->media_description()->type()
3598 : remote_content->media_description()->type());
3599 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3600 media_type == cricket::MEDIA_TYPE_VIDEO) {
3601 auto transceiver = GetAssociatedTransceiver(mid);
3602 RTC_CHECK(transceiver);
3603 // A media section is considered eligible for recycling if it is marked as
3604 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003605 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003606 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003607 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3608 RtpTransceiverDirection::kInactive,
3609 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003610 recycleable_mline_indices.push(i);
3611 } else {
3612 session_options->media_description_options.push_back(
3613 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3614 // CreateOffer shouldn't really cause any state changes in
3615 // PeerConnection, but we need a way to match new transceivers to new
3616 // media sections in SetLocalDescription and JSEP specifies this is done
3617 // by recording the index of the media section generated for the
3618 // transceiver in the offer.
3619 transceiver->internal()->set_mline_index(i);
3620 }
3621 } else {
3622 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003623 RTC_CHECK(GetDataMid());
3624 if (had_been_rejected || mid != *GetDataMid()) {
3625 session_options->media_description_options.push_back(
3626 GetMediaDescriptionOptionsForRejectedData(mid));
3627 } else {
3628 session_options->media_description_options.push_back(
3629 GetMediaDescriptionOptionsForActiveData(mid));
3630 }
Steve Antondcc3c022017-12-22 16:02:54 -08003631 }
3632 }
3633 // Next, look for transceivers that are newly added (that is, are not stopped
3634 // and not associated). Reuse media sections marked as recyclable first,
3635 // otherwise append to the end of the offer. New media sections should be
3636 // added in the order they were added to the PeerConnection.
3637 for (auto transceiver : transceivers_) {
3638 if (transceiver->mid() || transceiver->stopped()) {
3639 continue;
3640 }
3641 size_t mline_index;
3642 if (!recycleable_mline_indices.empty()) {
3643 mline_index = recycleable_mline_indices.front();
3644 recycleable_mline_indices.pop();
3645 session_options->media_description_options[mline_index] =
3646 GetMediaDescriptionOptionsForTransceiver(transceiver,
3647 AllocateMid(&used_mids));
3648 } else {
3649 mline_index = session_options->media_description_options.size();
3650 session_options->media_description_options.push_back(
3651 GetMediaDescriptionOptionsForTransceiver(transceiver,
3652 AllocateMid(&used_mids)));
3653 }
3654 // See comment above for why CreateOffer changes the transceiver's state.
3655 transceiver->internal()->set_mline_index(mline_index);
3656 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003657 // Lastly, add a m-section if we have local data channels and an m section
3658 // does not already exist.
3659 if (!GetDataMid() && HasDataChannels()) {
3660 session_options->media_description_options.push_back(
3661 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3662 }
Steve Antondcc3c022017-12-22 16:02:54 -08003663}
3664
3665void PeerConnection::GetOptionsForAnswer(
3666 const RTCOfferAnswerOptions& offer_answer_options,
3667 cricket::MediaSessionOptions* session_options) {
3668 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3669
3670 if (IsUnifiedPlan()) {
3671 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3672 } else {
3673 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3674 }
3675
Steve Antonfa2260d2017-12-28 16:38:23 -08003676 // Intentionally unset the data channel type for RTP data channel. Otherwise
3677 // the RTP data channels would be successfully negotiated by default and the
3678 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3679 // We want to leave RTP data channels broken, so people won't try to use them.
3680 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3681 session_options->data_channel_type = data_channel_type();
3682 }
3683
Steve Antondcc3c022017-12-22 16:02:54 -08003684 // Apply ICE renomination flag.
3685 for (auto& options : session_options->media_description_options) {
3686 options.transport_options.enable_ice_renomination =
3687 configuration_.enable_ice_renomination;
3688 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003689
3690 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003691 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003692 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003693}
3694
Steve Antondcc3c022017-12-22 16:02:54 -08003695void PeerConnection::GetOptionsForPlanBAnswer(
3696 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003697 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003698 // Figure out transceiver directional preferences.
3699 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3700 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3701
3702 // By default, generate sendrecv/recvonly m= sections. The direction is also
3703 // restricted by the direction in the offer.
3704 bool recv_audio = true;
3705 bool recv_video = true;
3706
3707 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003708 if (offer_answer_options.offer_to_receive_audio !=
3709 RTCOfferAnswerOptions::kUndefined) {
3710 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003711 }
Steve Antondcc3c022017-12-22 16:02:54 -08003712 if (offer_answer_options.offer_to_receive_video !=
3713 RTCOfferAnswerOptions::kUndefined) {
3714 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003715 }
3716
3717 rtc::Optional<size_t> audio_index;
3718 rtc::Optional<size_t> video_index;
3719 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003720
3721 // Generate m= sections that match those in the offer.
3722 // Note that mediasession.cc will handle intersection our preferred
3723 // direction with the offered direction.
3724 GenerateMediaDescriptionOptions(
3725 remote_description(),
3726 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3727 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3728 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003729
3730 cricket::MediaDescriptionOptions* audio_media_description_options =
3731 !audio_index ? nullptr
3732 : &session_options->media_description_options[*audio_index];
3733 cricket::MediaDescriptionOptions* video_media_description_options =
3734 !video_index ? nullptr
3735 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003736
Steve Anton4171afb2017-11-20 10:20:22 -08003737 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003738 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003739}
zhihuangaf388472016-11-02 16:49:48 -07003740
Steve Antondcc3c022017-12-22 16:02:54 -08003741void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3742 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3743 cricket::MediaSessionOptions* session_options) {
3744 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3745 // Answers) and 5.3.2 (Subsequent Answers).
3746 RTC_DCHECK(remote_description());
3747 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3748 for (const ContentInfo& content :
3749 remote_description()->description()->contents()) {
3750 cricket::MediaType media_type = content.media_description()->type();
3751 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3752 media_type == cricket::MEDIA_TYPE_VIDEO) {
3753 auto transceiver = GetAssociatedTransceiver(content.name);
3754 RTC_CHECK(transceiver);
3755 session_options->media_description_options.push_back(
3756 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3757 } else {
3758 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003759 // Reject all data sections if data channels are disabled.
3760 // Reject a data section if it has already been rejected.
3761 // Reject all data sections except for the first one.
3762 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3763 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003764 session_options->media_description_options.push_back(
3765 GetMediaDescriptionOptionsForRejectedData(content.name));
3766 } else {
3767 session_options->media_description_options.push_back(
3768 GetMediaDescriptionOptionsForActiveData(content.name));
3769 }
Steve Antondcc3c022017-12-22 16:02:54 -08003770 }
3771 }
htaa2a49d92016-03-04 02:51:39 -08003772}
3773
zhihuang1c378ed2017-08-17 14:10:50 -07003774void PeerConnection::GenerateMediaDescriptionOptions(
3775 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003776 RtpTransceiverDirection audio_direction,
3777 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003778 rtc::Optional<size_t>* audio_index,
3779 rtc::Optional<size_t>* video_index,
3780 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003781 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003782 for (const cricket::ContentInfo& content :
3783 session_desc->description()->contents()) {
3784 if (IsAudioContent(&content)) {
3785 // If we already have an audio m= section, reject this extra one.
3786 if (*audio_index) {
3787 session_options->media_description_options.push_back(
3788 cricket::MediaDescriptionOptions(
3789 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003790 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003791 } else {
3792 session_options->media_description_options.push_back(
3793 cricket::MediaDescriptionOptions(
3794 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003795 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003796 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003797 }
3798 } else if (IsVideoContent(&content)) {
3799 // If we already have an video m= section, reject this extra one.
3800 if (*video_index) {
3801 session_options->media_description_options.push_back(
3802 cricket::MediaDescriptionOptions(
3803 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003804 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003805 } else {
3806 session_options->media_description_options.push_back(
3807 cricket::MediaDescriptionOptions(
3808 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003809 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003810 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003811 }
3812 } else {
3813 RTC_DCHECK(IsDataContent(&content));
3814 // If we already have an data m= section, reject this extra one.
3815 if (*data_index) {
3816 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003817 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003818 } else {
3819 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003820 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003821 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003822 }
3823 }
htaa2a49d92016-03-04 02:51:39 -08003824 }
deadbeefab9b2d12015-10-14 11:33:11 -07003825}
3826
Steve Antonfa2260d2017-12-28 16:38:23 -08003827cricket::MediaDescriptionOptions
3828PeerConnection::GetMediaDescriptionOptionsForActiveData(
3829 const std::string& mid) const {
3830 // Direction for data sections is meaningless, but legacy endpoints might
3831 // expect sendrecv.
3832 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3833 RtpTransceiverDirection::kSendRecv,
3834 /*stopped=*/false);
3835 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3836 return options;
3837}
3838
3839cricket::MediaDescriptionOptions
3840PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3841 const std::string& mid) const {
3842 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3843 RtpTransceiverDirection::kInactive,
3844 /*stopped=*/true);
3845 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3846 return options;
3847}
3848
3849rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3850 switch (data_channel_type_) {
3851 case cricket::DCT_RTP:
3852 if (!rtp_data_channel_) {
3853 return rtc::nullopt;
3854 }
3855 return rtp_data_channel_->content_name();
3856 case cricket::DCT_SCTP:
3857 return sctp_content_name_;
3858 default:
3859 return rtc::nullopt;
3860 }
3861}
3862
Steve Anton4171afb2017-11-20 10:20:22 -08003863void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3864 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3865 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003866 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003867}
3868
Steve Anton4171afb2017-11-20 10:20:22 -08003869void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003870 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003871 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003872 cricket::MediaType media_type,
3873 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003874 std::vector<RtpSenderInfo>* current_senders =
3875 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003876
Steve Anton4171afb2017-11-20 10:20:22 -08003877 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003878 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003879 for (auto sender_it = current_senders->begin();
3880 sender_it != current_senders->end();
3881 /* incremented manually */) {
3882 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003883 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003884 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3885 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003886 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003887 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003888 sender_exists) {
3889 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003890 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003891 OnRemoteSenderRemoved(info, media_type);
3892 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003893 }
3894 }
3895
Steve Anton4171afb2017-11-20 10:20:22 -08003896 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003897 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08003898 // |params.id| is the sender id and the stream id uses the first of
3899 // |params.stream_ids|.
3900 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
3901 const std::string& stream_id =
3902 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003903 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003904 uint32_t ssrc = params.first_ssrc();
3905
3906 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003907 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003908 if (!stream) {
3909 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003910 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08003911 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07003912 remote_streams_->AddStream(stream);
3913 new_streams->AddStream(stream);
3914 }
3915
Steve Anton4171afb2017-11-20 10:20:22 -08003916 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08003917 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003918 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08003919 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08003920 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003921 }
3922 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003923
Steve Anton4171afb2017-11-20 10:20:22 -08003924 // Add default sender if necessary.
3925 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003926 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003927 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08003928 if (!default_stream) {
3929 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003930 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08003931 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08003932 remote_streams_->AddStream(default_stream);
3933 new_streams->AddStream(default_stream);
3934 }
Steve Anton4171afb2017-11-20 10:20:22 -08003935 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3936 ? kDefaultAudioSenderId
3937 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08003938 const RtpSenderInfo* default_sender_info =
3939 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003940 if (!default_sender_info) {
3941 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08003942 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08003943 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003944 }
3945 }
deadbeefab9b2d12015-10-14 11:33:11 -07003946}
3947
Steve Anton4171afb2017-11-20 10:20:22 -08003948void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3949 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003950 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003951
3952 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003953 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003954 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003955 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003956 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003957 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003958 }
3959}
3960
Steve Anton4171afb2017-11-20 10:20:22 -08003961void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3962 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003963 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003964
Henrik Boström933d8b02017-10-10 10:05:16 -07003965 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003966 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003967 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3968 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003969 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003970 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003971 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003972 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003973 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003974 }
3975 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003976 // Stopping or destroying a VideoRtpReceiver will end the
3977 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003978 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003979 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003980 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003981 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003982 // There's no guarantee the track is still available, e.g. the track may
3983 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003984 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003985 }
3986 } else {
nisseede5da42017-01-12 05:15:36 -08003987 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003988 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003989 if (receiver) {
3990 observer_->OnRemoveTrack(receiver);
3991 }
deadbeefab9b2d12015-10-14 11:33:11 -07003992}
3993
3994void PeerConnection::UpdateEndedRemoteMediaStreams() {
3995 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3996 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3997 MediaStreamInterface* stream = remote_streams_->at(i);
3998 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3999 streams_to_remove.push_back(stream);
4000 }
4001 }
4002
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004003 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004004 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004005 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004006 }
4007}
4008
Steve Anton4171afb2017-11-20 10:20:22 -08004009void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004010 const std::vector<cricket::StreamParams>& streams,
4011 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004012 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004013
Seth Hampson845e8782018-03-02 11:34:10 -08004014 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004015 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004016 for (auto sender_it = current_senders->begin();
4017 sender_it != current_senders->end();
4018 /* incremented manually */) {
4019 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004020 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004021 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4022 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004023 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004024 OnLocalSenderRemoved(info, media_type);
4025 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004026 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004027 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004028 }
4029 }
4030
Steve Anton4171afb2017-11-20 10:20:22 -08004031 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004032 for (const cricket::StreamParams& params : streams) {
4033 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004034 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004035 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004036 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004037 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004038 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08004039 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004040 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004041 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004042 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004043 }
4044 }
4045}
4046
Steve Anton4171afb2017-11-20 10:20:22 -08004047void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4048 cricket::MediaType media_type) {
4049 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004050 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004051 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4052 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004053 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004054 return;
4055 }
4056
deadbeeffac06552015-11-25 11:26:01 -08004057 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004058 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004059 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004060 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004061 }
deadbeeffac06552015-11-25 11:26:01 -08004062
Seth Hampson845e8782018-03-02 11:34:10 -08004063 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004064 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004065}
4066
Steve Anton4171afb2017-11-20 10:20:22 -08004067void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4068 cricket::MediaType media_type) {
4069 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004070 if (!sender) {
4071 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004072 // SessionDescriptions has been renegotiated.
4073 return;
4074 }
deadbeeffac06552015-11-25 11:26:01 -08004075
4076 // A sender has been removed from the SessionDescription but it's still
4077 // associated with the PeerConnection. This only occurs if the SDP doesn't
4078 // match with the calls to CreateSender, AddStream and RemoveStream.
4079 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004080 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004081 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004082 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004083 }
deadbeeffac06552015-11-25 11:26:01 -08004084
Steve Anton4171afb2017-11-20 10:20:22 -08004085 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004086}
4087
4088void PeerConnection::UpdateLocalRtpDataChannels(
4089 const cricket::StreamParamsVec& streams) {
4090 std::vector<std::string> existing_channels;
4091
4092 // Find new and active data channels.
4093 for (const cricket::StreamParams& params : streams) {
4094 // |it->sync_label| is actually the data channel label. The reason is that
4095 // we use the same naming of data channels as we do for
4096 // MediaStreams and Tracks.
4097 // For MediaStreams, the sync_label is the MediaStream label and the
4098 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004099 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004100 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004101 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004102 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004103 continue;
4104 }
4105 // Set the SSRC the data channel should use for sending.
4106 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4107 existing_channels.push_back(data_channel_it->first);
4108 }
4109
4110 UpdateClosingRtpDataChannels(existing_channels, true);
4111}
4112
4113void PeerConnection::UpdateRemoteRtpDataChannels(
4114 const cricket::StreamParamsVec& streams) {
4115 std::vector<std::string> existing_channels;
4116
4117 // Find new and active data channels.
4118 for (const cricket::StreamParams& params : streams) {
4119 // The data channel label is either the mslabel or the SSRC if the mslabel
4120 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004121 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004122 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004123 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004124 auto data_channel_it = rtp_data_channels_.find(label);
4125 if (data_channel_it == rtp_data_channels_.end()) {
4126 // This is a new data channel.
4127 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4128 } else {
4129 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4130 }
4131 existing_channels.push_back(label);
4132 }
4133
4134 UpdateClosingRtpDataChannels(existing_channels, false);
4135}
4136
4137void PeerConnection::UpdateClosingRtpDataChannels(
4138 const std::vector<std::string>& active_channels,
4139 bool is_local_update) {
4140 auto it = rtp_data_channels_.begin();
4141 while (it != rtp_data_channels_.end()) {
4142 DataChannel* data_channel = it->second;
4143 if (std::find(active_channels.begin(), active_channels.end(),
4144 data_channel->label()) != active_channels.end()) {
4145 ++it;
4146 continue;
4147 }
4148
4149 if (is_local_update) {
4150 data_channel->SetSendSsrc(0);
4151 } else {
4152 data_channel->RemotePeerRequestClose();
4153 }
4154
4155 if (data_channel->state() == DataChannel::kClosed) {
4156 rtp_data_channels_.erase(it);
4157 it = rtp_data_channels_.begin();
4158 } else {
4159 ++it;
4160 }
4161 }
4162}
4163
4164void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4165 uint32_t remote_ssrc) {
4166 rtc::scoped_refptr<DataChannel> channel(
4167 InternalCreateDataChannel(label, nullptr));
4168 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004169 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004170 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004171 return;
4172 }
4173 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004174 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4175 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004176 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004177}
4178
4179rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4180 const std::string& label,
4181 const InternalDataChannelInit* config) {
4182 if (IsClosed()) {
4183 return nullptr;
4184 }
Steve Anton75737c02017-11-06 10:37:17 -08004185 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004186 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004187 << "InternalCreateDataChannel: Data is not supported in this call.";
4188 return nullptr;
4189 }
4190 InternalDataChannelInit new_config =
4191 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004192 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004193 if (new_config.id < 0) {
4194 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004195 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004196 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_ERROR)
4198 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004199 return nullptr;
4200 }
4201 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004202 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004203 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004204 return nullptr;
4205 }
4206 }
4207
Steve Anton75737c02017-11-06 10:37:17 -08004208 rtc::scoped_refptr<DataChannel> channel(
4209 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004210 if (!channel) {
4211 sid_allocator_.ReleaseSid(new_config.id);
4212 return nullptr;
4213 }
4214
4215 if (channel->data_channel_type() == cricket::DCT_RTP) {
4216 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004217 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4218 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004219 return nullptr;
4220 }
4221 rtp_data_channels_[channel->label()] = channel;
4222 } else {
4223 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4224 sctp_data_channels_.push_back(channel);
4225 channel->SignalClosed.connect(this,
4226 &PeerConnection::OnSctpDataChannelClosed);
4227 }
4228
Steve Anton2d8609c2018-01-23 16:38:46 -08004229 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004230 return channel;
4231}
4232
4233bool PeerConnection::HasDataChannels() const {
4234 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4235}
4236
4237void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4238 for (const auto& channel : sctp_data_channels_) {
4239 if (channel->id() < 0) {
4240 int sid;
4241 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004242 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004243 continue;
4244 }
4245 channel->SetSctpSid(sid);
4246 }
4247 }
4248}
4249
4250void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004251 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004252 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4253 ++it) {
4254 if (it->get() == channel) {
4255 if (channel->id() >= 0) {
4256 sid_allocator_.ReleaseSid(channel->id());
4257 }
deadbeefbd292462015-12-14 18:15:29 -08004258 // Since this method is triggered by a signal from the DataChannel,
4259 // we can't free it directly here; we need to free it asynchronously.
4260 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004261 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004262 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4263 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004264 return;
4265 }
4266 }
4267}
4268
deadbeefab9b2d12015-10-14 11:33:11 -07004269void PeerConnection::OnDataChannelDestroyed() {
4270 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4271 // DataChannel may callback to us and try to modify the list.
4272 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4273 temp_rtp_dcs.swap(rtp_data_channels_);
4274 for (const auto& kv : temp_rtp_dcs) {
4275 kv.second->OnTransportChannelDestroyed();
4276 }
4277
4278 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4279 temp_sctp_dcs.swap(sctp_data_channels_);
4280 for (const auto& channel : temp_sctp_dcs) {
4281 channel->OnTransportChannelDestroyed();
4282 }
4283}
4284
4285void PeerConnection::OnDataChannelOpenMessage(
4286 const std::string& label,
4287 const InternalDataChannelInit& config) {
4288 rtc::scoped_refptr<DataChannel> channel(
4289 InternalCreateDataChannel(label, &config));
4290 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004291 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004292 return;
4293 }
4294
deadbeefa601f5c2016-06-06 14:27:39 -07004295 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4296 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004297 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004298}
4299
Steve Anton4171afb2017-11-20 10:20:22 -08004300rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4301PeerConnection::GetAudioTransceiver() const {
4302 // This method only works with Plan B SDP, where there is a single
4303 // audio/video transceiver.
4304 RTC_DCHECK(!IsUnifiedPlan());
4305 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004306 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004307 return transceiver;
4308 }
4309 }
4310 RTC_NOTREACHED();
4311 return nullptr;
4312}
4313
4314rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4315PeerConnection::GetVideoTransceiver() const {
4316 // This method only works with Plan B SDP, where there is a single
4317 // audio/video transceiver.
4318 RTC_DCHECK(!IsUnifiedPlan());
4319 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004320 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004321 return transceiver;
4322 }
4323 }
4324 RTC_NOTREACHED();
4325 return nullptr;
4326}
4327
4328// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4329// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004330bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004331 switch (type) {
4332 case cricket::MEDIA_TYPE_AUDIO:
4333 return !GetAudioTransceiver()->internal()->senders().empty();
4334 case cricket::MEDIA_TYPE_VIDEO:
4335 return !GetVideoTransceiver()->internal()->senders().empty();
4336 case cricket::MEDIA_TYPE_DATA:
4337 return false;
4338 }
4339 RTC_NOTREACHED();
4340 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004341}
4342
Steve Anton4171afb2017-11-20 10:20:22 -08004343rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4344PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4345 for (auto transceiver : transceivers_) {
4346 for (auto sender : transceiver->internal()->senders()) {
4347 if (sender->track() == track) {
4348 return sender;
4349 }
4350 }
4351 }
4352 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004353}
4354
Steve Anton4171afb2017-11-20 10:20:22 -08004355rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4356PeerConnection::FindSenderById(const std::string& sender_id) const {
4357 for (auto transceiver : transceivers_) {
4358 for (auto sender : transceiver->internal()->senders()) {
4359 if (sender->id() == sender_id) {
4360 return sender;
4361 }
4362 }
4363 }
4364 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004365}
4366
Steve Anton4171afb2017-11-20 10:20:22 -08004367rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4368PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4369 for (auto transceiver : transceivers_) {
4370 for (auto receiver : transceiver->internal()->receivers()) {
4371 if (receiver->id() == receiver_id) {
4372 return receiver;
4373 }
4374 }
4375 }
4376 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004377}
4378
Steve Anton4171afb2017-11-20 10:20:22 -08004379std::vector<PeerConnection::RtpSenderInfo>*
4380PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4381 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4382 media_type == cricket::MEDIA_TYPE_VIDEO);
4383 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4384 ? &remote_audio_sender_infos_
4385 : &remote_video_sender_infos_;
4386}
4387
4388std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004389 cricket::MediaType media_type) {
4390 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4391 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004392 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4393 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004394}
4395
Steve Anton4171afb2017-11-20 10:20:22 -08004396const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4397 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Seth Hampson845e8782018-03-02 11:34:10 -08004398 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004399 const std::string sender_id) const {
4400 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson845e8782018-03-02 11:34:10 -08004401 if (sender_info.stream_id == stream_id &&
Steve Anton4171afb2017-11-20 10:20:22 -08004402 sender_info.sender_id == sender_id) {
4403 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004404 }
4405 }
4406 return nullptr;
4407}
4408
4409DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4410 for (const auto& channel : sctp_data_channels_) {
4411 if (channel->id() == sid) {
4412 return channel;
4413 }
4414 }
4415 return nullptr;
4416}
4417
deadbeef91dd5672016-05-18 16:55:30 -07004418bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004419 const RTCConfiguration& configuration) {
4420 cricket::ServerAddresses stun_servers;
4421 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004422 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4423 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004424 return false;
4425 }
4426
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004427 port_allocator_->Initialize();
4428
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004429 // To handle both internal and externally created port allocator, we will
4430 // enable BUNDLE here.
4431 int portallocator_flags = port_allocator_->flags();
4432 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004433 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4434 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004435 // If the disable-IPv6 flag was specified, we'll not override it
4436 // by experiment.
4437 if (configuration.disable_ipv6) {
4438 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004439 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4440 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004441 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4442 }
4443
zhihuangb09b3f92017-03-07 14:40:51 -08004444 if (configuration.disable_ipv6_on_wifi) {
4445 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004446 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004447 }
4448
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004449 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4450 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004451 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004452 }
4453
honghaiz60347052016-05-31 18:29:12 -07004454 if (configuration.candidate_network_policy ==
4455 kCandidateNetworkPolicyLowCost) {
4456 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004457 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004458 }
4459
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004460 if (configuration.disable_link_local_networks) {
4461 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4462 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4463 }
4464
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004465 port_allocator_->set_flags(portallocator_flags);
4466 // No step delay is used while allocating ports.
4467 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4468 port_allocator_->set_candidate_filter(
4469 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004470 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004471
4472 // Call this last since it may create pooled allocator sessions using the
4473 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004474 port_allocator_->SetConfiguration(
4475 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4476 configuration.prune_turn_ports, configuration.turn_customizer,
4477 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004478 return true;
4479}
4480
deadbeef91dd5672016-05-18 16:55:30 -07004481bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004482 const cricket::ServerAddresses& stun_servers,
4483 const std::vector<cricket::RelayServerConfig>& turn_servers,
4484 IceTransportsType type,
4485 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004486 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004487 webrtc::TurnCustomizer* turn_customizer,
4488 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004489 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004490 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004491 // Call this last since it may create pooled allocator sessions using the
4492 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004493 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004494 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004495 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004496}
4497
Steve Antonba818672017-11-06 10:21:57 -08004498cricket::ChannelManager* PeerConnection::channel_manager() const {
4499 return factory_->channel_manager();
4500}
4501
4502MetricsObserverInterface* PeerConnection::metrics_observer() const {
4503 return uma_observer_;
4504}
4505
Elad Alon99c3fe52017-10-13 16:29:40 +02004506bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004507 std::unique_ptr<RtcEventLogOutput> output,
4508 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004509 if (!event_log_) {
4510 return false;
4511 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004512 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004513}
4514
4515void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004516 if (event_log_) {
4517 event_log_->StopLogging();
4518 }
ivoc14d5dbe2016-07-04 07:06:55 -07004519}
nisseeaabdf62017-05-05 02:23:02 -07004520
Steve Anton75737c02017-11-06 10:37:17 -08004521cricket::BaseChannel* PeerConnection::GetChannel(
4522 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004523 for (auto transceiver : transceivers_) {
4524 cricket::BaseChannel* channel = transceiver->internal()->channel();
4525 if (channel && channel->content_name() == content_name) {
4526 return channel;
4527 }
Steve Anton75737c02017-11-06 10:37:17 -08004528 }
4529 if (rtp_data_channel() &&
4530 rtp_data_channel()->content_name() == content_name) {
4531 return rtp_data_channel();
4532 }
4533 return nullptr;
4534}
4535
4536bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4537 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004538 RTC_LOG(LS_INFO)
4539 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004540 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004541 return false;
4542 }
4543 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004544 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004545 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004546 return false;
4547 }
4548
4549 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4550}
4551
4552bool PeerConnection::GetSslRole(const std::string& content_name,
4553 rtc::SSLRole* role) {
4554 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004555 RTC_LOG(LS_INFO)
4556 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004557 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004558 return false;
4559 }
4560
4561 return transport_controller_->GetSslRole(GetTransportName(content_name),
4562 role);
4563}
4564
Steve Antonf8470812017-12-04 10:46:21 -08004565void PeerConnection::SetSessionError(SessionError error,
4566 const std::string& error_desc) {
4567 RTC_DCHECK_RUN_ON(signaling_thread());
4568 if (error != session_error_) {
4569 session_error_ = error;
4570 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004571 }
4572}
4573
Steve Anton3828c062017-12-06 10:34:51 -08004574RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004575 cricket::ContentSource source) {
4576 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004577
4578 // If there's already a pending error then no state transition should happen.
4579 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004580 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004581
4582 // If this is an answer then we know whether to BUNDLE or not. If both the
4583 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004584 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004585 const cricket::ContentGroup* local_bundle =
4586 local_description()->description()->GetGroupByName(
4587 cricket::GROUP_TYPE_BUNDLE);
4588 const cricket::ContentGroup* remote_bundle =
4589 remote_description()->description()->GetGroupByName(
4590 cricket::GROUP_TYPE_BUNDLE);
4591 if (local_bundle && remote_bundle) {
4592 // The answerer decides the transport to bundle on.
4593 const cricket::ContentGroup* answer_bundle =
4594 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4595 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004596 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4597 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004598 }
4599 }
Steve Anton75737c02017-11-06 10:37:17 -08004600 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004601
4602 // Only push down the transport description after potentially enabling BUNDLE;
4603 // we don't want to push down a description on a transport about to be
4604 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004605 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004606 if (!error.ok()) {
4607 return error;
4608 }
4609
4610 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004611 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004612 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004613 }
4614
4615 // Update the signaling state according to the specified state machine (see
4616 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004617 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004618 ChangeSignalingState(source == cricket::CS_LOCAL
4619 ? PeerConnectionInterface::kHaveLocalOffer
4620 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004621 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004622 ChangeSignalingState(source == cricket::CS_LOCAL
4623 ? PeerConnectionInterface::kHaveLocalPrAnswer
4624 : PeerConnectionInterface::kHaveRemotePrAnswer);
4625 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004626 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004627 ChangeSignalingState(PeerConnectionInterface::kStable);
4628 }
4629
4630 // Update internal objects according to the session description's media
4631 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004632 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004633 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004634 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004635 }
4636
Steve Anton8a006912017-12-04 15:25:56 -08004637 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004638}
4639
Steve Anton8a006912017-12-04 15:25:56 -08004640RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004641 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004642 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004643 const SessionDescriptionInterface* sdesc =
4644 (source == cricket::CS_LOCAL ? local_description()
4645 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004646 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004647
4648 // Push down the new SDP media section for each audio/video transceiver.
4649 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004650 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004651 FindMediaSectionForTransceiver(transceiver, sdesc);
4652 cricket::BaseChannel* channel = transceiver->internal()->channel();
4653 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004654 continue;
4655 }
4656 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004657 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004658 if (!content_desc) {
4659 continue;
4660 }
4661 std::string error;
4662 bool success =
4663 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004664 ? channel->SetLocalContent(content_desc, type, &error)
4665 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004666 if (!success) {
4667 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4668 }
4669 }
4670
4671 // If using the RtpDataChannel, push down the new SDP section for it too.
4672 if (rtp_data_channel_) {
4673 const ContentInfo* data_content =
4674 cricket::GetFirstDataContent(sdesc->description());
4675 if (data_content && !data_content->rejected) {
4676 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004677 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004678 if (data_desc) {
4679 std::string error;
4680 bool success =
4681 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004682 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4683 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004684 &error);
4685 if (!success) {
4686 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4687 std::move(error));
4688 }
Steve Anton75737c02017-11-06 10:37:17 -08004689 }
4690 }
4691 }
Steve Antoned10bd92017-12-05 10:52:59 -08004692
Steve Anton75737c02017-11-06 10:37:17 -08004693 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4694 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4695 if (sctp_transport_ && local_description() && remote_description() &&
4696 cricket::GetFirstDataContent(local_description()->description()) &&
4697 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004698 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004699 RTC_FROM_HERE,
4700 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004701 if (!success) {
4702 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4703 "Failed to push down SCTP parameters.");
4704 }
Steve Anton75737c02017-11-06 10:37:17 -08004705 }
Steve Antoned10bd92017-12-05 10:52:59 -08004706
Steve Anton8a006912017-12-04 15:25:56 -08004707 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004708}
4709
4710bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4711 RTC_DCHECK(network_thread()->IsCurrent());
4712 RTC_DCHECK(local_description());
4713 RTC_DCHECK(remote_description());
4714 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4715 // When we support "max-message-size", that would also be pushed down here.
4716 return sctp_transport_->Start(
4717 GetSctpPort(local_description()->description()),
4718 GetSctpPort(remote_description()->description()));
4719}
4720
Steve Anton8a006912017-12-04 15:25:56 -08004721RTCError PeerConnection::PushdownTransportDescription(
4722 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004723 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004724 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004725
Steve Anton8a006912017-12-04 15:25:56 -08004726 const SessionDescriptionInterface* sdesc =
4727 (source == cricket::CS_LOCAL ? local_description()
4728 : remote_description());
4729 RTC_DCHECK(sdesc);
4730 for (const cricket::TransportInfo& tinfo :
4731 sdesc->description()->transport_infos()) {
4732 std::string error;
4733 bool success;
4734 if (source == cricket::CS_LOCAL) {
4735 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004736 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004737 } else {
4738 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004739 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004740 }
4741 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004742 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4743 "Failed to push down transport description for " +
4744 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004745 }
4746 }
4747
Steve Anton8a006912017-12-04 15:25:56 -08004748 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004749}
4750
4751bool PeerConnection::GetTransportDescription(
4752 const SessionDescription* description,
4753 const std::string& content_name,
4754 cricket::TransportDescription* tdesc) {
4755 if (!description || !tdesc) {
4756 return false;
4757 }
4758 const TransportInfo* transport_info =
4759 description->GetTransportInfoByName(content_name);
4760 if (!transport_info) {
4761 return false;
4762 }
4763 *tdesc = transport_info->description;
4764 return true;
4765}
4766
4767bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4768 const std::string* first_content_name = bundle.FirstContentName();
4769 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004770 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004771 return false;
4772 }
4773 const std::string& transport_name = *first_content_name;
4774
4775 auto maybe_set_transport = [this, bundle,
4776 transport_name](cricket::BaseChannel* ch) {
4777 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004778 return;
Steve Anton75737c02017-11-06 10:37:17 -08004779 }
4780
4781 std::string old_transport_name = ch->transport_name();
4782 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004783 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4784 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004785 return;
Steve Anton75737c02017-11-06 10:37:17 -08004786 }
4787
4788 cricket::DtlsTransportInternal* rtp_dtls_transport =
4789 transport_controller_->CreateDtlsTransport(
4790 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4791 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4792 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4793 if (need_rtcp) {
4794 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4795 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4796 }
4797
4798 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004799 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4800 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004801 transport_controller_->DestroyDtlsTransport(
4802 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4803 // If the channel needs rtcp, it means that the channel used to have a
4804 // rtcp transport which needs to be deleted now.
4805 if (need_rtcp) {
4806 transport_controller_->DestroyDtlsTransport(
4807 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4808 }
Steve Anton75737c02017-11-06 10:37:17 -08004809 };
4810
Steve Antoned10bd92017-12-05 10:52:59 -08004811 for (auto transceiver : transceivers_) {
4812 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004813 }
Steve Antoned10bd92017-12-05 10:52:59 -08004814 maybe_set_transport(rtp_data_channel_);
4815
Steve Anton75737c02017-11-06 10:37:17 -08004816 // For SCTP, transport creation/deletion happens here instead of in the
4817 // object itself.
4818 if (sctp_transport_) {
4819 RTC_DCHECK(sctp_transport_name_);
4820 RTC_DCHECK(sctp_content_name_);
4821 if (transport_name != *sctp_transport_name_ &&
4822 bundle.HasContentName(*sctp_content_name_)) {
4823 network_thread()->Invoke<void>(
4824 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4825 transport_name));
4826 }
4827 }
4828
4829 return true;
4830}
4831
Steve Anton75737c02017-11-06 10:37:17 -08004832cricket::IceConfig PeerConnection::ParseIceConfig(
4833 const PeerConnectionInterface::RTCConfiguration& config) const {
4834 cricket::ContinualGatheringPolicy gathering_policy;
4835 // TODO(honghaiz): Add the third continual gathering policy in
4836 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4837 switch (config.continual_gathering_policy) {
4838 case PeerConnectionInterface::GATHER_ONCE:
4839 gathering_policy = cricket::GATHER_ONCE;
4840 break;
4841 case PeerConnectionInterface::GATHER_CONTINUALLY:
4842 gathering_policy = cricket::GATHER_CONTINUALLY;
4843 break;
4844 default:
4845 RTC_NOTREACHED();
4846 gathering_policy = cricket::GATHER_ONCE;
4847 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004848
Steve Anton75737c02017-11-06 10:37:17 -08004849 cricket::IceConfig ice_config;
4850 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4851 ice_config.prioritize_most_likely_candidate_pairs =
4852 config.prioritize_most_likely_ice_candidate_pairs;
4853 ice_config.backup_connection_ping_interval =
4854 config.ice_backup_candidate_pair_ping_interval;
4855 ice_config.continual_gathering_policy = gathering_policy;
4856 ice_config.presume_writable_when_fully_relayed =
4857 config.presume_writable_when_fully_relayed;
4858 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004859 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004860 ice_config.regather_all_networks_interval_range =
4861 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004862 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004863 return ice_config;
4864}
4865
Steve Anton75737c02017-11-06 10:37:17 -08004866bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4867 std::string* track_id) {
4868 if (!local_description()) {
4869 return false;
4870 }
4871 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4872 track_id);
4873}
4874
4875bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4876 std::string* track_id) {
4877 if (!remote_description()) {
4878 return false;
4879 }
4880 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4881 track_id);
4882}
4883
4884bool PeerConnection::SendData(const cricket::SendDataParams& params,
4885 const rtc::CopyOnWriteBuffer& payload,
4886 cricket::SendDataResult* result) {
4887 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004888 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004889 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004890 return false;
4891 }
4892 return rtp_data_channel_
4893 ? rtp_data_channel_->SendData(params, payload, result)
4894 : network_thread()->Invoke<bool>(
4895 RTC_FROM_HERE,
4896 Bind(&cricket::SctpTransportInternal::SendData,
4897 sctp_transport_.get(), params, payload, result));
4898}
4899
4900bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4901 if (!rtp_data_channel_ && !sctp_transport_) {
4902 // Don't log an error here, because DataChannels are expected to call
4903 // ConnectDataChannel in this state. It's the only way to initially tell
4904 // whether or not the underlying transport is ready.
4905 return false;
4906 }
4907 if (rtp_data_channel_) {
4908 rtp_data_channel_->SignalReadyToSendData.connect(
4909 webrtc_data_channel, &DataChannel::OnChannelReady);
4910 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4911 &DataChannel::OnDataReceived);
4912 } else {
4913 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4914 &DataChannel::OnChannelReady);
4915 SignalSctpDataReceived.connect(webrtc_data_channel,
4916 &DataChannel::OnDataReceived);
4917 SignalSctpStreamClosedRemotely.connect(
4918 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4919 }
4920 return true;
4921}
4922
4923void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4924 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004925 RTC_LOG(LS_ERROR)
4926 << "DisconnectDataChannel called when rtp_data_channel_ and "
4927 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004928 return;
4929 }
4930 if (rtp_data_channel_) {
4931 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4932 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4933 } else {
4934 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4935 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4936 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4937 }
4938}
4939
4940void PeerConnection::AddSctpDataStream(int sid) {
4941 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004942 RTC_LOG(LS_ERROR)
4943 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004944 return;
4945 }
4946 network_thread()->Invoke<void>(
4947 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4948 sctp_transport_.get(), sid));
4949}
4950
4951void PeerConnection::RemoveSctpDataStream(int sid) {
4952 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004953 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004954 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004955 return;
4956 }
4957 network_thread()->Invoke<void>(
4958 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4959 sctp_transport_.get(), sid));
4960}
4961
4962bool PeerConnection::ReadyToSendData() const {
4963 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4964 sctp_ready_to_send_data_;
4965}
4966
Qingsi Wang72a43a12018-02-20 16:03:18 -08004967cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
4968 cricket::CandidateStatsList candidate_states_list;
4969 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
4970 return candidate_states_list;
4971}
4972
Steve Anton5dfde182018-02-06 10:34:40 -08004973std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4974 const {
4975 std::map<std::string, std::string> transport_names_by_mid;
4976 for (auto transceiver : transceivers_) {
4977 cricket::BaseChannel* channel = transceiver->internal()->channel();
4978 if (channel) {
4979 transport_names_by_mid[channel->content_name()] =
4980 channel->transport_name();
4981 }
Steve Anton75737c02017-11-06 10:37:17 -08004982 }
Steve Anton5dfde182018-02-06 10:34:40 -08004983 if (rtp_data_channel_) {
4984 transport_names_by_mid[rtp_data_channel_->content_name()] =
4985 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004986 }
4987 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004988 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004989 }
Steve Anton5dfde182018-02-06 10:34:40 -08004990 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004991}
4992
Steve Anton5dfde182018-02-06 10:34:40 -08004993std::map<std::string, cricket::TransportStats>
4994PeerConnection::GetTransportStatsByNames(
4995 const std::set<std::string>& transport_names) {
4996 if (!network_thread()->IsCurrent()) {
4997 return network_thread()
4998 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4999 RTC_FROM_HERE,
5000 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005001 }
Steve Anton5dfde182018-02-06 10:34:40 -08005002 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5003 for (const std::string& transport_name : transport_names) {
5004 cricket::TransportStats transport_stats;
5005 bool success =
5006 transport_controller_->GetStats(transport_name, &transport_stats);
5007 if (success) {
5008 transport_stats_by_name[transport_name] = std::move(transport_stats);
5009 } else {
5010 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5011 << transport_name;
5012 }
5013 }
5014 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005015}
5016
5017bool PeerConnection::GetLocalCertificate(
5018 const std::string& transport_name,
5019 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5020 return transport_controller_->GetLocalCertificate(transport_name,
5021 certificate);
5022}
5023
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005024std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005025 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005026 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005027}
5028
5029cricket::DataChannelType PeerConnection::data_channel_type() const {
5030 return data_channel_type_;
5031}
5032
5033bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5034 return pending_ice_restarts_.find(content_name) !=
5035 pending_ice_restarts_.end();
5036}
5037
Steve Anton75737c02017-11-06 10:37:17 -08005038bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5039 return transport_controller_->NeedsIceRestart(content_name);
5040}
5041
5042void PeerConnection::OnCertificateReady(
5043 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5044 transport_controller_->SetLocalCertificate(certificate);
5045}
5046
5047void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005048 SetSessionError(SessionError::kTransport,
5049 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005050}
5051
5052void PeerConnection::OnTransportControllerConnectionState(
5053 cricket::IceConnectionState state) {
5054 switch (state) {
5055 case cricket::kIceConnectionConnecting:
5056 // If the current state is Connected or Completed, then there were
5057 // writable channels but now there are not, so the next state must
5058 // be Disconnected.
5059 // kIceConnectionConnecting is currently used as the default,
5060 // un-connected state by the TransportController, so its only use is
5061 // detecting disconnections.
5062 if (ice_connection_state_ ==
5063 PeerConnectionInterface::kIceConnectionConnected ||
5064 ice_connection_state_ ==
5065 PeerConnectionInterface::kIceConnectionCompleted) {
5066 SetIceConnectionState(
5067 PeerConnectionInterface::kIceConnectionDisconnected);
5068 }
5069 break;
5070 case cricket::kIceConnectionFailed:
5071 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5072 break;
5073 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005074 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005075 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005076 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5077 break;
5078 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005079 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005080 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005081 if (ice_connection_state_ !=
5082 PeerConnectionInterface::kIceConnectionConnected) {
5083 // If jumping directly from "checking" to "connected",
5084 // signal "connected" first.
5085 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5086 }
5087 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5088 if (metrics_observer()) {
5089 ReportTransportStats();
5090 }
5091 break;
5092 default:
5093 RTC_NOTREACHED();
5094 }
5095}
5096
5097void PeerConnection::OnTransportControllerCandidatesGathered(
5098 const std::string& transport_name,
5099 const cricket::Candidates& candidates) {
5100 RTC_DCHECK(signaling_thread()->IsCurrent());
5101 int sdp_mline_index;
5102 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005103 RTC_LOG(LS_ERROR)
5104 << "OnTransportControllerCandidatesGathered: content name "
5105 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005106 return;
5107 }
5108
5109 for (cricket::Candidates::const_iterator citer = candidates.begin();
5110 citer != candidates.end(); ++citer) {
5111 // Use transport_name as the candidate media id.
5112 std::unique_ptr<JsepIceCandidate> candidate(
5113 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5114 if (local_description()) {
5115 mutable_local_description()->AddCandidate(candidate.get());
5116 }
5117 OnIceCandidate(std::move(candidate));
5118 }
5119}
5120
5121void PeerConnection::OnTransportControllerCandidatesRemoved(
5122 const std::vector<cricket::Candidate>& candidates) {
5123 RTC_DCHECK(signaling_thread()->IsCurrent());
5124 // Sanity check.
5125 for (const cricket::Candidate& candidate : candidates) {
5126 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005127 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005128 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005129 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005130 return;
5131 }
5132 }
5133
5134 if (local_description()) {
5135 mutable_local_description()->RemoveCandidates(candidates);
5136 }
5137 OnIceCandidatesRemoved(candidates);
5138}
5139
5140void PeerConnection::OnTransportControllerDtlsHandshakeError(
5141 rtc::SSLHandshakeError error) {
5142 if (metrics_observer()) {
5143 metrics_observer()->IncrementEnumCounter(
5144 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5145 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5146 }
5147}
5148
Steve Antoned10bd92017-12-05 10:52:59 -08005149void PeerConnection::EnableSending() {
5150 for (auto transceiver : transceivers_) {
5151 cricket::BaseChannel* channel = transceiver->internal()->channel();
5152 if (channel && !channel->enabled()) {
5153 channel->Enable(true);
5154 }
Steve Anton75737c02017-11-06 10:37:17 -08005155 }
5156
Steve Anton4171afb2017-11-20 10:20:22 -08005157 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005158 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005159 }
Steve Anton75737c02017-11-06 10:37:17 -08005160}
5161
5162// Returns the media index for a local ice candidate given the content name.
5163bool PeerConnection::GetLocalCandidateMediaIndex(
5164 const std::string& content_name,
5165 int* sdp_mline_index) {
5166 if (!local_description() || !sdp_mline_index) {
5167 return false;
5168 }
5169
5170 bool content_found = false;
5171 const ContentInfos& contents = local_description()->description()->contents();
5172 for (size_t index = 0; index < contents.size(); ++index) {
5173 if (contents[index].name == content_name) {
5174 *sdp_mline_index = static_cast<int>(index);
5175 content_found = true;
5176 break;
5177 }
5178 }
5179 return content_found;
5180}
5181
5182bool PeerConnection::UseCandidatesInSessionDescription(
5183 const SessionDescriptionInterface* remote_desc) {
5184 if (!remote_desc) {
5185 return true;
5186 }
5187 bool ret = true;
5188
5189 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5190 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5191 for (size_t n = 0; n < candidates->count(); ++n) {
5192 const IceCandidateInterface* candidate = candidates->at(n);
5193 bool valid = false;
5194 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5195 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005196 RTC_LOG(LS_INFO)
5197 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005198 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005199 }
5200 continue;
5201 }
5202 ret = UseCandidate(candidate);
5203 if (!ret) {
5204 break;
5205 }
5206 }
5207 }
5208 return ret;
5209}
5210
5211bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5212 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5213 size_t remote_content_size =
5214 remote_description()->description()->contents().size();
5215 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005216 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005217 return false;
5218 }
5219
5220 cricket::ContentInfo content =
5221 remote_description()->description()->contents()[mediacontent_index];
5222 std::vector<cricket::Candidate> candidates;
5223 candidates.push_back(candidate->candidate());
5224 // Invoking BaseSession method to handle remote candidates.
5225 std::string error;
5226 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5227 &error)) {
5228 // Candidates successfully submitted for checking.
5229 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5230 ice_connection_state_ ==
5231 PeerConnectionInterface::kIceConnectionDisconnected) {
5232 // If state is New, then the session has just gotten its first remote ICE
5233 // candidates, so go to Checking.
5234 // If state is Disconnected, the session is re-using old candidates or
5235 // receiving additional ones, so go to Checking.
5236 // If state is Connected, stay Connected.
5237 // TODO(bemasc): If state is Connected, and the new candidates are for a
5238 // newly added transport, then the state actually _should_ move to
5239 // checking. Add a way to distinguish that case.
5240 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5241 }
5242 // TODO(bemasc): If state is Completed, go back to Connected.
5243 } else {
5244 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005245 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005246 }
5247 }
5248 return true;
5249}
5250
5251void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005252 // Destroy video channel first since it may have a pointer to the
5253 // voice channel.
5254 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005255 if (!video_info || video_info->rejected) {
5256 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005257 }
5258
Steve Anton6fec8802017-12-04 10:37:29 -08005259 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5260 if (!audio_info || audio_info->rejected) {
5261 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005262 }
5263
5264 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5265 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005266 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005267 }
5268}
5269
Steve Antoneda6ccd2017-12-04 10:21:55 -08005270std::string PeerConnection::GetTransportNameForMediaSection(
5271 const std::string& mid,
5272 const cricket::ContentGroup* bundle_group) const {
5273 if (!bundle_group) {
5274 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005275 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005276 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005277 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005278 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005279 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005280 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005281 if (!bundle_group->HasContentName(mid)) {
5282 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5283 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005284 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005285 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5286 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005287}
5288
Steve Antondcc3c022017-12-22 16:02:54 -08005289RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5290 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005291 const cricket::ContentGroup* bundle_group = nullptr;
5292 if (configuration_.bundle_policy ==
5293 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005294 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005295 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005296 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5297 "max-bundle configured but session description "
5298 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005299 }
5300 }
Steve Antondcc3c022017-12-22 16:02:54 -08005301 return std::move(bundle_group);
5302}
5303
5304RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5305 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5306 if (!bundle_group_or_error.ok()) {
5307 return bundle_group_or_error.MoveError();
5308 }
5309 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005310
Steve Antoneda6ccd2017-12-04 10:21:55 -08005311 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005312 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005313 if (voice && !voice->rejected &&
5314 !GetAudioTransceiver()->internal()->channel()) {
5315 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5316 voice->name,
5317 GetTransportNameForMediaSection(voice->name, bundle_group));
5318 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005319 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5320 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005321 }
5322 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5323 }
5324
Steve Antondcc3c022017-12-22 16:02:54 -08005325 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005326 if (video && !video->rejected &&
5327 !GetVideoTransceiver()->internal()->channel()) {
5328 cricket::VideoChannel* video_channel = CreateVideoChannel(
5329 video->name,
5330 GetTransportNameForMediaSection(video->name, bundle_group));
5331 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005332 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5333 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005334 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005335 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005336 }
5337
Steve Antondcc3c022017-12-22 16:02:54 -08005338 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005339 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5340 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005341 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5342 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005343 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5344 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005345 }
5346 }
5347
Steve Anton8a006912017-12-04 15:25:56 -08005348 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005349}
5350
Steve Anton4171afb2017-11-20 10:20:22 -08005351// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005352cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5353 const std::string& mid,
5354 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005355 cricket::DtlsTransportInternal* rtp_dtls_transport =
5356 transport_controller_->CreateDtlsTransport(
5357 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5358 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5359 if (configuration_.rtcp_mux_policy !=
5360 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5361 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5362 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5363 }
5364
5365 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5366 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005367 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5368 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005369 if (!voice_channel) {
5370 transport_controller_->DestroyDtlsTransport(
5371 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5372 if (rtcp_dtls_transport) {
5373 transport_controller_->DestroyDtlsTransport(
5374 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5375 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005376 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005377 }
Steve Anton75737c02017-11-06 10:37:17 -08005378 voice_channel->SignalRtcpMuxFullyActive.connect(
5379 this, &PeerConnection::DestroyRtcpTransport_n);
5380 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5381 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005382 voice_channel->SignalSentPacket.connect(this,
5383 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005384
Steve Antoneda6ccd2017-12-04 10:21:55 -08005385 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005386}
5387
Steve Anton4171afb2017-11-20 10:20:22 -08005388// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005389cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5390 const std::string& mid,
5391 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005392 cricket::DtlsTransportInternal* rtp_dtls_transport =
5393 transport_controller_->CreateDtlsTransport(
5394 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5395 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5396 if (configuration_.rtcp_mux_policy !=
5397 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5398 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5399 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5400 }
5401
5402 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5403 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005404 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5405 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005406
5407 if (!video_channel) {
5408 transport_controller_->DestroyDtlsTransport(
5409 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5410 if (rtcp_dtls_transport) {
5411 transport_controller_->DestroyDtlsTransport(
5412 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5413 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005414 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005415 }
Steve Anton75737c02017-11-06 10:37:17 -08005416 video_channel->SignalRtcpMuxFullyActive.connect(
5417 this, &PeerConnection::DestroyRtcpTransport_n);
5418 video_channel->SignalDtlsSrtpSetupFailure.connect(
5419 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005420 video_channel->SignalSentPacket.connect(this,
5421 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005422
Steve Antoneda6ccd2017-12-04 10:21:55 -08005423 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005424}
5425
Steve Antoneda6ccd2017-12-04 10:21:55 -08005426bool PeerConnection::CreateDataChannel(const std::string& mid,
5427 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005428 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5429 if (sctp) {
5430 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005431 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005432 << "Trying to create SCTP transport, but didn't compile with "
5433 "SCTP support (HAVE_SCTP)";
5434 return false;
5435 }
5436 if (!network_thread()->Invoke<bool>(
5437 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005438 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005439 return false;
5440 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005441 for (const auto& channel : sctp_data_channels_) {
5442 channel->OnTransportChannelCreated();
5443 }
Steve Anton75737c02017-11-06 10:37:17 -08005444 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005445 cricket::DtlsTransportInternal* rtp_dtls_transport =
5446 transport_controller_->CreateDtlsTransport(
5447 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5448 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5449 if (configuration_.rtcp_mux_policy !=
5450 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5451 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5452 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5453 }
5454
5455 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5456 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005457 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005458
5459 if (!rtp_data_channel_) {
5460 transport_controller_->DestroyDtlsTransport(
5461 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5462 if (rtcp_dtls_transport) {
5463 transport_controller_->DestroyDtlsTransport(
5464 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5465 }
5466 return false;
5467 }
5468
5469 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5470 this, &PeerConnection::DestroyRtcpTransport_n);
5471 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5472 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5473 rtp_data_channel_->SignalSentPacket.connect(
5474 this, &PeerConnection::OnSentPacket_w);
5475 }
5476
Steve Anton75737c02017-11-06 10:37:17 -08005477 return true;
5478}
5479
5480Call::Stats PeerConnection::GetCallStats() {
5481 if (!worker_thread()->IsCurrent()) {
5482 return worker_thread()->Invoke<Call::Stats>(
5483 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5484 }
5485 if (call_) {
5486 return call_->GetStats();
5487 } else {
5488 return Call::Stats();
5489 }
5490}
5491
Steve Anton75737c02017-11-06 10:37:17 -08005492bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5493 const std::string& transport_name) {
5494 RTC_DCHECK(network_thread()->IsCurrent());
5495 RTC_DCHECK(sctp_factory_);
5496 cricket::DtlsTransportInternal* tc =
5497 transport_controller_->CreateDtlsTransport_n(
5498 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5499 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5500 RTC_DCHECK(sctp_transport_);
5501 sctp_invoker_.reset(new rtc::AsyncInvoker());
5502 sctp_transport_->SignalReadyToSendData.connect(
5503 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5504 sctp_transport_->SignalDataReceived.connect(
5505 this, &PeerConnection::OnSctpTransportDataReceived_n);
5506 sctp_transport_->SignalStreamClosedRemotely.connect(
5507 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005508 sctp_transport_name_ = transport_name;
5509 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005510 return true;
5511}
5512
5513void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5514 RTC_DCHECK(network_thread()->IsCurrent());
5515 RTC_DCHECK(sctp_transport_);
5516 RTC_DCHECK(sctp_transport_name_);
5517 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005518 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005519 cricket::DtlsTransportInternal* tc =
5520 transport_controller_->CreateDtlsTransport_n(
5521 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5522 sctp_transport_->SetTransportChannel(tc);
5523 transport_controller_->DestroyDtlsTransport_n(
5524 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5525}
5526
5527void PeerConnection::DestroySctpTransport_n() {
5528 RTC_DCHECK(network_thread()->IsCurrent());
5529 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005530 transport_controller_->DestroyDtlsTransport_n(
5531 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005532 sctp_content_name_.reset();
5533 sctp_transport_name_.reset();
5534 sctp_invoker_.reset(nullptr);
5535 sctp_ready_to_send_data_ = false;
5536}
5537
5538void PeerConnection::OnSctpTransportReadyToSendData_n() {
5539 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5540 RTC_DCHECK(network_thread()->IsCurrent());
5541 // Note: Cannot use rtc::Bind here because it will grab a reference to
5542 // PeerConnection and potentially cause PeerConnection to live longer than
5543 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5544 // be destroyed before PeerConnection is destroyed, and at that point all
5545 // pending tasks will be cleared.
5546 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5547 OnSctpTransportReadyToSendData_s(true);
5548 });
5549}
5550
5551void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5552 RTC_DCHECK(signaling_thread()->IsCurrent());
5553 sctp_ready_to_send_data_ = ready;
5554 SignalSctpReadyToSendData(ready);
5555}
5556
5557void PeerConnection::OnSctpTransportDataReceived_n(
5558 const cricket::ReceiveDataParams& params,
5559 const rtc::CopyOnWriteBuffer& payload) {
5560 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5561 RTC_DCHECK(network_thread()->IsCurrent());
5562 // Note: Cannot use rtc::Bind here because it will grab a reference to
5563 // PeerConnection and potentially cause PeerConnection to live longer than
5564 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5565 // be destroyed before PeerConnection is destroyed, and at that point all
5566 // pending tasks will be cleared.
5567 sctp_invoker_->AsyncInvoke<void>(
5568 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5569 OnSctpTransportDataReceived_s(params, payload);
5570 });
5571}
5572
5573void PeerConnection::OnSctpTransportDataReceived_s(
5574 const cricket::ReceiveDataParams& params,
5575 const rtc::CopyOnWriteBuffer& payload) {
5576 RTC_DCHECK(signaling_thread()->IsCurrent());
5577 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5578 // Received OPEN message; parse and signal that a new data channel should
5579 // be created.
5580 std::string label;
5581 InternalDataChannelInit config;
5582 config.id = params.ssrc;
5583 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005584 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5585 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005586 return;
5587 }
5588 config.open_handshake_role = InternalDataChannelInit::kAcker;
5589 OnDataChannelOpenMessage(label, config);
5590 } else {
5591 // Otherwise just forward the signal.
5592 SignalSctpDataReceived(params, payload);
5593 }
5594}
5595
5596void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5597 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5598 RTC_DCHECK(network_thread()->IsCurrent());
5599 sctp_invoker_->AsyncInvoke<void>(
5600 RTC_FROM_HERE, signaling_thread(),
5601 rtc::Bind(&sigslot::signal1<int>::operator(),
5602 &SignalSctpStreamClosedRemotely, sid));
5603}
5604
5605// Returns false if bundle is enabled and rtcp_mux is disabled.
5606bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5607 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5608 if (!bundle_enabled)
5609 return true;
5610
5611 const cricket::ContentGroup* bundle_group =
5612 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5613 RTC_DCHECK(bundle_group != NULL);
5614
5615 const cricket::ContentInfos& contents = desc->contents();
5616 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5617 citer != contents.end(); ++citer) {
5618 const cricket::ContentInfo* content = (&*citer);
5619 RTC_DCHECK(content != NULL);
5620 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005621 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005622 if (!HasRtcpMuxEnabled(content))
5623 return false;
5624 }
5625 }
5626 // RTCP-MUX is enabled in all the contents.
5627 return true;
5628}
5629
5630bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005631 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005632}
5633
Steve Anton8a006912017-12-04 15:25:56 -08005634RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005635 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005636 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005637 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005638 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005639 }
5640
5641 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005643 }
5644
Steve Anton3828c062017-12-06 10:34:51 -08005645 SdpType type = sdesc->GetType();
5646 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5647 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005648 LOG_AND_RETURN_ERROR(
5649 RTCErrorType::INVALID_PARAMETER,
5650 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005651 }
5652
5653 // Verify crypto settings.
5654 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005655 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5656 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005657 RTCError crypto_error =
5658 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005659 if (!crypto_error.ok()) {
5660 return crypto_error;
5661 }
Steve Anton75737c02017-11-06 10:37:17 -08005662 }
5663
5664 // Verify ice-ufrag and ice-pwd.
5665 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005666 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5667 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005668 }
5669
5670 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5672 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005673 }
5674
5675 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5676 // m-lines that do not rtcp-mux enabled.
5677
5678 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005679 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005680 // With an answer we want to compare the new answer session description with
5681 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005682 const cricket::SessionDescription* offer_desc =
5683 (source == cricket::CS_LOCAL) ? remote_description()->description()
5684 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005685 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5686 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5687 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005688 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5689 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005690 }
5691 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005692 // The re-offers should respect the order of m= sections in current
5693 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005694 // With a re-offer, either the current local or current remote descriptions
5695 // could be the most up to date, so we would like to check against both of
5696 // them if they exist. It could be the case that one of them has a 0 port
5697 // for a media section, but the other does not. This is important to check
5698 // against in the case that we are recycling an m= section.
5699 const cricket::SessionDescription* current_desc = nullptr;
5700 const cricket::SessionDescription* secondary_current_desc = nullptr;
5701 if (local_description()) {
5702 current_desc = local_description()->description();
5703 if (remote_description()) {
5704 secondary_current_desc = remote_description()->description();
5705 }
5706 } else if (remote_description()) {
5707 current_desc = remote_description()->description();
5708 }
Steve Anton75737c02017-11-06 10:37:17 -08005709 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005710 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5711 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005712 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5713 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005714 }
5715 }
5716
Steve Anton8a006912017-12-04 15:25:56 -08005717 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005718}
5719
Steve Anton3828c062017-12-06 10:34:51 -08005720bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005721 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005722 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005723 return (state == PeerConnectionInterface::kStable) ||
5724 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005725 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005726 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005727 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5728 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5729 }
5730}
5731
Steve Anton3828c062017-12-06 10:34:51 -08005732bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005733 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005734 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005735 return (state == PeerConnectionInterface::kStable) ||
5736 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005737 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005738 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005739 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5740 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5741 }
5742}
5743
Steve Antonf8470812017-12-04 10:46:21 -08005744const char* PeerConnection::SessionErrorToString(SessionError error) const {
5745 switch (error) {
5746 case SessionError::kNone:
5747 return "ERROR_NONE";
5748 case SessionError::kContent:
5749 return "ERROR_CONTENT";
5750 case SessionError::kTransport:
5751 return "ERROR_TRANSPORT";
5752 }
5753 RTC_NOTREACHED();
5754 return "";
5755}
5756
Steve Anton75737c02017-11-06 10:37:17 -08005757std::string PeerConnection::GetSessionErrorMsg() {
5758 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005759 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5760 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005761 return desc.str();
5762}
5763
Steve Anton0ffaaa22018-02-23 10:31:30 -08005764void PeerConnection::ReportNegotiatedSdpSemantics(
5765 const SessionDescriptionInterface& answer) {
5766 if (!uma_observer_) {
5767 return;
5768 }
5769 switch (answer.description()->msid_signaling()) {
5770 case 0:
5771 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5772 kSdpSemanticNegotiatedNone,
5773 kSdpSemanticNegotiatedMax);
5774 break;
5775 case cricket::kMsidSignalingMediaSection:
5776 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5777 kSdpSemanticNegotiatedUnifiedPlan,
5778 kSdpSemanticNegotiatedMax);
5779 break;
5780 case cricket::kMsidSignalingSsrcAttribute:
5781 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5782 kSdpSemanticNegotiatedPlanB,
5783 kSdpSemanticNegotiatedMax);
5784 break;
5785 case cricket::kMsidSignalingMediaSection |
5786 cricket::kMsidSignalingSsrcAttribute:
5787 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5788 kSdpSemanticNegotiatedMixed,
5789 kSdpSemanticNegotiatedMax);
5790 break;
5791 default:
5792 RTC_NOTREACHED();
5793 }
5794}
5795
Steve Anton75737c02017-11-06 10:37:17 -08005796// We need to check the local/remote description for the Transport instead of
5797// the session, because a new Transport added during renegotiation may have
5798// them unset while the session has them set from the previous negotiation.
5799// Not doing so may trigger the auto generation of transport description and
5800// mess up DTLS identity information, ICE credential, etc.
5801bool PeerConnection::ReadyToUseRemoteCandidate(
5802 const IceCandidateInterface* candidate,
5803 const SessionDescriptionInterface* remote_desc,
5804 bool* valid) {
5805 *valid = true;
5806
5807 const SessionDescriptionInterface* current_remote_desc =
5808 remote_desc ? remote_desc : remote_description();
5809
5810 if (!current_remote_desc) {
5811 return false;
5812 }
5813
5814 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5815 size_t remote_content_size =
5816 current_remote_desc->description()->contents().size();
5817 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005818 RTC_LOG(LS_ERROR)
5819 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5820 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005821
5822 *valid = false;
5823 return false;
5824 }
5825
5826 cricket::ContentInfo content =
5827 current_remote_desc->description()->contents()[mediacontent_index];
5828
5829 const std::string transport_name = GetTransportName(content.name);
5830 if (transport_name.empty()) {
5831 return false;
5832 }
5833 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5834}
5835
5836bool PeerConnection::SrtpRequired() const {
5837 return dtls_enabled_ ||
5838 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5839}
5840
5841void PeerConnection::OnTransportControllerGatheringState(
5842 cricket::IceGatheringState state) {
5843 RTC_DCHECK(signaling_thread()->IsCurrent());
5844 if (state == cricket::kIceGatheringGathering) {
5845 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5846 } else if (state == cricket::kIceGatheringComplete) {
5847 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5848 }
5849}
5850
5851void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005852 std::map<std::string, std::set<cricket::MediaType>>
5853 media_types_by_transport_name;
5854 for (auto transceiver : transceivers_) {
5855 if (transceiver->internal()->channel()) {
5856 const std::string& transport_name =
5857 transceiver->internal()->channel()->transport_name();
5858 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005859 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005860 }
Steve Anton75737c02017-11-06 10:37:17 -08005861 }
5862 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005863 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5864 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005865 }
5866 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005867 media_types_by_transport_name[*sctp_transport_name_].insert(
5868 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005869 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005870 for (const auto& entry : media_types_by_transport_name) {
5871 const std::string& transport_name = entry.first;
5872 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005873 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005874 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005875 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005876 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005877 }
5878 }
5879}
5880// Walk through the ConnectionInfos to gather best connection usage
5881// for IPv4 and IPv6.
5882void PeerConnection::ReportBestConnectionState(
5883 const cricket::TransportStats& stats) {
5884 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005885 for (const cricket::TransportChannelStats& channel_stats :
5886 stats.channel_stats) {
5887 for (const cricket::ConnectionInfo& connection_info :
5888 channel_stats.connection_infos) {
5889 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005890 continue;
5891 }
5892
5893 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005894 const cricket::Candidate& local = connection_info.local_candidate;
5895 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005896
5897 // Increment the counter for IceCandidatePairType.
5898 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5899 (local.type() == RELAY_PORT_TYPE &&
5900 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5901 type = kEnumCounterIceCandidatePairTypeTcp;
5902 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5903 type = kEnumCounterIceCandidatePairTypeUdp;
5904 } else {
5905 RTC_CHECK(0);
5906 }
5907 metrics_observer()->IncrementEnumCounter(
5908 type, GetIceCandidatePairCounter(local, remote),
5909 kIceCandidatePairMax);
5910
5911 // Increment the counter for IP type.
5912 if (local.address().family() == AF_INET) {
5913 metrics_observer()->IncrementEnumCounter(
5914 kEnumCounterAddressFamily, kBestConnections_IPv4,
5915 kPeerConnectionAddressFamilyCounter_Max);
5916
5917 } else if (local.address().family() == AF_INET6) {
5918 metrics_observer()->IncrementEnumCounter(
5919 kEnumCounterAddressFamily, kBestConnections_IPv6,
5920 kPeerConnectionAddressFamilyCounter_Max);
5921 } else {
5922 RTC_CHECK(0);
5923 }
5924
5925 return;
5926 }
5927 }
5928}
5929
5930void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005931 const cricket::TransportStats& stats,
5932 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005933 RTC_DCHECK(metrics_observer());
5934 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5935 return;
5936 }
5937
5938 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5939 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5940 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5941 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5942 return;
5943 }
5944
Steve Antonc7b964c2018-02-01 14:39:45 -08005945 for (cricket::MediaType media_type : media_types) {
5946 PeerConnectionEnumCounterType srtp_counter_type;
5947 PeerConnectionEnumCounterType ssl_counter_type;
5948 switch (media_type) {
5949 case cricket::MEDIA_TYPE_AUDIO:
5950 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5951 ssl_counter_type = kEnumCounterAudioSslCipher;
5952 break;
5953 case cricket::MEDIA_TYPE_VIDEO:
5954 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5955 ssl_counter_type = kEnumCounterVideoSslCipher;
5956 break;
5957 case cricket::MEDIA_TYPE_DATA:
5958 srtp_counter_type = kEnumCounterDataSrtpCipher;
5959 ssl_counter_type = kEnumCounterDataSslCipher;
5960 break;
5961 default:
5962 RTC_NOTREACHED();
5963 continue;
5964 }
5965 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5966 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5967 srtp_crypto_suite);
5968 }
5969 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5970 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5971 ssl_cipher_suite);
5972 }
Steve Anton75737c02017-11-06 10:37:17 -08005973 }
5974}
5975
5976void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5977 RTC_DCHECK(worker_thread()->IsCurrent());
5978 RTC_DCHECK(call_);
5979 call_->OnSentPacket(sent_packet);
5980}
5981
5982const std::string PeerConnection::GetTransportName(
5983 const std::string& content_name) {
5984 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005985 if (channel) {
5986 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005987 }
Steve Anton6fec8802017-12-04 10:37:29 -08005988 if (sctp_transport_) {
5989 RTC_DCHECK(sctp_content_name_);
5990 RTC_DCHECK(sctp_transport_name_);
5991 if (content_name == *sctp_content_name_) {
5992 return *sctp_transport_name_;
5993 }
5994 }
5995 // Return an empty string if failed to retrieve the transport name.
5996 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005997}
5998
5999void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6000 RTC_DCHECK(network_thread()->IsCurrent());
6001 transport_controller_->DestroyDtlsTransport_n(
6002 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6003}
6004
Steve Anton6fec8802017-12-04 10:37:29 -08006005void PeerConnection::DestroyTransceiverChannel(
6006 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6007 transceiver) {
6008 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006009
Steve Anton6fec8802017-12-04 10:37:29 -08006010 cricket::BaseChannel* channel = transceiver->internal()->channel();
6011 if (channel) {
6012 transceiver->internal()->SetChannel(nullptr);
6013 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006014 }
6015}
6016
6017void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006018 if (rtp_data_channel_) {
6019 OnDataChannelDestroyed();
6020 DestroyBaseChannel(rtp_data_channel_);
6021 rtp_data_channel_ = nullptr;
6022 }
6023
6024 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6025 // grab a reference to this PeerConnection. If this is called from the
6026 // PeerConnection destructor, the RefCountedObject vtable will have already
6027 // been destroyed (since it is a subclass of PeerConnection) and using
6028 // rtc::Bind will cause "Pure virtual function called" error to appear.
6029
6030 if (sctp_transport_) {
6031 OnDataChannelDestroyed();
6032 network_thread()->Invoke<void>(RTC_FROM_HERE,
6033 [this] { DestroySctpTransport_n(); });
6034 }
6035}
6036
6037void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6038 RTC_DCHECK(channel);
6039 RTC_DCHECK(channel->rtp_dtls_transport());
6040
6041 // Need to cache these before destroying the base channel so that we do not
6042 // access uninitialized memory.
6043 const std::string transport_name =
6044 channel->rtp_dtls_transport()->transport_name();
6045 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6046
6047 switch (channel->media_type()) {
6048 case cricket::MEDIA_TYPE_AUDIO:
6049 channel_manager()->DestroyVoiceChannel(
6050 static_cast<cricket::VoiceChannel*>(channel));
6051 break;
6052 case cricket::MEDIA_TYPE_VIDEO:
6053 channel_manager()->DestroyVideoChannel(
6054 static_cast<cricket::VideoChannel*>(channel));
6055 break;
6056 case cricket::MEDIA_TYPE_DATA:
6057 channel_manager()->DestroyRtpDataChannel(
6058 static_cast<cricket::RtpDataChannel*>(channel));
6059 break;
6060 default:
6061 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6062 break;
6063 }
6064
6065 // |channel| can no longer be used.
6066
Steve Anton75737c02017-11-06 10:37:17 -08006067 transport_controller_->DestroyDtlsTransport(
6068 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6069 if (need_to_delete_rtcp) {
6070 transport_controller_->DestroyDtlsTransport(
6071 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6072 }
6073}
6074
Harald Alvestrand89061872018-01-02 14:08:34 +01006075void PeerConnection::ClearStatsCache() {
6076 if (stats_collector_) {
6077 stats_collector_->ClearCachedStatsReport();
6078 }
6079}
6080
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006081} // namespace webrtc