blob: 2d28b8775eb56220f9c3385a1d470bf80f2a0257 [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;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
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;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
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 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " 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 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Qingsi Wang866e08d2018-03-22 17:54:23 -0700603rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
604 int rtc_configuration_parameter) {
605 if (rtc_configuration_parameter ==
606 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
607 return rtc::nullopt;
608 }
609 return rtc_configuration_parameter;
610}
611
Steve Anton75737c02017-11-06 10:37:17 -0800612} // namespace
613
Henrik Boström31638672017-11-23 17:48:32 +0100614// Upon completion, posts a task to execute the callback of the
615// SetSessionDescriptionObserver asynchronously on the same thread. At this
616// point, the state of the peer connection might no longer reflect the effects
617// of the SetRemoteDescription operation, as the peer connection could have been
618// modified during the post.
619// TODO(hbos): Remove this class once we remove the version of
620// PeerConnectionInterface::SetRemoteDescription() that takes a
621// SetSessionDescriptionObserver as an argument.
622class PeerConnection::SetRemoteDescriptionObserverAdapter
623 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
624 public:
625 SetRemoteDescriptionObserverAdapter(
626 rtc::scoped_refptr<PeerConnection> pc,
627 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
628 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
629
630 // SetRemoteDescriptionObserverInterface implementation.
631 void OnSetRemoteDescriptionComplete(RTCError error) override {
632 if (error.ok())
633 pc_->PostSetSessionDescriptionSuccess(wrapper_);
634 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100635 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100636 }
637
638 private:
639 rtc::scoped_refptr<PeerConnection> pc_;
640 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
641};
642
deadbeef293e9262017-01-11 12:28:30 -0800643bool PeerConnectionInterface::RTCConfiguration::operator==(
644 const PeerConnectionInterface::RTCConfiguration& o) const {
645 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700646 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800647 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000648 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700649 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800650 BundlePolicy bundle_policy;
651 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700652 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
653 int ice_candidate_pool_size;
654 bool disable_ipv6;
655 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700656 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100657 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 bool enable_rtp_data_channel;
659 rtc::Optional<int> screencast_min_bitrate;
660 rtc::Optional<bool> combined_audio_video_bwe;
661 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800662 TcpCandidatePolicy tcp_candidate_policy;
663 CandidateNetworkPolicy candidate_network_policy;
664 int audio_jitter_buffer_max_packets;
665 bool audio_jitter_buffer_fast_accelerate;
666 int ice_connection_receiving_timeout;
667 int ice_backup_candidate_pair_ping_interval;
668 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800669 bool prioritize_most_likely_ice_candidate_pairs;
670 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800671 bool prune_turn_ports;
672 bool presume_writable_when_fully_relayed;
673 bool enable_ice_renomination;
674 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800675 rtc::Optional<int> ice_check_interval_strong_connectivity;
676 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800677 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700678 rtc::Optional<int> ice_unwritable_timeout;
679 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800680 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700681 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200682 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800683 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800684 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800685 };
686 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
687 "Did you add something to RTCConfiguration and forget to "
688 "update operator==?");
689 return type == o.type && servers == o.servers &&
690 bundle_policy == o.bundle_policy &&
691 rtcp_mux_policy == o.rtcp_mux_policy &&
692 tcp_candidate_policy == o.tcp_candidate_policy &&
693 candidate_network_policy == o.candidate_network_policy &&
694 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
695 audio_jitter_buffer_fast_accelerate ==
696 o.audio_jitter_buffer_fast_accelerate &&
697 ice_connection_receiving_timeout ==
698 o.ice_connection_receiving_timeout &&
699 ice_backup_candidate_pair_ping_interval ==
700 o.ice_backup_candidate_pair_ping_interval &&
701 continual_gathering_policy == o.continual_gathering_policy &&
702 certificates == o.certificates &&
703 prioritize_most_likely_ice_candidate_pairs ==
704 o.prioritize_most_likely_ice_candidate_pairs &&
705 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800706 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700707 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100708 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800709 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800710 screencast_min_bitrate == o.screencast_min_bitrate &&
711 combined_audio_video_bwe == o.combined_audio_video_bwe &&
712 enable_dtls_srtp == o.enable_dtls_srtp &&
713 ice_candidate_pool_size == o.ice_candidate_pool_size &&
714 prune_turn_ports == o.prune_turn_ports &&
715 presume_writable_when_fully_relayed ==
716 o.presume_writable_when_fully_relayed &&
717 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800718 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800719 ice_check_interval_strong_connectivity ==
720 o.ice_check_interval_strong_connectivity &&
721 ice_check_interval_weak_connectivity ==
722 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700723 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700724 ice_unwritable_timeout == o.ice_unwritable_timeout &&
725 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800726 stun_candidate_keepalive_interval ==
727 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200728 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800729 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800730 sdp_semantics == o.sdp_semantics &&
731 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800732}
733
734bool PeerConnectionInterface::RTCConfiguration::operator!=(
735 const PeerConnectionInterface::RTCConfiguration& o) const {
736 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800737}
738
zhihuang8f65cdf2016-05-06 18:40:30 -0700739// Generate a RTCP CNAME when a PeerConnection is created.
740std::string GenerateRtcpCname() {
741 std::string cname;
742 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100743 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800744 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700745 }
746 return cname;
747}
748
zhihuang1c378ed2017-08-17 14:10:50 -0700749bool ValidateOfferAnswerOptions(
750 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
751 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
752 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700753}
754
zhihuang1c378ed2017-08-17 14:10:50 -0700755// From |rtc_options|, fill parts of |session_options| shared by all generated
756// m= sections (in other words, nothing that involves a map/array).
757void ExtractSharedMediaSessionOptions(
758 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
759 cricket::MediaSessionOptions* session_options) {
760 session_options->vad_enabled = rtc_options.voice_activity_detection;
761 session_options->bundle_enabled = rtc_options.use_rtp_mux;
762}
zhihuanga77e6bb2017-08-14 18:17:48 -0700763
zhihuang1c378ed2017-08-17 14:10:50 -0700764bool ConvertConstraintsToOfferAnswerOptions(
765 const MediaConstraintsInterface* constraints,
766 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700767 if (!constraints) {
768 return true;
769 }
zhihuang1c378ed2017-08-17 14:10:50 -0700770
771 bool value = false;
772 size_t mandatory_constraints_satisfied = 0;
773
774 if (FindConstraint(constraints,
775 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
776 &mandatory_constraints_satisfied)) {
777 offer_answer_options->offer_to_receive_audio =
778 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
779 kOfferToReceiveMediaTrue
780 : 0;
781 }
782
783 if (FindConstraint(constraints,
784 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
785 &mandatory_constraints_satisfied)) {
786 offer_answer_options->offer_to_receive_video =
787 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
788 kOfferToReceiveMediaTrue
789 : 0;
790 }
791 if (FindConstraint(constraints,
792 MediaConstraintsInterface::kVoiceActivityDetection, &value,
793 &mandatory_constraints_satisfied)) {
794 offer_answer_options->voice_activity_detection = value;
795 }
796 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
797 &mandatory_constraints_satisfied)) {
798 offer_answer_options->use_rtp_mux = value;
799 }
800 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
801 &value, &mandatory_constraints_satisfied)) {
802 offer_answer_options->ice_restart = value;
803 }
804
deadbeefab9b2d12015-10-14 11:33:11 -0700805 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
806}
807
zhihuang38ede132017-06-15 12:52:32 -0700808PeerConnection::PeerConnection(PeerConnectionFactory* factory,
809 std::unique_ptr<RtcEventLog> event_log,
810 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700812 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700813 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700814 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700815 remote_streams_(StreamCollection::Create()),
816 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817
818PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100819 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800820 RTC_DCHECK_RUN_ON(signaling_thread());
821
Steve Anton8af21862017-12-15 11:20:13 -0800822 // Need to stop transceivers before destroying the stats collector because
823 // AudioRtpSender has a reference to the StatsCollector it will update when
824 // stopping.
825 for (auto transceiver : transceivers_) {
826 transceiver->Stop();
827 }
Steve Anton4171afb2017-11-20 10:20:22 -0800828
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700829 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800830 if (stats_collector_) {
831 stats_collector_->WaitForPendingRequest();
832 stats_collector_ = nullptr;
833 }
Steve Anton75737c02017-11-06 10:37:17 -0800834
Steve Anton8af21862017-12-15 11:20:13 -0800835 // Don't destroy BaseChannels until after stats has been cleaned up so that
836 // the last stats request can still read from the channels.
837 DestroyAllChannels();
838
Mirko Bonadei675513b2017-11-09 11:09:25 +0100839 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800840
841 webrtc_session_desc_factory_.reset();
842 sctp_invoker_.reset();
843 sctp_factory_.reset();
844 transport_controller_.reset();
845
deadbeef91dd5672016-05-18 16:55:30 -0700846 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700847 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700848 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700849 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700850 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700851 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800852 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700853 event_log_.reset();
854 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855}
856
Steve Anton8af21862017-12-15 11:20:13 -0800857void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800858 // Destroy video channels first since they may have a pointer to a voice
859 // channel.
860 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800861 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800862 DestroyTransceiverChannel(transceiver);
863 }
864 }
865 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800866 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800867 DestroyTransceiverChannel(transceiver);
868 }
869 }
870 DestroyDataChannel();
871}
872
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000874 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700875 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200876 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800877 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100878 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700879
880 RTCError config_error = ValidateConfiguration(configuration);
881 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100882 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700883 return false;
884 }
885
deadbeef293e9262017-01-11 12:28:30 -0800886 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100887 RTC_LOG(LS_ERROR)
888 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100889 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800890 return false;
891 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200892
deadbeef653b8e02015-11-11 12:55:10 -0800893 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800894 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100896 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800897 return false;
898 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000899 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800900 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800901
deadbeef91dd5672016-05-18 16:55:30 -0700902 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700903 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700904 if (!network_thread()->Invoke<bool>(
905 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
906 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907 return false;
908 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909
Steve Anton75737c02017-11-06 10:37:17 -0800910 // RFC 3264: The numeric value of the session id and version in the
911 // o line MUST be representable with a "64 bit signed integer".
912 // Due to this constraint session id |session_id_| is max limited to
913 // LLONG_MAX.
914 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
915 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800916 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
917 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800918 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
919 transport_controller_->SignalConnectionState.connect(
920 this, &PeerConnection::OnTransportControllerConnectionState);
921 transport_controller_->SignalGatheringState.connect(
922 this, &PeerConnection::OnTransportControllerGatheringState);
923 transport_controller_->SignalCandidatesGathered.connect(
924 this, &PeerConnection::OnTransportControllerCandidatesGathered);
925 transport_controller_->SignalCandidatesRemoved.connect(
926 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
927 transport_controller_->SignalDtlsHandshakeError.connect(
928 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
929
930 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700931
deadbeefab9b2d12015-10-14 11:33:11 -0700932 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700933 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934
Steve Antonba818672017-11-06 10:21:57 -0800935 configuration_ = configuration;
936
Steve Anton75737c02017-11-06 10:37:17 -0800937 const PeerConnectionFactoryInterface::Options& options = factory_->options();
938
939 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
940
941 // Obtain a certificate from RTCConfiguration if any were provided (optional).
942 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
943 if (!configuration.certificates.empty()) {
944 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
945 // just picking the first one. The decision should be made based on the DTLS
946 // handshake. The DTLS negotiations need to know about all certificates.
947 certificate = configuration.certificates[0];
948 }
949
Steve Antond25da372017-11-06 14:50:29 -0800950 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800951
952 if (options.disable_encryption) {
953 dtls_enabled_ = false;
954 } else {
955 // Enable DTLS by default if we have an identity store or a certificate.
956 dtls_enabled_ = (cert_generator || certificate);
957 // |configuration| can override the default |dtls_enabled_| value.
958 if (configuration.enable_dtls_srtp) {
959 dtls_enabled_ = *(configuration.enable_dtls_srtp);
960 }
961 }
962
963 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
964 // It takes precendence over the disable_sctp_data_channels
965 // PeerConnectionFactoryInterface::Options.
966 if (configuration.enable_rtp_data_channel) {
967 data_channel_type_ = cricket::DCT_RTP;
968 } else {
969 // DTLS has to be enabled to use SCTP.
970 if (!options.disable_sctp_data_channels && dtls_enabled_) {
971 data_channel_type_ = cricket::DCT_SCTP;
972 }
973 }
974
975 video_options_.screencast_min_bitrate_kbps =
976 configuration.screencast_min_bitrate;
977 audio_options_.combined_audio_video_bwe =
978 configuration.combined_audio_video_bwe;
979
980 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100981 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800982
983 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100984 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800985
986 // Whether the certificate generator/certificate is null or not determines
987 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
988 // the right instructions by clearing the variables if needed.
989 if (!dtls_enabled_) {
990 cert_generator.reset();
991 certificate = nullptr;
992 } else if (certificate) {
993 // Favor generated certificate over the certificate generator.
994 cert_generator.reset();
995 }
996
997 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
998 signaling_thread(), channel_manager(), this, session_id(),
999 std::move(cert_generator), certificate));
1000 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1001 this, &PeerConnection::OnCertificateReady);
1002
1003 if (options.disable_encryption) {
1004 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1005 }
1006
1007 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1008 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009
Steve Anton4171afb2017-11-20 10:20:22 -08001010 // Add default audio/video transceivers for Plan B SDP.
1011 if (!IsUnifiedPlan()) {
1012 transceivers_.push_back(
1013 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1014 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1015 transceivers_.push_back(
1016 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1017 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1018 }
1019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 return true;
1021}
1022
Steve Anton038834f2017-07-14 15:59:59 -07001023RTCError PeerConnection::ValidateConfiguration(
1024 const RTCConfiguration& config) const {
1025 if (config.ice_regather_interval_range &&
1026 config.continual_gathering_policy == GATHER_ONCE) {
1027 return RTCError(RTCErrorType::INVALID_PARAMETER,
1028 "ice_regather_interval_range specified but continual "
1029 "gathering policy is GATHER_ONCE");
1030 }
1031 return RTCError::OK();
1032}
1033
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001034rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001036 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1037 "Plan SdpSemantics. Please use GetSenders "
1038 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001039 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040}
1041
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001042rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001044 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1045 "Plan SdpSemantics. Please use GetReceivers "
1046 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001047 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001048}
1049
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001050bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001051 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1052 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001053 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054 if (IsClosed()) {
1055 return false;
1056 }
deadbeefab9b2d12015-10-14 11:33:11 -07001057 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058 return false;
1059 }
deadbeefab9b2d12015-10-14 11:33:11 -07001060
1061 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001062 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1063 observer->SignalAudioTrackAdded.connect(this,
1064 &PeerConnection::OnAudioTrackAdded);
1065 observer->SignalAudioTrackRemoved.connect(
1066 this, &PeerConnection::OnAudioTrackRemoved);
1067 observer->SignalVideoTrackAdded.connect(this,
1068 &PeerConnection::OnVideoTrackAdded);
1069 observer->SignalVideoTrackRemoved.connect(
1070 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001071 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001072
deadbeefab9b2d12015-10-14 11:33:11 -07001073 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001074 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001075 }
1076 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001077 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001078 }
1079
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001080 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 observer_->OnRenegotiationNeeded();
1082 return true;
1083}
1084
1085void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001086 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1087 "Plan SdpSemantics. Please use RemoveTrack "
1088 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001089 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001090 if (!IsClosed()) {
1091 for (const auto& track : local_stream->GetAudioTracks()) {
1092 RemoveAudioTrack(track.get(), local_stream);
1093 }
1094 for (const auto& track : local_stream->GetVideoTracks()) {
1095 RemoveVideoTrack(track.get(), local_stream);
1096 }
deadbeefab9b2d12015-10-14 11:33:11 -07001097 }
deadbeefab9b2d12015-10-14 11:33:11 -07001098 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001099 stream_observers_.erase(
1100 std::remove_if(
1101 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001102 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001103 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001104 }),
1105 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 if (IsClosed()) {
1108 return;
1109 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 observer_->OnRenegotiationNeeded();
1111}
1112
deadbeefe1f9d832016-01-14 15:35:42 -08001113rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1114 MediaStreamTrackInterface* track,
1115 std::vector<MediaStreamInterface*> streams) {
1116 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001117 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001118 for (auto* stream : streams) {
1119 if (!stream) {
1120 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1121 return nullptr;
1122 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001123 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001124 }
Seth Hampson845e8782018-03-02 11:34:10 -08001125 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001126 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001127 return nullptr;
1128 }
Steve Antonf9381f02017-12-14 10:23:57 -08001129 return sender_or_error.MoveValue();
1130}
1131
Steve Anton2d6c76a2018-01-05 17:10:52 -08001132RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001133 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001134 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001135 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001136 if (!track) {
1137 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1138 }
1139 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1140 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1141 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1142 "Track has invalid kind: " + track->kind());
1143 }
Steve Antonf9381f02017-12-14 10:23:57 -08001144 if (IsClosed()) {
1145 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1146 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001147 }
Steve Anton4171afb2017-11-20 10:20:22 -08001148 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001149 LOG_AND_RETURN_ERROR(
1150 RTCErrorType::INVALID_PARAMETER,
1151 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001152 }
Steve Antonf9381f02017-12-14 10:23:57 -08001153 auto sender_or_error =
Seth Hampson15502922018-03-26 10:06:46 -07001154 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1155 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (sender_or_error.ok()) {
1157 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001158 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001159 }
1160 return sender_or_error;
1161}
deadbeefe1f9d832016-01-14 15:35:42 -08001162
Steve Antonf9381f02017-12-14 10:23:57 -08001163RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1164PeerConnection::AddTrackPlanB(
1165 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001166 const std::vector<std::string>& stream_ids) {
Seth Hampson15502922018-03-26 10:06:46 -07001167 if (stream_ids.size() > 1u) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1169 "AddTrack with more than one stream is not "
1170 "supported with Plan B semantics.");
1171 }
1172 std::vector<std::string> adjusted_stream_ids = stream_ids;
1173 if (adjusted_stream_ids.empty()) {
1174 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1175 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001176 cricket::MediaType media_type =
1177 (track->kind() == MediaStreamTrackInterface::kAudioKind
1178 ? cricket::MEDIA_TYPE_AUDIO
1179 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson15502922018-03-26 10:06:46 -07001180 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001181 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001182 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001183 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001184 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07001185 FindSenderInfo(local_audio_sender_infos_, track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001186 if (sender_info) {
1187 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001188 }
Steve Antonf9381f02017-12-14 10:23:57 -08001189 } else {
1190 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001191 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001192 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001193 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07001194 FindSenderInfo(local_video_sender_infos_, track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001195 if (sender_info) {
1196 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001197 }
deadbeefe1f9d832016-01-14 15:35:42 -08001198 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001199 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001200}
deadbeefe1f9d832016-01-14 15:35:42 -08001201
Steve Antonf9381f02017-12-14 10:23:57 -08001202RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1203PeerConnection::AddTrackUnifiedPlan(
1204 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001205 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001206 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1207 if (transceiver) {
1208 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001209 transceiver->internal()->set_direction(
1210 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001211 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001212 transceiver->internal()->set_direction(
1213 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001215 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001216 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001217 } else {
1218 cricket::MediaType media_type =
1219 (track->kind() == MediaStreamTrackInterface::kAudioKind
1220 ? cricket::MEDIA_TYPE_AUDIO
1221 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001222 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001223 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1224 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001225 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001226 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001227 }
Steve Antonf9381f02017-12-14 10:23:57 -08001228 return transceiver->sender();
1229}
1230
1231rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1232PeerConnection::FindFirstTransceiverForAddedTrack(
1233 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1234 RTC_DCHECK(track);
1235 for (auto transceiver : transceivers_) {
1236 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001237 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001238 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001239 !transceiver->internal()->has_ever_been_used_to_send() &&
1240 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001241 return transceiver;
1242 }
1243 }
1244 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001245}
1246
1247bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1248 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001249 return RemoveTrackInternal(sender).ok();
1250}
1251
1252RTCError PeerConnection::RemoveTrackInternal(
1253 rtc::scoped_refptr<RtpSenderInterface> sender) {
1254 if (!sender) {
1255 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1256 }
deadbeefe1f9d832016-01-14 15:35:42 -08001257 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001258 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1259 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001260 }
Steve Antonf9381f02017-12-14 10:23:57 -08001261 if (IsUnifiedPlan()) {
1262 auto transceiver = FindTransceiverBySender(sender);
1263 if (!transceiver || !sender->track()) {
1264 return RTCError::OK();
1265 }
1266 sender->SetTrack(nullptr);
1267 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001268 transceiver->internal()->set_direction(
1269 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001270 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001271 transceiver->internal()->set_direction(
1272 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001273 }
Steve Anton4171afb2017-11-20 10:20:22 -08001274 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001275 bool removed;
1276 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1277 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1278 } else {
1279 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1280 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1281 }
1282 if (!removed) {
1283 LOG_AND_RETURN_ERROR(
1284 RTCErrorType::INVALID_PARAMETER,
1285 "Couldn't find sender " + sender->id() + " to remove.");
1286 }
Steve Anton4171afb2017-11-20 10:20:22 -08001287 }
deadbeefe1f9d832016-01-14 15:35:42 -08001288 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001289 return RTCError::OK();
1290}
1291
1292rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1293PeerConnection::FindTransceiverBySender(
1294 rtc::scoped_refptr<RtpSenderInterface> sender) {
1295 for (auto transceiver : transceivers_) {
1296 if (transceiver->sender() == sender) {
1297 return transceiver;
1298 }
1299 }
1300 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001301}
1302
Steve Anton9158ef62017-11-27 13:01:52 -08001303RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1304PeerConnection::AddTransceiver(
1305 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1306 return AddTransceiver(track, RtpTransceiverInit());
1307}
1308
1309RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1310PeerConnection::AddTransceiver(
1311 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1312 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001313 RTC_CHECK(IsUnifiedPlan())
1314 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001315 if (!track) {
1316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1317 }
1318 cricket::MediaType media_type;
1319 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1320 media_type = cricket::MEDIA_TYPE_AUDIO;
1321 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1322 media_type = cricket::MEDIA_TYPE_VIDEO;
1323 } else {
1324 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1325 "Track kind is not audio or video");
1326 }
1327 return AddTransceiver(media_type, track, init);
1328}
1329
1330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1332 return AddTransceiver(media_type, RtpTransceiverInit());
1333}
1334
1335RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1336PeerConnection::AddTransceiver(cricket::MediaType media_type,
1337 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001338 RTC_CHECK(IsUnifiedPlan())
1339 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001340 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1341 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1343 "media type is not audio or video");
1344 }
1345 return AddTransceiver(media_type, nullptr, init);
1346}
1347
1348RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1349PeerConnection::AddTransceiver(
1350 cricket::MediaType media_type,
1351 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001352 const RtpTransceiverInit& init,
1353 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001354 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1355 media_type == cricket::MEDIA_TYPE_VIDEO));
1356 if (track) {
1357 RTC_DCHECK_EQ(media_type,
1358 (track->kind() == MediaStreamTrackInterface::kAudioKind
1359 ? cricket::MEDIA_TYPE_AUDIO
1360 : cricket::MEDIA_TYPE_VIDEO));
1361 }
1362
1363 // TODO(bugs.webrtc.org/7600): Verify init.
1364
Seth Hampson15502922018-03-26 10:06:46 -07001365 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001366 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1367 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1368 transceiver->internal()->set_direction(init.direction);
1369
Steve Anton22da89f2018-01-25 13:58:07 -08001370 if (fire_callback) {
1371 observer_->OnRenegotiationNeeded();
1372 }
Steve Antonf9381f02017-12-14 10:23:57 -08001373
1374 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1375}
1376
Steve Anton02ee47c2018-01-10 16:26:06 -08001377rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1378PeerConnection::CreateSender(
1379 cricket::MediaType media_type,
1380 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001381 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001382 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001383 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1384 RTC_DCHECK(!track ||
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1386 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1387 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001388 new AudioRtpSender(worker_thread(),
1389 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001390 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001391 } else {
1392 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1393 RTC_DCHECK(!track ||
1394 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1395 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1396 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001397 new VideoRtpSender(worker_thread(),
1398 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001399 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001400 }
Seth Hampson845e8782018-03-02 11:34:10 -08001401 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001402 return sender;
1403}
1404
1405rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1406PeerConnection::CreateReceiver(cricket::MediaType media_type,
1407 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001408 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1409 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001410 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001411 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001412 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001413 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001414 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001415 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001416 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1417 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001418 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001419 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 return receiver;
1421}
1422
1423rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1424PeerConnection::CreateAndAddTransceiver(
1425 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1426 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1427 receiver) {
1428 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1429 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001430 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001431 transceiver->internal()->SignalNegotiationNeeded.connect(
1432 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001433 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001434}
1435
Steve Anton52d86772018-02-20 15:48:12 -08001436void PeerConnection::OnNegotiationNeeded() {
1437 RTC_DCHECK_RUN_ON(signaling_thread());
1438 RTC_DCHECK(!IsClosed());
1439 observer_->OnRenegotiationNeeded();
1440}
1441
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001442rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001443 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001444 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001445 if (IsClosed()) {
1446 return nullptr;
1447 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001449 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001450 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 }
Steve Anton4171afb2017-11-20 10:20:22 -08001452 auto track_sender = FindSenderForTrack(track);
1453 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001454 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001455 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 }
1457
Steve Anton4171afb2017-11-20 10:20:22 -08001458 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459}
1460
deadbeeffac06552015-11-25 11:26:01 -08001461rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001462 const std::string& kind,
1463 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001464 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1465 "Plan SdpSemantics. Please use AddTransceiver "
1466 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001467 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001468 if (IsClosed()) {
1469 return nullptr;
1470 }
Steve Anton4171afb2017-11-20 10:20:22 -08001471
Seth Hampson15502922018-03-26 10:06:46 -07001472 // Internally we need to have one stream with Plan B semantics, so we
1473 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001474 std::vector<std::string> stream_ids;
Seth Hampson15502922018-03-26 10:06:46 -07001475 if (stream_id.empty()) {
1476 stream_ids.push_back(rtc::CreateRandomUuid());
1477 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001478 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001479 }
1480
Steve Anton4171afb2017-11-20 10:20:22 -08001481 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001482 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001483 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001484 auto* audio_sender =
1485 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001486 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001487 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001488 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001489 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001490 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001491 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001492 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001493 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001494 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001496 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001497 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001498 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001499 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001500 }
Steve Anton4171afb2017-11-20 10:20:22 -08001501
deadbeefe1f9d832016-01-14 15:35:42 -08001502 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001503}
1504
deadbeef70ab1a12015-09-28 16:53:55 -07001505std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1506 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001507 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001508 for (auto sender : GetSendersInternal()) {
1509 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001510 }
1511 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001512}
1513
Steve Anton4171afb2017-11-20 10:20:22 -08001514std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1515PeerConnection::GetSendersInternal() const {
1516 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1517 all_senders;
1518 for (auto transceiver : transceivers_) {
1519 auto senders = transceiver->internal()->senders();
1520 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1521 }
1522 return all_senders;
1523}
1524
deadbeef70ab1a12015-09-28 16:53:55 -07001525std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1526PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001527 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001528 for (const auto& receiver : GetReceiversInternal()) {
1529 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001530 }
1531 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001532}
1533
Steve Anton4171afb2017-11-20 10:20:22 -08001534std::vector<
1535 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1536PeerConnection::GetReceiversInternal() const {
1537 std::vector<
1538 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1539 all_receivers;
1540 for (auto transceiver : transceivers_) {
1541 auto receivers = transceiver->internal()->receivers();
1542 all_receivers.insert(all_receivers.end(), receivers.begin(),
1543 receivers.end());
1544 }
1545 return all_receivers;
1546}
1547
Steve Anton9158ef62017-11-27 13:01:52 -08001548std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1549PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001550 RTC_CHECK(IsUnifiedPlan())
1551 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001552 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1553 for (auto transceiver : transceivers_) {
1554 all_transceivers.push_back(transceiver);
1555 }
1556 return all_transceivers;
1557}
1558
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001560 MediaStreamTrackInterface* track,
1561 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001562 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001563 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001564 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566 return false;
1567 }
1568
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001569 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001570 // The StatsCollector is used to tell if a track is valid because it may
1571 // remember tracks that the PeerConnection previously removed.
1572 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001573 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1574 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001575 return false;
1576 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001577 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001578 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 return true;
1580}
1581
hbos74e1a4f2016-09-15 23:33:01 -07001582void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001583 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001584 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001585 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001586 stats_collector_->GetStatsReport(callback);
1587}
1588
Henrik Boström1df1bf82018-03-20 13:24:20 +01001589void PeerConnection::GetStats(
1590 rtc::scoped_refptr<RtpSenderInterface> selector,
1591 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1592 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1593 RTC_DCHECK(callback);
1594 RTC_DCHECK(stats_collector_);
1595 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1596 if (selector) {
1597 for (const auto& proxy_transceiver : transceivers_) {
1598 for (const auto& proxy_sender :
1599 proxy_transceiver->internal()->senders()) {
1600 if (proxy_sender == selector) {
1601 internal_sender = proxy_sender->internal();
1602 break;
1603 }
1604 }
1605 if (internal_sender)
1606 break;
1607 }
1608 }
1609 // If there is no |internal_sender| then |selector| is either null or does not
1610 // belong to the PeerConnection (in Plan B, senders can be removed from the
1611 // PeerConnection). This means that "all the stats objects representing the
1612 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1613 // produces an empty stats report.
1614 stats_collector_->GetStatsReport(internal_sender, callback);
1615}
1616
1617void PeerConnection::GetStats(
1618 rtc::scoped_refptr<RtpReceiverInterface> selector,
1619 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1620 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1621 RTC_DCHECK(callback);
1622 RTC_DCHECK(stats_collector_);
1623 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1624 if (selector) {
1625 for (const auto& proxy_transceiver : transceivers_) {
1626 for (const auto& proxy_receiver :
1627 proxy_transceiver->internal()->receivers()) {
1628 if (proxy_receiver == selector) {
1629 internal_receiver = proxy_receiver->internal();
1630 break;
1631 }
1632 }
1633 if (internal_receiver)
1634 break;
1635 }
1636 }
1637 // If there is no |internal_receiver| then |selector| is either null or does
1638 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1639 // the PeerConnection). This means that "all the stats objects representing
1640 // the selector" is an empty set. Invoking GetStatsReport() with a null
1641 // selector produces an empty stats report.
1642 stats_collector_->GetStatsReport(internal_receiver, callback);
1643}
1644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1646 return signaling_state_;
1647}
1648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001649PeerConnectionInterface::IceConnectionState
1650PeerConnection::ice_connection_state() {
1651 return ice_connection_state_;
1652}
1653
1654PeerConnectionInterface::IceGatheringState
1655PeerConnection::ice_gathering_state() {
1656 return ice_gathering_state_;
1657}
1658
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001659rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001660PeerConnection::CreateDataChannel(
1661 const std::string& label,
1662 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001663 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001664
deadbeefab9b2d12015-10-14 11:33:11 -07001665 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001666
kwibergd1fe2812016-04-27 06:47:29 -07001667 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001668 if (config) {
1669 internal_config.reset(new InternalDataChannelInit(*config));
1670 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001671 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001672 InternalCreateDataChannel(label, internal_config.get()));
1673 if (!channel.get()) {
1674 return nullptr;
1675 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001677 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1678 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001679 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001680 observer_->OnRenegotiationNeeded();
1681 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 return DataChannelProxy::Create(signaling_thread(), channel.get());
1684}
1685
1686void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1687 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001688 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001689
zhihuang1c378ed2017-08-17 14:10:50 -07001690 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1691 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1692 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1693 // compares the mandatory fields parsed with the mandatory fields added in the
1694 // |constraints| and some downstream applications might create offers with
1695 // mandatory fields which would not be parsed in the helper method. For
1696 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1697 // |constraints| as a mandatory field but it is not parsed.
1698 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001699
zhihuang1c378ed2017-08-17 14:10:50 -07001700 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001701}
1702
1703void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1704 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001705 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001706
nisse7ce109a2017-01-31 00:57:56 -08001707 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001708 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001709 return;
1710 }
deadbeefab9b2d12015-10-14 11:33:11 -07001711
Steve Anton8d3444d2017-10-20 15:30:51 -07001712 if (IsClosed()) {
1713 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001714 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001715 PostCreateSessionDescriptionFailure(
1716 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001717 return;
1718 }
1719
zhihuang1c378ed2017-08-17 14:10:50 -07001720 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001721 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001722 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001723 PostCreateSessionDescriptionFailure(
1724 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001725 return;
1726 }
1727
Steve Anton22da89f2018-01-25 13:58:07 -08001728 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1729 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1730 if (IsUnifiedPlan()) {
1731 RTCError error = HandleLegacyOfferOptions(options);
1732 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001733 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001734 return;
1735 }
1736 }
1737
zhihuang1c378ed2017-08-17 14:10:50 -07001738 cricket::MediaSessionOptions session_options;
1739 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001740 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741}
1742
Steve Anton22da89f2018-01-25 13:58:07 -08001743RTCError PeerConnection::HandleLegacyOfferOptions(
1744 const RTCOfferAnswerOptions& options) {
1745 RTC_DCHECK(IsUnifiedPlan());
1746
1747 if (options.offer_to_receive_audio == 0) {
1748 RemoveRecvDirectionFromReceivingTransceiversOfType(
1749 cricket::MEDIA_TYPE_AUDIO);
1750 } else if (options.offer_to_receive_audio == 1) {
1751 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1752 } else if (options.offer_to_receive_audio > 1) {
1753 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1754 "offer_to_receive_audio > 1 is not supported.");
1755 }
1756
1757 if (options.offer_to_receive_video == 0) {
1758 RemoveRecvDirectionFromReceivingTransceiversOfType(
1759 cricket::MEDIA_TYPE_VIDEO);
1760 } else if (options.offer_to_receive_video == 1) {
1761 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1762 } else if (options.offer_to_receive_video > 1) {
1763 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1764 "offer_to_receive_video > 1 is not supported.");
1765 }
1766
1767 return RTCError::OK();
1768}
1769
1770void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1771 cricket::MediaType media_type) {
1772 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1773 transceiver->internal()->set_direction(
1774 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1775 }
1776}
1777
1778void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1779 cricket::MediaType media_type) {
1780 if (GetReceivingTransceiversOfType(media_type).empty()) {
1781 RtpTransceiverInit init;
1782 init.direction = RtpTransceiverDirection::kRecvOnly;
1783 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1784 }
1785}
1786
1787std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1788PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1789 std::vector<
1790 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1791 receiving_transceivers;
1792 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001793 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001794 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1795 receiving_transceivers.push_back(transceiver);
1796 }
1797 }
1798 return receiving_transceivers;
1799}
1800
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801void PeerConnection::CreateAnswer(
1802 CreateSessionDescriptionObserver* observer,
1803 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001804 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001805
nisse7ce109a2017-01-31 00:57:56 -08001806 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001807 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001808 return;
1809 }
deadbeefab9b2d12015-10-14 11:33:11 -07001810
zhihuang1c378ed2017-08-17 14:10:50 -07001811 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1812 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1813 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001814 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001815 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001816 PostCreateSessionDescriptionFailure(
1817 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001818 return;
1819 }
1820
Steve Anton8d3444d2017-10-20 15:30:51 -07001821 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001822}
1823
1824void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1825 const RTCOfferAnswerOptions& options) {
1826 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001827 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001828 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001829 return;
1830 }
1831
Steve Antondffead82018-02-06 10:31:29 -08001832 if (!(signaling_state_ == kHaveRemoteOffer ||
1833 signaling_state_ == kHaveLocalPrAnswer)) {
1834 std::string error =
1835 "PeerConnection cannot create an answer in a state other than "
1836 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001837 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001838 PostCreateSessionDescriptionFailure(
1839 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001840 return;
1841 }
1842
Steve Antondffead82018-02-06 10:31:29 -08001843 // The remote description should be set if we're in the right state.
1844 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001845
Steve Anton22da89f2018-01-25 13:58:07 -08001846 if (IsUnifiedPlan()) {
1847 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1848 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1849 "supported with Unified Plan semantics. Use the "
1850 "RtpTransceiver API instead.";
1851 }
1852 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1853 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1854 "supported with Unified Plan semantics. Use the "
1855 "RtpTransceiver API instead.";
1856 }
1857 }
1858
htaa2a49d92016-03-04 02:51:39 -08001859 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001860 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001861
Steve Antond25da372017-11-06 14:50:29 -08001862 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001863}
1864
1865void PeerConnection::SetLocalDescription(
1866 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001867 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001868 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001869
Steve Anton80dd7b52018-02-16 17:08:42 -08001870 // The SetLocalDescription contract is that we take ownership of the session
1871 // description regardless of the outcome, so wrap it in a unique_ptr right
1872 // away. Ideally, SetLocalDescription's signature will be changed to take the
1873 // description as a unique_ptr argument to formalize this agreement.
1874 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1875
nisse7ce109a2017-01-31 00:57:56 -08001876 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001877 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 return;
1879 }
Steve Anton8a006912017-12-04 15:25:56 -08001880
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001882 PostSetSessionDescriptionFailure(
1883 observer,
1884 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885 return;
1886 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001887
Steve Anton80dd7b52018-02-16 17:08:42 -08001888 // If a session error has occurred the PeerConnection is in a possibly
1889 // inconsistent state so fail right away.
1890 if (session_error() != SessionError::kNone) {
1891 std::string error_message = GetSessionErrorMsg();
1892 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001893 PostSetSessionDescriptionFailure(
1894 observer,
1895 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001896 return;
1897 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001898
Steve Anton80dd7b52018-02-16 17:08:42 -08001899 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1900 if (!error.ok()) {
1901 std::string error_message = GetSetDescriptionErrorMessage(
1902 cricket::CS_LOCAL, desc->GetType(), error);
1903 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001904 PostSetSessionDescriptionFailure(
1905 observer,
1906 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001907 return;
1908 }
1909
1910 // Grab the description type before moving ownership to ApplyLocalDescription,
1911 // which may destroy it before returning.
1912 const SdpType type = desc->GetType();
1913
1914 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001915 // |desc| may be destroyed at this point.
1916
1917 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001918 // If ApplyLocalDescription fails, the PeerConnection could be in an
1919 // inconsistent state, so act conservatively here and set the session error
1920 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1921 SetSessionError(SessionError::kContent, error.message());
1922 std::string error_message =
1923 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1924 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001925 PostSetSessionDescriptionFailure(
1926 observer,
1927 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001928 return;
1929 }
Steve Anton8a006912017-12-04 15:25:56 -08001930 RTC_DCHECK(local_description());
1931
1932 PostSetSessionDescriptionSuccess(observer);
1933
1934 // According to JSEP, after setLocalDescription, changing the candidate pool
1935 // size is not allowed, and changing the set of ICE servers will not result
1936 // in new candidates being gathered.
1937 port_allocator_->FreezeCandidatePool();
1938
1939 // MaybeStartGathering needs to be called after posting
1940 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1941 // before signaling that SetLocalDescription completed.
1942 transport_controller_->MaybeStartGathering();
1943
Steve Antona3a92c22017-12-07 10:27:41 -08001944 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001945 // TODO(deadbeef): We already had to hop to the network thread for
1946 // MaybeStartGathering...
1947 network_thread()->Invoke<void>(
1948 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1949 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001950 // Make UMA notes about what was agreed to.
1951 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001952 }
1953}
1954
1955RTCError PeerConnection::ApplyLocalDescription(
1956 std::unique_ptr<SessionDescriptionInterface> desc) {
1957 RTC_DCHECK_RUN_ON(signaling_thread());
1958 RTC_DCHECK(desc);
1959
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 // Update stats here so that we have the most recent stats for tracks and
1961 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001962 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001963
1964 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001965 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001966 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001967 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001968 if (*initial_offerer_) {
1969 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1970 } else {
1971 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1972 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 }
Steve Anton8a006912017-12-04 15:25:56 -08001974
Steve Antondcc3c022017-12-22 16:02:54 -08001975 // Take a reference to the old local description since it's used below to
1976 // compare against the new local description. When setting the new local
1977 // description, grab ownership of the replaced session description in case it
1978 // is the same as |old_local_description|, to keep it alive for the duration
1979 // of the method.
1980 const SessionDescriptionInterface* old_local_description =
1981 local_description();
1982 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001983 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001984 replaced_local_description = pending_local_description_
1985 ? std::move(pending_local_description_)
1986 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001987 current_local_description_ = std::move(desc);
1988 pending_local_description_ = nullptr;
1989 current_remote_description_ = std::move(pending_remote_description_);
1990 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001991 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001992 pending_local_description_ = std::move(desc);
1993 }
1994 // The session description to apply now must be accessed by
1995 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001996 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001997
Steve Antondcc3c022017-12-22 16:02:54 -08001998 if (IsUnifiedPlan()) {
1999 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002000 cricket::CS_LOCAL, *local_description(), old_local_description,
2001 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002002 if (!error.ok()) {
2003 return error;
2004 }
Steve Antondcc3c022017-12-22 16:02:54 -08002005 for (auto transceiver : transceivers_) {
2006 const ContentInfo* content =
2007 FindMediaSectionForTransceiver(transceiver, local_description());
2008 if (!content) {
2009 continue;
2010 }
2011 const MediaContentDescription* media_desc = content->media_description();
2012 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2013 transceiver->internal()->set_current_direction(media_desc->direction());
2014 }
2015 if (content->rejected && !transceiver->stopped()) {
2016 transceiver->Stop();
2017 }
2018 }
2019 } else {
2020 // Transport and Media channels will be created only when offer is set.
2021 if (type == SdpType::kOffer) {
2022 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2023 // description is applied. Restore back to old description.
2024 RTCError error = CreateChannels(*local_description()->description());
2025 if (!error.ok()) {
2026 return error;
2027 }
2028 }
Steve Anton8a006912017-12-04 15:25:56 -08002029
Steve Antondcc3c022017-12-22 16:02:54 -08002030 // Remove unused channels if MediaContentDescription is rejected.
2031 RemoveUnusedChannels(local_description()->description());
2032 }
Steve Anton8a006912017-12-04 15:25:56 -08002033
Steve Anton80dd7b52018-02-16 17:08:42 -08002034 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08002035 if (!error.ok()) {
2036 return error;
2037 }
Steve Antondcc3c022017-12-22 16:02:54 -08002038
Steve Anton8a006912017-12-04 15:25:56 -08002039 if (remote_description()) {
2040 // Now that we have a local description, we can push down remote candidates.
2041 UseCandidatesInSessionDescription(remote_description());
2042 }
2043
2044 pending_ice_restarts_.clear();
2045 if (session_error() != SessionError::kNone) {
2046 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2047 }
2048
deadbeefab9b2d12015-10-14 11:33:11 -07002049 // If setting the description decided our SSL role, allocate any necessary
2050 // SCTP sids.
2051 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002052 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002053 AllocateSctpSids(role);
2054 }
2055
Steve Antond3679212018-01-17 17:41:02 -08002056 if (IsUnifiedPlan()) {
2057 for (auto transceiver : transceivers_) {
2058 const ContentInfo* content =
2059 FindMediaSectionForTransceiver(transceiver, local_description());
2060 if (!content) {
2061 continue;
2062 }
2063 if (content->rejected && !transceiver->stopped()) {
2064 transceiver->Stop();
2065 }
Steve Anton74255ff2018-01-24 18:32:57 -08002066 const auto& streams = content->media_description()->streams();
2067 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002068 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002069 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002070 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002071 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002072 }
2073 }
2074 } else {
2075 // Plan B semantics.
2076
Steve Antondcc3c022017-12-22 16:02:54 -08002077 // Update state and SSRC of local MediaStreams and DataChannels based on the
2078 // local session description.
2079 const cricket::ContentInfo* audio_content =
2080 GetFirstAudioContent(local_description()->description());
2081 if (audio_content) {
2082 if (audio_content->rejected) {
2083 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2084 } else {
2085 const cricket::AudioContentDescription* audio_desc =
2086 audio_content->media_description()->as_audio();
2087 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2088 }
deadbeeffaac4972015-11-12 15:33:07 -08002089 }
deadbeefab9b2d12015-10-14 11:33:11 -07002090
Steve Antondcc3c022017-12-22 16:02:54 -08002091 const cricket::ContentInfo* video_content =
2092 GetFirstVideoContent(local_description()->description());
2093 if (video_content) {
2094 if (video_content->rejected) {
2095 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2096 } else {
2097 const cricket::VideoContentDescription* video_desc =
2098 video_content->media_description()->as_video();
2099 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2100 }
deadbeeffaac4972015-11-12 15:33:07 -08002101 }
deadbeefab9b2d12015-10-14 11:33:11 -07002102 }
2103
2104 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002105 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002106 if (data_content) {
2107 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002108 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002109 if (rtc::starts_with(data_desc->protocol().data(),
2110 cricket::kMediaProtocolRtpPrefix)) {
2111 UpdateLocalRtpDataChannels(data_desc->streams());
2112 }
2113 }
2114
Steve Anton8a006912017-12-04 15:25:56 -08002115 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002116}
2117
2118void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002119 SetSessionDescriptionObserver* observer,
2120 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002121 SetRemoteDescription(
2122 std::unique_ptr<SessionDescriptionInterface>(desc),
2123 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2124 new SetRemoteDescriptionObserverAdapter(this, observer)));
2125}
2126
2127void PeerConnection::SetRemoteDescription(
2128 std::unique_ptr<SessionDescriptionInterface> desc,
2129 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002130 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002131
nisse7ce109a2017-01-31 00:57:56 -08002132 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002133 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 return;
2135 }
Steve Anton8a006912017-12-04 15:25:56 -08002136
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002138 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002139 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 return;
2141 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002142
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 // If a session error has occurred the PeerConnection is in a possibly
2144 // inconsistent state so fail right away.
2145 if (session_error() != SessionError::kNone) {
2146 std::string error_message = GetSessionErrorMsg();
2147 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2148 observer->OnSetRemoteDescriptionComplete(
2149 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2150 return;
2151 }
Steve Anton71439a62018-02-15 11:53:06 -08002152
Steve Anton80dd7b52018-02-16 17:08:42 -08002153 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002154 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002155 std::string error_message = GetSetDescriptionErrorMessage(
2156 cricket::CS_REMOTE, desc->GetType(), error);
2157 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002158 observer->OnSetRemoteDescriptionComplete(
2159 RTCError(error.type(), std::move(error_message)));
2160 return;
2161 }
Steve Anton71439a62018-02-15 11:53:06 -08002162
Steve Anton80dd7b52018-02-16 17:08:42 -08002163 // Grab the description type before moving ownership to
2164 // ApplyRemoteDescription, which may destroy it before returning.
2165 const SdpType type = desc->GetType();
2166
2167 error = ApplyRemoteDescription(std::move(desc));
2168 // |desc| may be destroyed at this point.
2169
2170 if (!error.ok()) {
2171 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2172 // inconsistent state, so act conservatively here and set the session error
2173 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2174 SetSessionError(SessionError::kContent, error.message());
2175 std::string error_message =
2176 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2177 RTC_LOG(LS_ERROR) << error_message;
2178 observer->OnSetRemoteDescriptionComplete(
2179 RTCError(error.type(), std::move(error_message)));
2180 return;
2181 }
2182 RTC_DCHECK(remote_description());
2183
Steve Anton8e20f172018-03-06 10:55:04 -08002184 if (type == SdpType::kOffer) {
2185 // Report to UMA the format of the received offer.
2186 ReportSdpFormatReceived(*remote_description());
2187 }
2188
Steve Anton80dd7b52018-02-16 17:08:42 -08002189 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002190 // TODO(deadbeef): We already had to hop to the network thread for
2191 // MaybeStartGathering...
2192 network_thread()->Invoke<void>(
2193 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2194 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002195 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002196 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002197 }
2198
2199 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2200}
2201
2202RTCError PeerConnection::ApplyRemoteDescription(
2203 std::unique_ptr<SessionDescriptionInterface> desc) {
2204 RTC_DCHECK_RUN_ON(signaling_thread());
2205 RTC_DCHECK(desc);
2206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 // Update stats here so that we have the most recent stats for tracks and
2208 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002209 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002210
Steve Antondcc3c022017-12-22 16:02:54 -08002211 // Take a reference to the old remote description since it's used below to
2212 // compare against the new remote description. When setting the new remote
2213 // description, grab ownership of the replaced session description in case it
2214 // is the same as |old_remote_description|, to keep it alive for the duration
2215 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002216 const SessionDescriptionInterface* old_remote_description =
2217 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002218 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002219 SdpType type = desc->GetType();
2220 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002221 replaced_remote_description = pending_remote_description_
2222 ? std::move(pending_remote_description_)
2223 : std::move(current_remote_description_);
2224 current_remote_description_ = std::move(desc);
2225 pending_remote_description_ = nullptr;
2226 current_local_description_ = std::move(pending_local_description_);
2227 } else {
2228 replaced_remote_description = std::move(pending_remote_description_);
2229 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 }
Steve Anton8a006912017-12-04 15:25:56 -08002231 // The session description to apply now must be accessed by
2232 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002233 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234
Steve Anton8a006912017-12-04 15:25:56 -08002235 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002236 if (IsUnifiedPlan()) {
2237 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002238 cricket::CS_REMOTE, *remote_description(), local_description(),
2239 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002240 if (!error.ok()) {
2241 return error;
2242 }
Steve Antondcc3c022017-12-22 16:02:54 -08002243 } else {
2244 if (type == SdpType::kOffer) {
2245 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2246 // description is applied. Restore back to old description.
2247 RTCError error = CreateChannels(*remote_description()->description());
2248 if (!error.ok()) {
2249 return error;
2250 }
2251 }
Steve Anton8a006912017-12-04 15:25:56 -08002252
Steve Antondcc3c022017-12-22 16:02:54 -08002253 // Remove unused channels if MediaContentDescription is rejected.
2254 RemoveUnusedChannels(remote_description()->description());
2255 }
Steve Anton8a006912017-12-04 15:25:56 -08002256
2257 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2258 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002259 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002260 if (!error.ok()) {
2261 return error;
2262 }
2263
2264 if (local_description() &&
2265 !UseCandidatesInSessionDescription(remote_description())) {
2266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2267 }
2268
2269 if (old_remote_description) {
2270 for (const cricket::ContentInfo& content :
2271 old_remote_description->description()->contents()) {
2272 // Check if this new SessionDescription contains new ICE ufrag and
2273 // password that indicates the remote peer requests an ICE restart.
2274 // TODO(deadbeef): When we start storing both the current and pending
2275 // remote description, this should reset pending_ice_restarts and compare
2276 // against the current description.
2277 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2278 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002279 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002280 pending_ice_restarts_.insert(content.name);
2281 }
2282 } else {
2283 // We retain all received candidates only if ICE is not restarted.
2284 // When ICE is restarted, all previous candidates belong to an old
2285 // generation and should not be kept.
2286 // TODO(deadbeef): This goes against the W3C spec which says the remote
2287 // description should only contain candidates from the last set remote
2288 // description plus any candidates added since then. We should remove
2289 // this once we're sure it won't break anything.
2290 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2291 old_remote_description, content.name, mutable_remote_description());
2292 }
2293 }
2294 }
2295
2296 if (session_error() != SessionError::kNone) {
2297 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2298 }
2299
2300 // Set the the ICE connection state to connecting since the connection may
2301 // become writable with peer reflexive candidates before any remote candidate
2302 // is signaled.
2303 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2304 // is to have a new signal the indicates a change in checking state from the
2305 // transport and expose a new checking() member from transport that can be
2306 // read to determine the current checking state. The existing SignalConnecting
2307 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002308 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002309 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2310 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2311 }
2312
deadbeefab9b2d12015-10-14 11:33:11 -07002313 // If setting the description decided our SSL role, allocate any necessary
2314 // SCTP sids.
2315 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002316 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002317 AllocateSctpSids(role);
2318 }
2319
Steve Antondcc3c022017-12-22 16:02:54 -08002320 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002321 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2322 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002323 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002324 for (auto transceiver : transceivers_) {
2325 const ContentInfo* content =
2326 FindMediaSectionForTransceiver(transceiver, remote_description());
2327 if (!content) {
2328 continue;
2329 }
2330 const MediaContentDescription* media_desc = content->media_description();
2331 RtpTransceiverDirection local_direction =
2332 RtpTransceiverDirectionReversed(media_desc->direction());
2333 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2334 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2335 // transceiver's current direction is neither sendrecv nor recvonly,
2336 // process the addition of a remote track for the media description.
Seth Hampson15502922018-03-26 10:06:46 -07002337 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002338 if (!media_desc->streams().empty()) {
Seth Hampson15502922018-03-26 10:06:46 -07002339 // TODO(bugs.webrtc.org/7932): Currently stream ids are all populated
2340 // within StreamParams. When they are updated to be stored within the
2341 // MediaContentDescription, change the logic here.
Steve Anton5a26a3a2018-02-28 11:38:47 -08002342 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002343 if (!stream_params.stream_ids().empty()) {
Seth Hampson15502922018-03-26 10:06:46 -07002344 stream_ids = stream_params.stream_ids();
Steve Anton5a26a3a2018-02-28 11:38:47 -08002345 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346 }
Steve Antondcc3c022017-12-22 16:02:54 -08002347 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2348 (!transceiver->current_direction() ||
2349 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002350 *transceiver->current_direction()))) {
Seth Hampson15502922018-03-26 10:06:46 -07002351 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2352 for (const std::string& stream_id : stream_ids) {
2353 rtc::scoped_refptr<MediaStreamInterface> stream =
2354 remote_streams_->find(stream_id);
2355 if (!stream) {
2356 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2357 MediaStream::Create(stream_id));
2358 remote_streams_->AddStream(stream);
2359 added_streams.push_back(stream);
2360 }
2361 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002362 }
Seth Hampson15502922018-03-26 10:06:46 -07002363 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton8b815cd2018-02-16 16:14:42 -08002364 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002365 }
2366 // If direction is sendonly or inactive, and transceiver's current
2367 // direction is neither sendonly nor inactive, process the removal of a
2368 // remote track for the media description.
2369 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002370 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002371 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002372 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002373 }
2374 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2375 transceiver->internal()->set_current_direction(local_direction);
2376 }
2377 if (content->rejected && !transceiver->stopped()) {
2378 transceiver->Stop();
2379 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002380 if (!content->rejected &&
2381 RtpTransceiverDirectionHasRecv(local_direction)) {
2382 // Set ssrc to 0 in the case of an unsignalled ssrc.
2383 uint32_t ssrc = 0;
2384 if (!media_desc->streams().empty()) {
2385 ssrc = media_desc->streams()[0].first_ssrc();
2386 }
2387 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002388 }
Steve Antondcc3c022017-12-22 16:02:54 -08002389 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002390 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002391 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002392 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002393 observer_->OnTrack(transceiver);
2394 observer_->OnAddTrack(transceiver->receiver(),
2395 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002396 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002397 for (auto stream : added_streams) {
2398 observer_->OnAddStream(stream);
2399 }
Steve Antondcc3c022017-12-22 16:02:54 -08002400 }
2401
Henrik Boströmfdb92012017-11-09 19:55:44 +01002402 const cricket::ContentInfo* audio_content =
2403 GetFirstAudioContent(remote_description()->description());
2404 const cricket::ContentInfo* video_content =
2405 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002406 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002407 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002408 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002409 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002410 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002411 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002412
2413 // Check if the descriptions include streams, just in case the peer supports
2414 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002415 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002416 (audio_desc && !audio_desc->streams().empty()) ||
2417 (video_desc && !video_desc->streams().empty())) {
2418 remote_peer_supports_msid_ = true;
2419 }
deadbeefab9b2d12015-10-14 11:33:11 -07002420
2421 // We wait to signal new streams until we finish processing the description,
2422 // since only at that point will new streams have all their tracks.
2423 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2424
Steve Antondcc3c022017-12-22 16:02:54 -08002425 if (!IsUnifiedPlan()) {
2426 // TODO(steveanton): When removing RTP senders/receivers in response to a
2427 // rejected media section, there is some cleanup logic that expects the
2428 // voice/ video channel to still be set. But in this method the voice/video
2429 // channel would have been destroyed by the SetRemoteDescription caller
2430 // above so the cleanup that relies on them fails to run. The RemoveSenders
2431 // calls should be moved to right before the DestroyChannel calls to fix
2432 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002433
Steve Antondcc3c022017-12-22 16:02:54 -08002434 // Find all audio rtp streams and create corresponding remote AudioTracks
2435 // and MediaStreams.
2436 if (audio_content) {
2437 if (audio_content->rejected) {
2438 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2439 } else {
2440 bool default_audio_track_needed =
2441 !remote_peer_supports_msid_ &&
2442 RtpTransceiverDirectionHasSend(audio_desc->direction());
2443 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2444 default_audio_track_needed, audio_desc->type(),
2445 new_streams);
2446 }
deadbeeffaac4972015-11-12 15:33:07 -08002447 }
deadbeefab9b2d12015-10-14 11:33:11 -07002448
Steve Antondcc3c022017-12-22 16:02:54 -08002449 // Find all video rtp streams and create corresponding remote VideoTracks
2450 // and MediaStreams.
2451 if (video_content) {
2452 if (video_content->rejected) {
2453 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2454 } else {
2455 bool default_video_track_needed =
2456 !remote_peer_supports_msid_ &&
2457 RtpTransceiverDirectionHasSend(video_desc->direction());
2458 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2459 default_video_track_needed, video_desc->type(),
2460 new_streams);
2461 }
deadbeeffaac4972015-11-12 15:33:07 -08002462 }
deadbeefab9b2d12015-10-14 11:33:11 -07002463
Steve Antondcc3c022017-12-22 16:02:54 -08002464 // Update the DataChannels with the information from the remote peer.
2465 if (data_desc) {
2466 if (rtc::starts_with(data_desc->protocol().data(),
2467 cricket::kMediaProtocolRtpPrefix)) {
2468 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2469 }
deadbeefab9b2d12015-10-14 11:33:11 -07002470 }
deadbeefab9b2d12015-10-14 11:33:11 -07002471
Steve Antondcc3c022017-12-22 16:02:54 -08002472 // Iterate new_streams and notify the observer about new MediaStreams.
2473 for (size_t i = 0; i < new_streams->count(); ++i) {
2474 MediaStreamInterface* new_stream = new_streams->at(i);
2475 stats_->AddStream(new_stream);
2476 observer_->OnAddStream(
2477 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2478 }
deadbeefab9b2d12015-10-14 11:33:11 -07002479
Steve Antondcc3c022017-12-22 16:02:54 -08002480 UpdateEndedRemoteMediaStreams();
2481 }
deadbeefab9b2d12015-10-14 11:33:11 -07002482
Steve Anton8a006912017-12-04 15:25:56 -08002483 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002484}
2485
Steve Antondcc3c022017-12-22 16:02:54 -08002486RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2487 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002488 const SessionDescriptionInterface& new_session,
2489 const SessionDescriptionInterface* old_local_description,
2490 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002491 RTC_DCHECK(IsUnifiedPlan());
2492
Steve Anton7464fca2018-01-19 11:10:37 -08002493 const cricket::ContentGroup* bundle_group = nullptr;
2494 if (new_session.GetType() == SdpType::kOffer) {
2495 auto bundle_group_or_error =
2496 GetEarlyBundleGroup(*new_session.description());
2497 if (!bundle_group_or_error.ok()) {
2498 return bundle_group_or_error.MoveError();
2499 }
2500 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002501 }
Steve Antondcc3c022017-12-22 16:02:54 -08002502
Steve Antondcc3c022017-12-22 16:02:54 -08002503 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002504 for (size_t i = 0; i < new_contents.size(); ++i) {
2505 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002506 cricket::MediaType media_type = new_content.media_description()->type();
2507 seen_mids_.insert(new_content.name);
2508 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2509 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002510 const cricket::ContentInfo* old_local_content = nullptr;
2511 if (old_local_description &&
2512 i < old_local_description->description()->contents().size()) {
2513 old_local_content =
2514 &old_local_description->description()->contents()[i];
2515 }
2516 const cricket::ContentInfo* old_remote_content = nullptr;
2517 if (old_remote_description &&
2518 i < old_remote_description->description()->contents().size()) {
2519 old_remote_content =
2520 &old_remote_description->description()->contents()[i];
2521 }
Steve Antondcc3c022017-12-22 16:02:54 -08002522 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002523 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2524 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002525 if (!transceiver_or_error.ok()) {
2526 return transceiver_or_error.MoveError();
2527 }
2528 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002529 RTCError error =
2530 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2531 if (!error.ok()) {
2532 return error;
2533 }
2534 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002535 if (GetDataMid() && new_content.name != *GetDataMid()) {
2536 // Ignore all but the first data section.
2537 continue;
2538 }
2539 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2540 if (!error.ok()) {
2541 return error;
2542 }
Steve Antondcc3c022017-12-22 16:02:54 -08002543 } else {
2544 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2545 "Unknown section type.");
2546 }
2547 }
2548
2549 return RTCError::OK();
2550}
2551
2552RTCError PeerConnection::UpdateTransceiverChannel(
2553 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2554 transceiver,
2555 const cricket::ContentInfo& content,
2556 const cricket::ContentGroup* bundle_group) {
2557 RTC_DCHECK(IsUnifiedPlan());
2558 RTC_DCHECK(transceiver);
2559 cricket::BaseChannel* channel = transceiver->internal()->channel();
2560 if (content.rejected) {
2561 if (channel) {
2562 transceiver->internal()->SetChannel(nullptr);
2563 DestroyBaseChannel(channel);
2564 }
2565 } else {
2566 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002567 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002568 channel = CreateVoiceChannel(
2569 content.name,
2570 GetTransportNameForMediaSection(content.name, bundle_group));
2571 } else {
Steve Anton69470252018-02-09 11:43:08 -08002572 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002573 channel = CreateVideoChannel(
2574 content.name,
2575 GetTransportNameForMediaSection(content.name, bundle_group));
2576 }
2577 if (!channel) {
2578 LOG_AND_RETURN_ERROR(
2579 RTCErrorType::INTERNAL_ERROR,
2580 "Failed to create channel for mid=" + content.name);
2581 }
2582 transceiver->internal()->SetChannel(channel);
2583 }
2584 }
2585 return RTCError::OK();
2586}
2587
Steve Antonfa2260d2017-12-28 16:38:23 -08002588RTCError PeerConnection::UpdateDataChannel(
2589 cricket::ContentSource source,
2590 const cricket::ContentInfo& content,
2591 const cricket::ContentGroup* bundle_group) {
2592 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002593 // If data channels are disabled, ignore this media section. CreateAnswer
2594 // will take care of rejecting it.
2595 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002596 }
2597 if (content.rejected) {
2598 DestroyDataChannel();
2599 } else {
2600 if (!rtp_data_channel_ && !sctp_transport_) {
2601 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2602 content.name, bundle_group))) {
2603 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2604 "Failed to create data channel.");
2605 }
2606 }
2607 if (source == cricket::CS_REMOTE) {
2608 const MediaContentDescription* data_desc = content.media_description();
2609 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2610 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2611 }
2612 }
2613 }
2614 return RTCError::OK();
2615}
2616
Steve Antondcc3c022017-12-22 16:02:54 -08002617RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2618PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002619 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002620 size_t mline_index,
2621 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002622 const ContentInfo* old_local_content,
2623 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002624 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002625 // If this is an offer then the m= section might be recycled. If the m=
2626 // section is being recycled (defined as: rejected in the current local or
2627 // remote description and not rejected in new description), dissociate the
2628 // currently associated RtpTransceiver by setting its mid property to null,
2629 // and discard the mapping between the transceiver and its m= section index.
2630 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2631 old_remote_content)) {
2632 // We want to dissociate the transceiver that has the rejected mid.
2633 const std::string& old_mid =
2634 (old_local_content && old_local_content->rejected)
2635 ? old_local_content->name
2636 : old_remote_content->name;
2637 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002638 if (old_transceiver) {
2639 old_transceiver->internal()->set_mid(rtc::nullopt);
2640 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2641 }
2642 }
2643 const MediaContentDescription* media_desc = content.media_description();
2644 auto transceiver = GetAssociatedTransceiver(content.name);
2645 if (source == cricket::CS_LOCAL) {
2646 // Find the RtpTransceiver that corresponds to this m= section, using the
2647 // mapping between transceivers and m= section indices established when
2648 // creating the offer.
2649 if (!transceiver) {
2650 transceiver = GetTransceiverByMLineIndex(mline_index);
2651 }
2652 if (!transceiver) {
2653 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2654 "Unknown transceiver");
2655 }
2656 } else {
2657 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2658 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2659 // of the same type...
2660 if (!transceiver &&
2661 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2662 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2663 }
2664 // If no RtpTransceiver was found in the previous step, create one with a
2665 // recvonly direction.
2666 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002667 auto sender =
2668 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002669 std::string receiver_id;
2670 if (!media_desc->streams().empty()) {
2671 receiver_id = media_desc->streams()[0].id;
2672 } else {
2673 receiver_id = rtc::CreateRandomUuid();
2674 }
2675 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002676 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002677 transceiver->internal()->set_direction(
2678 RtpTransceiverDirection::kRecvOnly);
2679 }
2680 }
2681 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002682 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002683 LOG_AND_RETURN_ERROR(
2684 RTCErrorType::INVALID_PARAMETER,
2685 "Transceiver type does not match media description type.");
2686 }
2687 // Associate the found or created RtpTransceiver with the m= section by
2688 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2689 // section, and establish a mapping between the transceiver and the index of
2690 // the m= section.
2691 transceiver->internal()->set_mid(content.name);
2692 transceiver->internal()->set_mline_index(mline_index);
2693 return std::move(transceiver);
2694}
2695
2696rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2697PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2698 RTC_DCHECK(IsUnifiedPlan());
2699 for (auto transceiver : transceivers_) {
2700 if (transceiver->mid() == mid) {
2701 return transceiver;
2702 }
2703 }
2704 return nullptr;
2705}
2706
2707rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2708PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2709 RTC_DCHECK(IsUnifiedPlan());
2710 for (auto transceiver : transceivers_) {
2711 if (transceiver->internal()->mline_index() == mline_index) {
2712 return transceiver;
2713 }
2714 }
2715 return nullptr;
2716}
2717
2718rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2719PeerConnection::FindAvailableTransceiverToReceive(
2720 cricket::MediaType media_type) const {
2721 RTC_DCHECK(IsUnifiedPlan());
2722 // From JSEP section 5.10 (Applying a Remote Description):
2723 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2724 // the same type that were added to the PeerConnection by addTrack and are not
2725 // associated with any m= section and are not stopped, find the first such
2726 // RtpTransceiver.
2727 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002728 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002729 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2730 !transceiver->stopped()) {
2731 return transceiver;
2732 }
2733 }
2734 return nullptr;
2735}
2736
Steve Antoned10bd92017-12-05 10:52:59 -08002737const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2738 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2739 transceiver,
2740 const SessionDescriptionInterface* sdesc) const {
2741 RTC_DCHECK(transceiver);
2742 RTC_DCHECK(sdesc);
2743 if (IsUnifiedPlan()) {
2744 if (!transceiver->internal()->mid()) {
2745 // This transceiver is not associated with a media section yet.
2746 return nullptr;
2747 }
2748 return sdesc->description()->GetContentByName(
2749 *transceiver->internal()->mid());
2750 } else {
2751 // Plan B only allows at most one audio and one video section, so use the
2752 // first media section of that type.
2753 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002754 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002755 }
2756}
2757
deadbeef46c73892016-11-16 19:42:04 -08002758PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2759 return configuration_;
2760}
2761
deadbeef293e9262017-01-11 12:28:30 -08002762bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2763 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002764 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002765
Steve Anton75737c02017-11-06 10:37:17 -08002766 if (local_description() && configuration.ice_candidate_pool_size !=
2767 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002768 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2769 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002770 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002771 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002772
deadbeef293e9262017-01-11 12:28:30 -08002773 // The simplest (and most future-compatible) way to tell if the config was
2774 // modified in an invalid way is to copy each property we do support
2775 // modifying, then use operator==. There are far more properties we don't
2776 // support modifying than those we do, and more could be added.
2777 RTCConfiguration modified_config = configuration_;
2778 modified_config.servers = configuration.servers;
2779 modified_config.type = configuration.type;
2780 modified_config.ice_candidate_pool_size =
2781 configuration.ice_candidate_pool_size;
2782 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002783 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002784 modified_config.ice_check_interval_strong_connectivity =
2785 configuration.ice_check_interval_strong_connectivity;
2786 modified_config.ice_check_interval_weak_connectivity =
2787 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002788 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2789 modified_config.ice_unwritable_min_checks =
2790 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002791 modified_config.stun_candidate_keepalive_interval =
2792 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002793 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002794 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002795 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002796 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002797 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2798 }
2799
Steve Anton038834f2017-07-14 15:59:59 -07002800 // Validate the modified configuration.
2801 RTCError validate_error = ValidateConfiguration(modified_config);
2802 if (!validate_error.ok()) {
2803 return SafeSetError(std::move(validate_error), error);
2804 }
2805
deadbeef293e9262017-01-11 12:28:30 -08002806 // Note that this isn't possible through chromium, since it's an unsigned
2807 // short in WebIDL.
2808 if (configuration.ice_candidate_pool_size < 0 ||
2809 configuration.ice_candidate_pool_size > UINT16_MAX) {
2810 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2811 }
2812
2813 // Parse ICE servers before hopping to network thread.
2814 cricket::ServerAddresses stun_servers;
2815 std::vector<cricket::RelayServerConfig> turn_servers;
2816 RTCErrorType parse_error =
2817 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2818 if (parse_error != RTCErrorType::NONE) {
2819 return SafeSetError(parse_error, error);
2820 }
2821
2822 // In theory this shouldn't fail.
2823 if (!network_thread()->Invoke<bool>(
2824 RTC_FROM_HERE,
2825 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2826 stun_servers, turn_servers, modified_config.type,
2827 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002828 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002829 modified_config.turn_customizer,
2830 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002831 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002832 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2833 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002834
deadbeefd1a38b52016-12-10 13:15:33 -08002835 // As described in JSEP, calling setConfiguration with new ICE servers or
2836 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2837 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002838 if (modified_config.servers != configuration_.servers ||
2839 modified_config.type != configuration_.type ||
2840 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002841 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002842 }
skvladd1f5fda2017-02-03 16:54:05 -08002843
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002844 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002845
deadbeef293e9262017-01-11 12:28:30 -08002846 configuration_ = modified_config;
2847 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002848}
2849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850bool PeerConnection::AddIceCandidate(
2851 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002852 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002853 if (IsClosed()) {
2854 return false;
2855 }
Steve Antond25da372017-11-06 14:50:29 -08002856
2857 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002858 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002859 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002860 return false;
2861 }
2862
2863 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002864 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002865 return false;
2866 }
2867
2868 bool valid = false;
2869 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2870 if (!valid) {
2871 return false;
2872 }
2873
2874 // Add this candidate to the remote session description.
2875 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002876 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002877 return false;
2878 }
2879
2880 if (ready) {
2881 return UseCandidate(ice_candidate);
2882 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002883 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002884 return true;
2885 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886}
2887
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002888bool PeerConnection::RemoveIceCandidates(
2889 const std::vector<cricket::Candidate>& candidates) {
2890 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002891 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002892 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002893 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002894 return false;
2895 }
2896
2897 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002898 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002899 return false;
2900 }
2901
2902 size_t number_removed =
2903 mutable_remote_description()->RemoveCandidates(candidates);
2904 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002905 RTC_LOG(LS_ERROR)
2906 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002907 "Requested "
2908 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002909 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002910 }
2911
2912 // Remove the candidates from the transport controller.
2913 std::string error;
2914 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2915 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002916 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002917 }
2918 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002919}
2920
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002921void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002922 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002923 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002924
Steve Anton75737c02017-11-06 10:37:17 -08002925 if (transport_controller()) {
2926 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002927 }
2928
Steve Antondb67ba12018-03-19 17:41:42 -07002929 for (auto transceiver : transceivers_) {
2930 auto* channel = transceiver->internal()->channel();
2931 if (channel) {
2932 channel->SetMetricsObserver(uma_observer_);
2933 }
2934 }
2935
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002936 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002937 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002938 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002939 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002940 uma_observer_->IncrementEnumCounter(
2941 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2942 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002943 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002944 uma_observer_->IncrementEnumCounter(
2945 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2946 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002947 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002948 // Send information about the requested SDP semantics.
2949 switch (configuration_.sdp_semantics) {
2950 case SdpSemantics::kDefault:
2951 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2952 kSdpSemanticRequestDefault,
2953 kSdpSemanticRequestMax);
2954
2955 break;
2956 case SdpSemantics::kPlanB:
2957 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2958 kSdpSemanticRequestPlanB,
2959 kSdpSemanticRequestMax);
2960 break;
2961 case SdpSemantics::kUnifiedPlan:
2962 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2963 kSdpSemanticRequestUnifiedPlan,
2964 kSdpSemanticRequestMax);
2965 break;
2966 default:
2967 RTC_NOTREACHED();
2968 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002969 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002970}
2971
zstein4b979802017-06-02 14:37:37 -07002972RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002973 if (!worker_thread()->IsCurrent()) {
2974 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002975 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2976 }
2977
2978 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2979 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2980 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2981 if (has_min && *bitrate.min_bitrate_bps < 0) {
2982 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2983 "min_bitrate_bps <= 0");
2984 }
2985 if (has_current) {
2986 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2987 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2988 "current_bitrate_bps < min_bitrate_bps");
2989 } else if (*bitrate.current_bitrate_bps < 0) {
2990 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2991 "curent_bitrate_bps < 0");
2992 }
2993 }
2994 if (has_max) {
2995 if (has_current &&
2996 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2997 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2998 "max_bitrate_bps < current_bitrate_bps");
2999 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3000 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3001 "max_bitrate_bps < min_bitrate_bps");
3002 } else if (*bitrate.max_bitrate_bps < 0) {
3003 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3004 "max_bitrate_bps < 0");
3005 }
3006 }
3007
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003008 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003009 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3010 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3011 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3012
3013 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003014 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003015
3016 return RTCError::OK();
3017}
3018
Alex Narest78609d52017-10-20 10:37:47 +02003019void PeerConnection::SetBitrateAllocationStrategy(
3020 std::unique_ptr<rtc::BitrateAllocationStrategy>
3021 bitrate_allocation_strategy) {
3022 rtc::Thread* worker_thread = factory_->worker_thread();
3023 if (!worker_thread->IsCurrent()) {
3024 rtc::BitrateAllocationStrategy* strategy_raw =
3025 bitrate_allocation_strategy.release();
3026 auto functor = [this, strategy_raw]() {
3027 call_->SetBitrateAllocationStrategy(
3028 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3029 };
3030 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3031 return;
3032 }
3033 RTC_DCHECK(call_.get());
3034 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3035}
3036
henrika5f6bf242017-11-01 11:06:56 +01003037void PeerConnection::SetAudioPlayout(bool playout) {
3038 if (!worker_thread()->IsCurrent()) {
3039 worker_thread()->Invoke<void>(
3040 RTC_FROM_HERE,
3041 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3042 return;
3043 }
3044 auto audio_state =
3045 factory_->channel_manager()->media_engine()->GetAudioState();
3046 audio_state->SetPlayout(playout);
3047}
3048
3049void PeerConnection::SetAudioRecording(bool recording) {
3050 if (!worker_thread()->IsCurrent()) {
3051 worker_thread()->Invoke<void>(
3052 RTC_FROM_HERE,
3053 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3054 return;
3055 }
3056 auto audio_state =
3057 factory_->channel_manager()->media_engine()->GetAudioState();
3058 audio_state->SetRecording(recording);
3059}
3060
Steve Anton8c0f7a72017-10-03 10:03:10 -07003061std::unique_ptr<rtc::SSLCertificate>
3062PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003063 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3064 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003065 return nullptr;
3066 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003067 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003068}
3069
Zhi Huang70b820f2018-01-27 14:16:15 -08003070std::unique_ptr<rtc::SSLCertChain>
3071PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003072 auto audio_transceiver = GetFirstAudioTransceiver();
3073 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003074 return nullptr;
3075 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003076 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003077 audio_transceiver->internal()->channel()->transport_name());
3078}
3079
3080rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3081PeerConnection::GetFirstAudioTransceiver() const {
3082 for (auto transceiver : transceivers_) {
3083 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3084 return transceiver;
3085 }
3086 }
3087 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003088}
3089
ivoc14d5dbe2016-07-04 07:06:55 -07003090bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3091 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003092 // TODO(eladalon): It would be better to not allow negative values into PC.
3093 const size_t max_size = (max_size_bytes < 0)
3094 ? RtcEventLog::kUnlimitedOutput
3095 : rtc::saturated_cast<size_t>(max_size_bytes);
3096 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003097 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3098 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003099}
3100
Bjorn Tereliusde939432017-11-20 17:38:14 +01003101bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3102 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003103 // TODO(eladalon): In C++14, this can be done with a lambda.
3104 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003105 bool operator()() {
3106 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3107 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003108 PeerConnection* const pc;
3109 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003110 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003111 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003112 return worker_thread()->Invoke<bool>(
3113 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003114}
3115
3116void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003117 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003118 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3119}
3120
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003121const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003122 return pending_local_description_ ? pending_local_description_.get()
3123 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003124}
3125
3126const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003127 return pending_remote_description_ ? pending_remote_description_.get()
3128 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003129}
3130
deadbeeffe4a8a42016-12-20 17:56:17 -08003131const SessionDescriptionInterface* PeerConnection::current_local_description()
3132 const {
Steve Anton75737c02017-11-06 10:37:17 -08003133 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003134}
3135
3136const SessionDescriptionInterface* PeerConnection::current_remote_description()
3137 const {
Steve Anton75737c02017-11-06 10:37:17 -08003138 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003139}
3140
3141const SessionDescriptionInterface* PeerConnection::pending_local_description()
3142 const {
Steve Anton75737c02017-11-06 10:37:17 -08003143 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003144}
3145
3146const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3147 const {
Steve Anton75737c02017-11-06 10:37:17 -08003148 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003149}
3150
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003152 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003153 // Update stats here so that we have the most recent stats for tracks and
3154 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003155 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156
Steve Anton75737c02017-11-06 10:37:17 -08003157 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003158
Steve Anton8af21862017-12-15 11:20:13 -08003159 for (auto transceiver : transceivers_) {
3160 transceiver->Stop();
3161 }
3162 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003163
Qingsi Wang93a84392018-01-30 17:13:09 -08003164 // The event log is used in the transport controller, which must be outlived
3165 // by the former. CreateOffer by the peer connection is implemented
3166 // asynchronously and if the peer connection is closed without resetting the
3167 // WebRTC session description factory, the session description factory would
3168 // call the transport controller.
3169 webrtc_session_desc_factory_.reset();
3170 transport_controller_.reset();
3171
deadbeef42a42632017-03-10 15:18:00 -08003172 network_thread()->Invoke<void>(
3173 RTC_FROM_HERE,
3174 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3175 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003176
Steve Anton978b8762017-09-29 12:15:02 -07003177 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003178 call_.reset();
3179 // The event log must outlive call (and any other object that uses it).
3180 event_log_.reset();
3181 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182}
3183
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003184void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003185 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3187 SetSessionDescriptionMsg* param =
3188 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3189 param->observer->OnSuccess();
3190 delete param;
3191 break;
3192 }
3193 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3194 SetSessionDescriptionMsg* param =
3195 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003196 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197 delete param;
3198 break;
3199 }
deadbeefab9b2d12015-10-14 11:33:11 -07003200 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3201 CreateSessionDescriptionMsg* param =
3202 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003203 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003204 delete param;
3205 break;
3206 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 case MSG_GETSTATS: {
3208 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003209 StatsReports reports;
3210 stats_->GetStats(param->track, &reports);
3211 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 delete param;
3213 break;
3214 }
deadbeefbd292462015-12-14 18:15:29 -08003215 case MSG_FREE_DATACHANNELS: {
3216 sctp_data_channels_to_free_.clear();
3217 break;
3218 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003220 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003221 break;
3222 }
3223}
3224
Steve Antonafb0bb72018-02-20 11:35:37 -08003225cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3226 RTC_DCHECK(!IsUnifiedPlan());
3227 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3228 GetAudioTransceiver()->internal()->channel());
3229 if (voice_channel) {
3230 return voice_channel->media_channel();
3231 } else {
3232 return nullptr;
3233 }
3234}
3235
3236cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3237 RTC_DCHECK(!IsUnifiedPlan());
3238 auto* video_channel = static_cast<cricket::VideoChannel*>(
3239 GetVideoTransceiver()->internal()->channel());
3240 if (video_channel) {
3241 return video_channel->media_channel();
3242 } else {
3243 return nullptr;
3244 }
3245}
3246
Steve Anton4171afb2017-11-20 10:20:22 -08003247void PeerConnection::CreateAudioReceiver(
3248 MediaStreamInterface* stream,
3249 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003250 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3251 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003252 auto* audio_receiver = new AudioRtpReceiver(
3253 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003254 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003255 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3256 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3257 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003258 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003259 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260}
3261
Steve Anton4171afb2017-11-20 10:20:22 -08003262void PeerConnection::CreateVideoReceiver(
3263 MediaStreamInterface* stream,
3264 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003265 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3266 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003267 auto* video_receiver = new VideoRtpReceiver(
3268 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003269 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003270 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3271 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3272 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003273 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003274 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275}
3276
deadbeef70ab1a12015-09-28 16:53:55 -07003277// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3278// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003279rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003280 const RtpSenderInfo& remote_sender_info) {
3281 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3282 if (!receiver) {
3283 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3284 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003285 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003286 }
Steve Anton4171afb2017-11-20 10:20:22 -08003287 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3288 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3289 } else {
3290 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3291 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003292 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003293}
3294
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003295void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3296 MediaStreamInterface* stream) {
3297 RTC_DCHECK(!IsClosed());
3298 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003299 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003300 // We already have a sender for this track, so just change the stream_id
3301 // so that it's correct in the next call to CreateOffer.
Seth Hampson15502922018-03-26 10:06:46 -07003302 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003303 return;
3304 }
3305
3306 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003307 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003308 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003309 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003310 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003311 // If the sender has already been configured in SDP, we call SetSsrc,
3312 // which will connect the sender to the underlying transport. This can
3313 // occur if a local session description that contains the ID of the sender
3314 // is set before AddStream is called. It can also occur if the local
3315 // session description is not changed and RemoveStream is called, and
3316 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003317 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07003318 FindSenderInfo(local_audio_sender_infos_, track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003319 if (sender_info) {
3320 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003321 }
3322}
3323
3324// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3325// indefinitely, when we have unified plan SDP.
3326void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3327 MediaStreamInterface* stream) {
3328 RTC_DCHECK(!IsClosed());
3329 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003330 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003331 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3332 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003333 return;
3334 }
Steve Anton4171afb2017-11-20 10:20:22 -08003335 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003336}
3337
3338void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3339 MediaStreamInterface* stream) {
3340 RTC_DCHECK(!IsClosed());
3341 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003342 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003343 // We already have a sender for this track, so just change the stream_id
3344 // so that it's correct in the next call to CreateOffer.
Seth Hampson15502922018-03-26 10:06:46 -07003345 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003346 return;
3347 }
3348
3349 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003350 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003351 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003352 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003353 GetVideoTransceiver()->internal()->AddSender(new_sender);
3354 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07003355 FindSenderInfo(local_video_sender_infos_, track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003356 if (sender_info) {
3357 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003358 }
3359}
3360
3361void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3362 MediaStreamInterface* stream) {
3363 RTC_DCHECK(!IsClosed());
3364 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003365 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003366 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3367 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003368 return;
3369 }
Steve Anton4171afb2017-11-20 10:20:22 -08003370 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003371}
3372
Steve Antonba818672017-11-06 10:21:57 -08003373void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003374 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003375 if (ice_connection_state_ == new_state) {
3376 return;
3377 }
3378
deadbeefcbecd352015-09-23 11:50:27 -07003379 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003380 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003381 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003382 return;
3383 }
Steve Antonba818672017-11-06 10:21:57 -08003384
Mirko Bonadei675513b2017-11-09 11:09:25 +01003385 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3386 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003387 RTC_DCHECK(ice_connection_state_ !=
3388 PeerConnectionInterface::kIceConnectionClosed);
3389
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003391 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392}
3393
3394void PeerConnection::OnIceGatheringChange(
3395 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003396 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003397 if (IsClosed()) {
3398 return;
3399 }
3400 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003401 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402}
3403
jbauch81bf7b02017-03-25 08:31:12 -07003404void PeerConnection::OnIceCandidate(
3405 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003406 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003407 if (IsClosed()) {
3408 return;
3409 }
jbauch81bf7b02017-03-25 08:31:12 -07003410 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411}
3412
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003413void PeerConnection::OnIceCandidatesRemoved(
3414 const std::vector<cricket::Candidate>& candidates) {
3415 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003416 if (IsClosed()) {
3417 return;
3418 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003419 observer_->OnIceCandidatesRemoved(candidates);
3420}
3421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003422void PeerConnection::ChangeSignalingState(
3423 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003424 RTC_DCHECK(signaling_thread()->IsCurrent());
3425 if (signaling_state_ == signaling_state) {
3426 return;
3427 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003428 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3429 << GetSignalingStateString(signaling_state_)
3430 << " New state: "
3431 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432 signaling_state_ = signaling_state;
3433 if (signaling_state == kClosed) {
3434 ice_connection_state_ = kIceConnectionClosed;
3435 observer_->OnIceConnectionChange(ice_connection_state_);
3436 if (ice_gathering_state_ != kIceGatheringComplete) {
3437 ice_gathering_state_ = kIceGatheringComplete;
3438 observer_->OnIceGatheringChange(ice_gathering_state_);
3439 }
3440 }
3441 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442}
3443
deadbeefeb459812015-12-15 19:24:43 -08003444void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3445 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003446 if (IsClosed()) {
3447 return;
3448 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003449 AddAudioTrack(track, stream);
3450 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003451}
3452
deadbeefeb459812015-12-15 19:24:43 -08003453void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3454 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003455 if (IsClosed()) {
3456 return;
3457 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003458 RemoveAudioTrack(track, stream);
3459 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003460}
3461
3462void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3463 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003464 if (IsClosed()) {
3465 return;
3466 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003467 AddVideoTrack(track, stream);
3468 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003469}
3470
3471void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3472 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003473 if (IsClosed()) {
3474 return;
3475 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003476 RemoveVideoTrack(track, stream);
3477 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003478}
3479
Henrik Boström31638672017-11-23 17:48:32 +01003480void PeerConnection::PostSetSessionDescriptionSuccess(
3481 SetSessionDescriptionObserver* observer) {
3482 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3483 signaling_thread()->Post(RTC_FROM_HERE, this,
3484 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3485}
3486
deadbeefab9b2d12015-10-14 11:33:11 -07003487void PeerConnection::PostSetSessionDescriptionFailure(
3488 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003489 RTCError&& error) {
3490 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003491 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003492 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003493 signaling_thread()->Post(RTC_FROM_HERE, this,
3494 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003495}
3496
3497void PeerConnection::PostCreateSessionDescriptionFailure(
3498 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003499 RTCError error) {
3500 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003501 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003502 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003503 signaling_thread()->Post(RTC_FROM_HERE, this,
3504 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003505}
3506
zhihuang1c378ed2017-08-17 14:10:50 -07003507void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003508 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003509 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003510 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003511
Steve Antondcc3c022017-12-22 16:02:54 -08003512 if (IsUnifiedPlan()) {
3513 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3514 } else {
3515 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3516 }
3517
Steve Antonfa2260d2017-12-28 16:38:23 -08003518 // Intentionally unset the data channel type for RTP data channel with the
3519 // second condition. Otherwise the RTP data channels would be successfully
3520 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3521 // when building with chromium. We want to leave RTP data channels broken, so
3522 // people won't try to use them.
3523 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3524 session_options->data_channel_type = data_channel_type();
3525 }
3526
Steve Antondcc3c022017-12-22 16:02:54 -08003527 // Apply ICE restart flag and renomination flag.
3528 for (auto& options : session_options->media_description_options) {
3529 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3530 options.transport_options.enable_ice_renomination =
3531 configuration_.enable_ice_renomination;
3532 }
3533
3534 session_options->rtcp_cname = rtcp_cname_;
3535 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003536 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003537}
3538
3539void PeerConnection::GetOptionsForPlanBOffer(
3540 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3541 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003542 // Figure out transceiver directional preferences.
3543 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3544 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3545
3546 // By default, generate sendrecv/recvonly m= sections.
3547 bool recv_audio = true;
3548 bool recv_video = true;
3549
3550 // By default, only offer a new m= section if we have media to send with it.
3551 bool offer_new_audio_description = send_audio;
3552 bool offer_new_video_description = send_video;
3553 bool offer_new_data_description = HasDataChannels();
3554
3555 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003556 if (offer_answer_options.offer_to_receive_audio !=
3557 RTCOfferAnswerOptions::kUndefined) {
3558 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003559 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003560 offer_new_audio_description ||
3561 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003562 }
Steve Antondcc3c022017-12-22 16:02:54 -08003563 if (offer_answer_options.offer_to_receive_video !=
3564 RTCOfferAnswerOptions::kUndefined) {
3565 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003566 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003567 offer_new_video_description ||
3568 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003569 }
3570
3571 rtc::Optional<size_t> audio_index;
3572 rtc::Optional<size_t> video_index;
3573 rtc::Optional<size_t> data_index;
3574 // If a current description exists, generate m= sections in the same order,
3575 // using the first audio/video/data section that appears and rejecting
3576 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003577 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003578 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003579 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003580 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3581 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3582 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003583 }
3584
zhihuang1c378ed2017-08-17 14:10:50 -07003585 // Add audio/video/data m= sections to the end if needed.
3586 if (!audio_index && offer_new_audio_description) {
3587 session_options->media_description_options.push_back(
3588 cricket::MediaDescriptionOptions(
3589 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003590 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3591 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003592 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003593 }
zhihuang1c378ed2017-08-17 14:10:50 -07003594 if (!video_index && offer_new_video_description) {
3595 session_options->media_description_options.push_back(
3596 cricket::MediaDescriptionOptions(
3597 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003598 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3599 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003600 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003601 }
zhihuang1c378ed2017-08-17 14:10:50 -07003602 if (!data_index && offer_new_data_description) {
3603 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003604 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003605 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003606 }
3607
3608 cricket::MediaDescriptionOptions* audio_media_description_options =
3609 !audio_index ? nullptr
3610 : &session_options->media_description_options[*audio_index];
3611 cricket::MediaDescriptionOptions* video_media_description_options =
3612 !video_index ? nullptr
3613 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003614
Steve Anton4171afb2017-11-20 10:20:22 -08003615 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003616 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003617}
3618
3619// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3620// and return a reference to it.
3621// Generated MIDs should be no more than 3 bytes long to take up less space in
3622// the RTP packet.
3623static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3624 RTC_DCHECK(used_mids);
3625 // We're boring: just generate MIDs 0, 1, 2, ...
3626 size_t i = 0;
3627 std::set<std::string>::iterator it;
3628 bool inserted;
3629 do {
3630 std::string mid = rtc::ToString(i++);
3631 auto insert_result = used_mids->insert(mid);
3632 it = insert_result.first;
3633 inserted = insert_result.second;
3634 } while (!inserted);
3635 return *it;
3636}
3637
3638static cricket::MediaDescriptionOptions
3639GetMediaDescriptionOptionsForTransceiver(
3640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3641 transceiver,
3642 const std::string& mid) {
3643 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003644 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003645 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003646 // This behavior is specified in JSEP. The gist is that:
3647 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3648 // sendrecv.
3649 // 2. If the MSID is included, then it must be included in any subsequent
3650 // offer/answer exactly the same until the RtpTransceiver is stopped.
3651 if (!transceiver->stopped() &&
3652 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3653 transceiver->internal()->has_ever_been_used_to_send())) {
3654 cricket::SenderOptions sender_options;
3655 sender_options.track_id = transceiver->sender()->id();
3656 sender_options.stream_ids = transceiver->sender()->stream_ids();
3657 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3658 // set in the RTP parameters when the transceiver was added.
3659 sender_options.num_sim_layers = 1;
3660 media_description_options.sender_options.push_back(sender_options);
3661 }
Steve Antondcc3c022017-12-22 16:02:54 -08003662 return media_description_options;
3663}
3664
3665void PeerConnection::GetOptionsForUnifiedPlanOffer(
3666 const RTCOfferAnswerOptions& offer_answer_options,
3667 cricket::MediaSessionOptions* session_options) {
3668 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3669 // Offers) and 5.2.2 (Subsequent Offers).
3670 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3671 const ContentInfos& local_contents =
3672 (local_description() ? local_description()->description()->contents()
3673 : ContentInfos());
3674 const ContentInfos& remote_contents =
3675 (remote_description() ? remote_description()->description()->contents()
3676 : ContentInfos());
3677 // The mline indices that can be recycled. New transceivers should reuse these
3678 // slots first.
3679 std::queue<size_t> recycleable_mline_indices;
3680 // Track the MIDs used in previous offer/answer exchanges and the current
3681 // offer so that new, unique MIDs are generated.
3682 std::set<std::string> used_mids = seen_mids_;
3683 // First, go through each media section that exists in either the local or
3684 // remote description and generate a media section in this offer for the
3685 // associated transceiver. If a media section can be recycled, generate a
3686 // default, rejected media section here that can be later overwritten.
3687 for (size_t i = 0;
3688 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3689 // Either |local_content| or |remote_content| is non-null.
3690 const ContentInfo* local_content =
3691 (i < local_contents.size() ? &local_contents[i] : nullptr);
3692 const ContentInfo* remote_content =
3693 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3694 bool had_been_rejected = (local_content && local_content->rejected) ||
3695 (remote_content && remote_content->rejected);
3696 const std::string& mid =
3697 (local_content ? local_content->name : remote_content->name);
3698 cricket::MediaType media_type =
3699 (local_content ? local_content->media_description()->type()
3700 : remote_content->media_description()->type());
3701 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3702 media_type == cricket::MEDIA_TYPE_VIDEO) {
3703 auto transceiver = GetAssociatedTransceiver(mid);
3704 RTC_CHECK(transceiver);
3705 // A media section is considered eligible for recycling if it is marked as
3706 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003707 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003708 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003709 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3710 RtpTransceiverDirection::kInactive,
3711 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003712 recycleable_mline_indices.push(i);
3713 } else {
3714 session_options->media_description_options.push_back(
3715 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3716 // CreateOffer shouldn't really cause any state changes in
3717 // PeerConnection, but we need a way to match new transceivers to new
3718 // media sections in SetLocalDescription and JSEP specifies this is done
3719 // by recording the index of the media section generated for the
3720 // transceiver in the offer.
3721 transceiver->internal()->set_mline_index(i);
3722 }
3723 } else {
3724 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003725 RTC_CHECK(GetDataMid());
3726 if (had_been_rejected || mid != *GetDataMid()) {
3727 session_options->media_description_options.push_back(
3728 GetMediaDescriptionOptionsForRejectedData(mid));
3729 } else {
3730 session_options->media_description_options.push_back(
3731 GetMediaDescriptionOptionsForActiveData(mid));
3732 }
Steve Antondcc3c022017-12-22 16:02:54 -08003733 }
3734 }
3735 // Next, look for transceivers that are newly added (that is, are not stopped
3736 // and not associated). Reuse media sections marked as recyclable first,
3737 // otherwise append to the end of the offer. New media sections should be
3738 // added in the order they were added to the PeerConnection.
3739 for (auto transceiver : transceivers_) {
3740 if (transceiver->mid() || transceiver->stopped()) {
3741 continue;
3742 }
3743 size_t mline_index;
3744 if (!recycleable_mline_indices.empty()) {
3745 mline_index = recycleable_mline_indices.front();
3746 recycleable_mline_indices.pop();
3747 session_options->media_description_options[mline_index] =
3748 GetMediaDescriptionOptionsForTransceiver(transceiver,
3749 AllocateMid(&used_mids));
3750 } else {
3751 mline_index = session_options->media_description_options.size();
3752 session_options->media_description_options.push_back(
3753 GetMediaDescriptionOptionsForTransceiver(transceiver,
3754 AllocateMid(&used_mids)));
3755 }
3756 // See comment above for why CreateOffer changes the transceiver's state.
3757 transceiver->internal()->set_mline_index(mline_index);
3758 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003759 // Lastly, add a m-section if we have local data channels and an m section
3760 // does not already exist.
3761 if (!GetDataMid() && HasDataChannels()) {
3762 session_options->media_description_options.push_back(
3763 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3764 }
Steve Antondcc3c022017-12-22 16:02:54 -08003765}
3766
3767void PeerConnection::GetOptionsForAnswer(
3768 const RTCOfferAnswerOptions& offer_answer_options,
3769 cricket::MediaSessionOptions* session_options) {
3770 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3771
3772 if (IsUnifiedPlan()) {
3773 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3774 } else {
3775 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3776 }
3777
Steve Antonfa2260d2017-12-28 16:38:23 -08003778 // Intentionally unset the data channel type for RTP data channel. Otherwise
3779 // the RTP data channels would be successfully negotiated by default and the
3780 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3781 // We want to leave RTP data channels broken, so people won't try to use them.
3782 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3783 session_options->data_channel_type = data_channel_type();
3784 }
3785
Steve Antondcc3c022017-12-22 16:02:54 -08003786 // Apply ICE renomination flag.
3787 for (auto& options : session_options->media_description_options) {
3788 options.transport_options.enable_ice_renomination =
3789 configuration_.enable_ice_renomination;
3790 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003791
3792 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003793 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003794 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003795}
3796
Steve Antondcc3c022017-12-22 16:02:54 -08003797void PeerConnection::GetOptionsForPlanBAnswer(
3798 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003799 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003800 // Figure out transceiver directional preferences.
3801 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3802 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3803
3804 // By default, generate sendrecv/recvonly m= sections. The direction is also
3805 // restricted by the direction in the offer.
3806 bool recv_audio = true;
3807 bool recv_video = true;
3808
3809 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003810 if (offer_answer_options.offer_to_receive_audio !=
3811 RTCOfferAnswerOptions::kUndefined) {
3812 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003813 }
Steve Antondcc3c022017-12-22 16:02:54 -08003814 if (offer_answer_options.offer_to_receive_video !=
3815 RTCOfferAnswerOptions::kUndefined) {
3816 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003817 }
3818
3819 rtc::Optional<size_t> audio_index;
3820 rtc::Optional<size_t> video_index;
3821 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003822
3823 // Generate m= sections that match those in the offer.
3824 // Note that mediasession.cc will handle intersection our preferred
3825 // direction with the offered direction.
3826 GenerateMediaDescriptionOptions(
3827 remote_description(),
3828 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3829 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3830 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003831
3832 cricket::MediaDescriptionOptions* audio_media_description_options =
3833 !audio_index ? nullptr
3834 : &session_options->media_description_options[*audio_index];
3835 cricket::MediaDescriptionOptions* video_media_description_options =
3836 !video_index ? nullptr
3837 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003838
Steve Anton4171afb2017-11-20 10:20:22 -08003839 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003840 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003841}
zhihuangaf388472016-11-02 16:49:48 -07003842
Steve Antondcc3c022017-12-22 16:02:54 -08003843void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3844 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3845 cricket::MediaSessionOptions* session_options) {
3846 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3847 // Answers) and 5.3.2 (Subsequent Answers).
3848 RTC_DCHECK(remote_description());
3849 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3850 for (const ContentInfo& content :
3851 remote_description()->description()->contents()) {
3852 cricket::MediaType media_type = content.media_description()->type();
3853 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3854 media_type == cricket::MEDIA_TYPE_VIDEO) {
3855 auto transceiver = GetAssociatedTransceiver(content.name);
3856 RTC_CHECK(transceiver);
3857 session_options->media_description_options.push_back(
3858 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3859 } else {
3860 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003861 // Reject all data sections if data channels are disabled.
3862 // Reject a data section if it has already been rejected.
3863 // Reject all data sections except for the first one.
3864 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3865 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003866 session_options->media_description_options.push_back(
3867 GetMediaDescriptionOptionsForRejectedData(content.name));
3868 } else {
3869 session_options->media_description_options.push_back(
3870 GetMediaDescriptionOptionsForActiveData(content.name));
3871 }
Steve Antondcc3c022017-12-22 16:02:54 -08003872 }
3873 }
htaa2a49d92016-03-04 02:51:39 -08003874}
3875
zhihuang1c378ed2017-08-17 14:10:50 -07003876void PeerConnection::GenerateMediaDescriptionOptions(
3877 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003878 RtpTransceiverDirection audio_direction,
3879 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003880 rtc::Optional<size_t>* audio_index,
3881 rtc::Optional<size_t>* video_index,
3882 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003883 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003884 for (const cricket::ContentInfo& content :
3885 session_desc->description()->contents()) {
3886 if (IsAudioContent(&content)) {
3887 // If we already have an audio m= section, reject this extra one.
3888 if (*audio_index) {
3889 session_options->media_description_options.push_back(
3890 cricket::MediaDescriptionOptions(
3891 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003892 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003893 } else {
3894 session_options->media_description_options.push_back(
3895 cricket::MediaDescriptionOptions(
3896 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003897 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003898 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003899 }
3900 } else if (IsVideoContent(&content)) {
3901 // If we already have an video m= section, reject this extra one.
3902 if (*video_index) {
3903 session_options->media_description_options.push_back(
3904 cricket::MediaDescriptionOptions(
3905 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003906 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003907 } else {
3908 session_options->media_description_options.push_back(
3909 cricket::MediaDescriptionOptions(
3910 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003911 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003912 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003913 }
3914 } else {
3915 RTC_DCHECK(IsDataContent(&content));
3916 // If we already have an data m= section, reject this extra one.
3917 if (*data_index) {
3918 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003919 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003920 } else {
3921 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003922 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003923 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003924 }
3925 }
htaa2a49d92016-03-04 02:51:39 -08003926 }
deadbeefab9b2d12015-10-14 11:33:11 -07003927}
3928
Steve Antonfa2260d2017-12-28 16:38:23 -08003929cricket::MediaDescriptionOptions
3930PeerConnection::GetMediaDescriptionOptionsForActiveData(
3931 const std::string& mid) const {
3932 // Direction for data sections is meaningless, but legacy endpoints might
3933 // expect sendrecv.
3934 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3935 RtpTransceiverDirection::kSendRecv,
3936 /*stopped=*/false);
3937 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3938 return options;
3939}
3940
3941cricket::MediaDescriptionOptions
3942PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3943 const std::string& mid) const {
3944 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3945 RtpTransceiverDirection::kInactive,
3946 /*stopped=*/true);
3947 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3948 return options;
3949}
3950
3951rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3952 switch (data_channel_type_) {
3953 case cricket::DCT_RTP:
3954 if (!rtp_data_channel_) {
3955 return rtc::nullopt;
3956 }
3957 return rtp_data_channel_->content_name();
3958 case cricket::DCT_SCTP:
3959 return sctp_content_name_;
3960 default:
3961 return rtc::nullopt;
3962 }
3963}
3964
Steve Anton4171afb2017-11-20 10:20:22 -08003965void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3966 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3967 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003968 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003969}
3970
Steve Anton4171afb2017-11-20 10:20:22 -08003971void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003972 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003973 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003974 cricket::MediaType media_type,
3975 StreamCollection* new_streams) {
Seth Hampson15502922018-03-26 10:06:46 -07003976 RTC_DCHECK(!IsUnifiedPlan());
3977
Steve Anton4171afb2017-11-20 10:20:22 -08003978 std::vector<RtpSenderInfo>* current_senders =
3979 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003980
Steve Anton4171afb2017-11-20 10:20:22 -08003981 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003982 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003983 for (auto sender_it = current_senders->begin();
3984 sender_it != current_senders->end();
3985 /* incremented manually */) {
3986 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003987 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003988 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson15502922018-03-26 10:06:46 -07003989 bool sender_exists = params && params->id == info.sender_id &&
3990 params->first_stream_id() == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003991 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003992 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003993 sender_exists) {
3994 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003995 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003996 OnRemoteSenderRemoved(info, media_type);
3997 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003998 }
3999 }
4000
Steve Anton4171afb2017-11-20 10:20:22 -08004001 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004002 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08004003 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson15502922018-03-26 10:06:46 -07004004 // |params.stream_ids|. The remote description could come from a Unified
4005 // Plan endpoint, with multiple or no stream_ids() signalled. Since this is
4006 // not supported in Plan B, we just take the first here and create an empty
4007 // stream id if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004008 const std::string& stream_id =
4009 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08004010 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004011 uint32_t ssrc = params.first_ssrc();
4012
4013 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004014 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004015 if (!stream) {
4016 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004017 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004018 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004019 remote_streams_->AddStream(stream);
4020 new_streams->AddStream(stream);
4021 }
4022
Steve Anton4171afb2017-11-20 10:20:22 -08004023 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07004024 FindSenderInfo(*current_senders, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004025 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004026 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004027 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004028 }
4029 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004030
Steve Anton4171afb2017-11-20 10:20:22 -08004031 // Add default sender if necessary.
4032 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004033 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004034 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004035 if (!default_stream) {
4036 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004037 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004038 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004039 remote_streams_->AddStream(default_stream);
4040 new_streams->AddStream(default_stream);
4041 }
Steve Anton4171afb2017-11-20 10:20:22 -08004042 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4043 ? kDefaultAudioSenderId
4044 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004045 const RtpSenderInfo* default_sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07004046 FindSenderInfo(*current_senders, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004047 if (!default_sender_info) {
4048 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004049 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004050 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004051 }
4052 }
deadbeefab9b2d12015-10-14 11:33:11 -07004053}
4054
Steve Anton4171afb2017-11-20 10:20:22 -08004055void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4056 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004057 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004058
4059 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004060 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004061 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004062 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004063 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004064 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004065 }
4066}
4067
Steve Anton4171afb2017-11-20 10:20:22 -08004068void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4069 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004070 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004071
Henrik Boström933d8b02017-10-10 10:05:16 -07004072 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004073 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004074 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4075 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004076 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004077 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004078 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004079 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004080 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004081 }
4082 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004083 // Stopping or destroying a VideoRtpReceiver will end the
4084 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004085 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004086 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004087 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004088 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004089 // There's no guarantee the track is still available, e.g. the track may
4090 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004091 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004092 }
4093 } else {
nisseede5da42017-01-12 05:15:36 -08004094 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004095 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004096 if (receiver) {
4097 observer_->OnRemoveTrack(receiver);
4098 }
deadbeefab9b2d12015-10-14 11:33:11 -07004099}
4100
4101void PeerConnection::UpdateEndedRemoteMediaStreams() {
4102 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4103 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4104 MediaStreamInterface* stream = remote_streams_->at(i);
4105 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4106 streams_to_remove.push_back(stream);
4107 }
4108 }
4109
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004110 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004111 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004112 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004113 }
4114}
4115
Steve Anton4171afb2017-11-20 10:20:22 -08004116void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004117 const std::vector<cricket::StreamParams>& streams,
4118 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004119 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004120
Seth Hampson845e8782018-03-02 11:34:10 -08004121 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004122 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004123 for (auto sender_it = current_senders->begin();
4124 sender_it != current_senders->end();
4125 /* incremented manually */) {
4126 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004127 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004128 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4129 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004130 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004131 OnLocalSenderRemoved(info, media_type);
4132 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004133 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004134 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004135 }
4136 }
4137
Steve Anton4171afb2017-11-20 10:20:22 -08004138 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004139 for (const cricket::StreamParams& params : streams) {
4140 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004141 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004142 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004143 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004144 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004145 const RtpSenderInfo* sender_info =
Seth Hampson15502922018-03-26 10:06:46 -07004146 FindSenderInfo(*current_senders, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004147 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004148 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004149 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004150 }
4151 }
4152}
4153
Steve Anton4171afb2017-11-20 10:20:22 -08004154void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4155 cricket::MediaType media_type) {
Seth Hampson15502922018-03-26 10:06:46 -07004156 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004157 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004158 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004159 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4160 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004161 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004162 return;
4163 }
4164
deadbeeffac06552015-11-25 11:26:01 -08004165 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004166 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004167 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004168 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004169 }
deadbeeffac06552015-11-25 11:26:01 -08004170
Seth Hampson15502922018-03-26 10:06:46 -07004171 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004172 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004173}
4174
Steve Anton4171afb2017-11-20 10:20:22 -08004175void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4176 cricket::MediaType media_type) {
4177 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004178 if (!sender) {
4179 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004180 // SessionDescriptions has been renegotiated.
4181 return;
4182 }
deadbeeffac06552015-11-25 11:26:01 -08004183
4184 // A sender has been removed from the SessionDescription but it's still
4185 // associated with the PeerConnection. This only occurs if the SDP doesn't
4186 // match with the calls to CreateSender, AddStream and RemoveStream.
4187 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004188 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004189 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004190 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004191 }
deadbeeffac06552015-11-25 11:26:01 -08004192
Steve Anton4171afb2017-11-20 10:20:22 -08004193 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004194}
4195
4196void PeerConnection::UpdateLocalRtpDataChannels(
4197 const cricket::StreamParamsVec& streams) {
4198 std::vector<std::string> existing_channels;
4199
4200 // Find new and active data channels.
4201 for (const cricket::StreamParams& params : streams) {
4202 // |it->sync_label| is actually the data channel label. The reason is that
4203 // we use the same naming of data channels as we do for
4204 // MediaStreams and Tracks.
4205 // For MediaStreams, the sync_label is the MediaStream label and the
4206 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004207 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004208 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004209 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004210 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004211 continue;
4212 }
4213 // Set the SSRC the data channel should use for sending.
4214 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4215 existing_channels.push_back(data_channel_it->first);
4216 }
4217
4218 UpdateClosingRtpDataChannels(existing_channels, true);
4219}
4220
4221void PeerConnection::UpdateRemoteRtpDataChannels(
4222 const cricket::StreamParamsVec& streams) {
4223 std::vector<std::string> existing_channels;
4224
4225 // Find new and active data channels.
4226 for (const cricket::StreamParams& params : streams) {
4227 // The data channel label is either the mslabel or the SSRC if the mslabel
4228 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004229 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004230 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004231 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004232 auto data_channel_it = rtp_data_channels_.find(label);
4233 if (data_channel_it == rtp_data_channels_.end()) {
4234 // This is a new data channel.
4235 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4236 } else {
4237 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4238 }
4239 existing_channels.push_back(label);
4240 }
4241
4242 UpdateClosingRtpDataChannels(existing_channels, false);
4243}
4244
4245void PeerConnection::UpdateClosingRtpDataChannels(
4246 const std::vector<std::string>& active_channels,
4247 bool is_local_update) {
4248 auto it = rtp_data_channels_.begin();
4249 while (it != rtp_data_channels_.end()) {
4250 DataChannel* data_channel = it->second;
4251 if (std::find(active_channels.begin(), active_channels.end(),
4252 data_channel->label()) != active_channels.end()) {
4253 ++it;
4254 continue;
4255 }
4256
4257 if (is_local_update) {
4258 data_channel->SetSendSsrc(0);
4259 } else {
4260 data_channel->RemotePeerRequestClose();
4261 }
4262
4263 if (data_channel->state() == DataChannel::kClosed) {
4264 rtp_data_channels_.erase(it);
4265 it = rtp_data_channels_.begin();
4266 } else {
4267 ++it;
4268 }
4269 }
4270}
4271
4272void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4273 uint32_t remote_ssrc) {
4274 rtc::scoped_refptr<DataChannel> channel(
4275 InternalCreateDataChannel(label, nullptr));
4276 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004277 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004278 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004279 return;
4280 }
4281 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004282 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4283 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004284 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004285}
4286
4287rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4288 const std::string& label,
4289 const InternalDataChannelInit* config) {
4290 if (IsClosed()) {
4291 return nullptr;
4292 }
Steve Anton75737c02017-11-06 10:37:17 -08004293 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004294 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004295 << "InternalCreateDataChannel: Data is not supported in this call.";
4296 return nullptr;
4297 }
4298 InternalDataChannelInit new_config =
4299 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004300 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004301 if (new_config.id < 0) {
4302 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004303 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004304 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004305 RTC_LOG(LS_ERROR)
4306 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004307 return nullptr;
4308 }
4309 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004310 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004311 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004312 return nullptr;
4313 }
4314 }
4315
Steve Anton75737c02017-11-06 10:37:17 -08004316 rtc::scoped_refptr<DataChannel> channel(
4317 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004318 if (!channel) {
4319 sid_allocator_.ReleaseSid(new_config.id);
4320 return nullptr;
4321 }
4322
4323 if (channel->data_channel_type() == cricket::DCT_RTP) {
4324 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004325 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4326 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004327 return nullptr;
4328 }
4329 rtp_data_channels_[channel->label()] = channel;
4330 } else {
4331 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4332 sctp_data_channels_.push_back(channel);
4333 channel->SignalClosed.connect(this,
4334 &PeerConnection::OnSctpDataChannelClosed);
4335 }
4336
Steve Anton2d8609c2018-01-23 16:38:46 -08004337 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004338 return channel;
4339}
4340
4341bool PeerConnection::HasDataChannels() const {
4342 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4343}
4344
4345void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4346 for (const auto& channel : sctp_data_channels_) {
4347 if (channel->id() < 0) {
4348 int sid;
4349 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004350 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004351 continue;
4352 }
4353 channel->SetSctpSid(sid);
4354 }
4355 }
4356}
4357
4358void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004359 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004360 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4361 ++it) {
4362 if (it->get() == channel) {
4363 if (channel->id() >= 0) {
4364 sid_allocator_.ReleaseSid(channel->id());
4365 }
deadbeefbd292462015-12-14 18:15:29 -08004366 // Since this method is triggered by a signal from the DataChannel,
4367 // we can't free it directly here; we need to free it asynchronously.
4368 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004369 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004370 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4371 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004372 return;
4373 }
4374 }
4375}
4376
deadbeefab9b2d12015-10-14 11:33:11 -07004377void PeerConnection::OnDataChannelDestroyed() {
4378 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4379 // DataChannel may callback to us and try to modify the list.
4380 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4381 temp_rtp_dcs.swap(rtp_data_channels_);
4382 for (const auto& kv : temp_rtp_dcs) {
4383 kv.second->OnTransportChannelDestroyed();
4384 }
4385
4386 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4387 temp_sctp_dcs.swap(sctp_data_channels_);
4388 for (const auto& channel : temp_sctp_dcs) {
4389 channel->OnTransportChannelDestroyed();
4390 }
4391}
4392
4393void PeerConnection::OnDataChannelOpenMessage(
4394 const std::string& label,
4395 const InternalDataChannelInit& config) {
4396 rtc::scoped_refptr<DataChannel> channel(
4397 InternalCreateDataChannel(label, &config));
4398 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004399 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004400 return;
4401 }
4402
deadbeefa601f5c2016-06-06 14:27:39 -07004403 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4404 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004405 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004406}
4407
Steve Anton4171afb2017-11-20 10:20:22 -08004408rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4409PeerConnection::GetAudioTransceiver() const {
4410 // This method only works with Plan B SDP, where there is a single
4411 // audio/video transceiver.
4412 RTC_DCHECK(!IsUnifiedPlan());
4413 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004414 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004415 return transceiver;
4416 }
4417 }
4418 RTC_NOTREACHED();
4419 return nullptr;
4420}
4421
4422rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4423PeerConnection::GetVideoTransceiver() const {
4424 // This method only works with Plan B SDP, where there is a single
4425 // audio/video transceiver.
4426 RTC_DCHECK(!IsUnifiedPlan());
4427 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004428 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004429 return transceiver;
4430 }
4431 }
4432 RTC_NOTREACHED();
4433 return nullptr;
4434}
4435
4436// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4437// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004438bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004439 switch (type) {
4440 case cricket::MEDIA_TYPE_AUDIO:
4441 return !GetAudioTransceiver()->internal()->senders().empty();
4442 case cricket::MEDIA_TYPE_VIDEO:
4443 return !GetVideoTransceiver()->internal()->senders().empty();
4444 case cricket::MEDIA_TYPE_DATA:
4445 return false;
4446 }
4447 RTC_NOTREACHED();
4448 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004449}
4450
Steve Anton4171afb2017-11-20 10:20:22 -08004451rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4452PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4453 for (auto transceiver : transceivers_) {
4454 for (auto sender : transceiver->internal()->senders()) {
4455 if (sender->track() == track) {
4456 return sender;
4457 }
4458 }
4459 }
4460 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004461}
4462
Steve Anton4171afb2017-11-20 10:20:22 -08004463rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4464PeerConnection::FindSenderById(const std::string& sender_id) const {
4465 for (auto transceiver : transceivers_) {
4466 for (auto sender : transceiver->internal()->senders()) {
4467 if (sender->id() == sender_id) {
4468 return sender;
4469 }
4470 }
4471 }
4472 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004473}
4474
Steve Anton4171afb2017-11-20 10:20:22 -08004475rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4476PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4477 for (auto transceiver : transceivers_) {
4478 for (auto receiver : transceiver->internal()->receivers()) {
4479 if (receiver->id() == receiver_id) {
4480 return receiver;
4481 }
4482 }
4483 }
4484 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004485}
4486
Steve Anton4171afb2017-11-20 10:20:22 -08004487std::vector<PeerConnection::RtpSenderInfo>*
4488PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4489 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4490 media_type == cricket::MEDIA_TYPE_VIDEO);
4491 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4492 ? &remote_audio_sender_infos_
4493 : &remote_video_sender_infos_;
4494}
4495
4496std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004497 cricket::MediaType media_type) {
4498 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4499 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004500 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4501 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004502}
4503
Steve Anton4171afb2017-11-20 10:20:22 -08004504const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4505 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Steve Anton4171afb2017-11-20 10:20:22 -08004506 const std::string sender_id) const {
4507 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson15502922018-03-26 10:06:46 -07004508 if (sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004509 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004510 }
4511 }
4512 return nullptr;
4513}
4514
4515DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4516 for (const auto& channel : sctp_data_channels_) {
4517 if (channel->id() == sid) {
4518 return channel;
4519 }
4520 }
4521 return nullptr;
4522}
4523
deadbeef91dd5672016-05-18 16:55:30 -07004524bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004525 const RTCConfiguration& configuration) {
4526 cricket::ServerAddresses stun_servers;
4527 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004528 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4529 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004530 return false;
4531 }
4532
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004533 port_allocator_->Initialize();
4534
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004535 // To handle both internal and externally created port allocator, we will
4536 // enable BUNDLE here.
4537 int portallocator_flags = port_allocator_->flags();
4538 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004539 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4540 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004541 // If the disable-IPv6 flag was specified, we'll not override it
4542 // by experiment.
4543 if (configuration.disable_ipv6) {
4544 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004545 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4546 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004547 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4548 }
4549
zhihuangb09b3f92017-03-07 14:40:51 -08004550 if (configuration.disable_ipv6_on_wifi) {
4551 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004552 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004553 }
4554
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004555 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4556 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004557 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004558 }
4559
honghaiz60347052016-05-31 18:29:12 -07004560 if (configuration.candidate_network_policy ==
4561 kCandidateNetworkPolicyLowCost) {
4562 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004563 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004564 }
4565
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004566 if (configuration.disable_link_local_networks) {
4567 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4568 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4569 }
4570
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004571 port_allocator_->set_flags(portallocator_flags);
4572 // No step delay is used while allocating ports.
4573 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4574 port_allocator_->set_candidate_filter(
4575 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004576 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004577
4578 // Call this last since it may create pooled allocator sessions using the
4579 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004580 port_allocator_->SetConfiguration(
4581 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4582 configuration.prune_turn_ports, configuration.turn_customizer,
4583 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004584 return true;
4585}
4586
deadbeef91dd5672016-05-18 16:55:30 -07004587bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004588 const cricket::ServerAddresses& stun_servers,
4589 const std::vector<cricket::RelayServerConfig>& turn_servers,
4590 IceTransportsType type,
4591 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004592 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004593 webrtc::TurnCustomizer* turn_customizer,
4594 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004595 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004596 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004597 // Call this last since it may create pooled allocator sessions using the
4598 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004599 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004600 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004601 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004602}
4603
Steve Antonba818672017-11-06 10:21:57 -08004604cricket::ChannelManager* PeerConnection::channel_manager() const {
4605 return factory_->channel_manager();
4606}
4607
4608MetricsObserverInterface* PeerConnection::metrics_observer() const {
4609 return uma_observer_;
4610}
4611
Elad Alon99c3fe52017-10-13 16:29:40 +02004612bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004613 std::unique_ptr<RtcEventLogOutput> output,
4614 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004615 if (!event_log_) {
4616 return false;
4617 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004618 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004619}
4620
4621void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004622 if (event_log_) {
4623 event_log_->StopLogging();
4624 }
ivoc14d5dbe2016-07-04 07:06:55 -07004625}
nisseeaabdf62017-05-05 02:23:02 -07004626
Steve Anton75737c02017-11-06 10:37:17 -08004627cricket::BaseChannel* PeerConnection::GetChannel(
4628 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004629 for (auto transceiver : transceivers_) {
4630 cricket::BaseChannel* channel = transceiver->internal()->channel();
4631 if (channel && channel->content_name() == content_name) {
4632 return channel;
4633 }
Steve Anton75737c02017-11-06 10:37:17 -08004634 }
4635 if (rtp_data_channel() &&
4636 rtp_data_channel()->content_name() == content_name) {
4637 return rtp_data_channel();
4638 }
4639 return nullptr;
4640}
4641
4642bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4643 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004644 RTC_LOG(LS_INFO)
4645 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004646 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004647 return false;
4648 }
4649 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004650 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004651 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004652 return false;
4653 }
4654
4655 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4656}
4657
4658bool PeerConnection::GetSslRole(const std::string& content_name,
4659 rtc::SSLRole* role) {
4660 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004661 RTC_LOG(LS_INFO)
4662 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004663 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004664 return false;
4665 }
4666
4667 return transport_controller_->GetSslRole(GetTransportName(content_name),
4668 role);
4669}
4670
Steve Antonf8470812017-12-04 10:46:21 -08004671void PeerConnection::SetSessionError(SessionError error,
4672 const std::string& error_desc) {
4673 RTC_DCHECK_RUN_ON(signaling_thread());
4674 if (error != session_error_) {
4675 session_error_ = error;
4676 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004677 }
4678}
4679
Steve Anton3828c062017-12-06 10:34:51 -08004680RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004681 cricket::ContentSource source) {
4682 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004683
4684 // If there's already a pending error then no state transition should happen.
4685 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004686 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004687
4688 // If this is an answer then we know whether to BUNDLE or not. If both the
4689 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004690 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004691 const cricket::ContentGroup* local_bundle =
4692 local_description()->description()->GetGroupByName(
4693 cricket::GROUP_TYPE_BUNDLE);
4694 const cricket::ContentGroup* remote_bundle =
4695 remote_description()->description()->GetGroupByName(
4696 cricket::GROUP_TYPE_BUNDLE);
4697 if (local_bundle && remote_bundle) {
4698 // The answerer decides the transport to bundle on.
4699 const cricket::ContentGroup* answer_bundle =
4700 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4701 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004702 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4703 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004704 }
4705 }
Steve Anton75737c02017-11-06 10:37:17 -08004706 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004707
4708 // Only push down the transport description after potentially enabling BUNDLE;
4709 // we don't want to push down a description on a transport about to be
4710 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004711 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004712 if (!error.ok()) {
4713 return error;
4714 }
4715
4716 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004717 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004718 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004719 }
4720
4721 // Update the signaling state according to the specified state machine (see
4722 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004723 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004724 ChangeSignalingState(source == cricket::CS_LOCAL
4725 ? PeerConnectionInterface::kHaveLocalOffer
4726 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004727 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004728 ChangeSignalingState(source == cricket::CS_LOCAL
4729 ? PeerConnectionInterface::kHaveLocalPrAnswer
4730 : PeerConnectionInterface::kHaveRemotePrAnswer);
4731 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004732 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004733 ChangeSignalingState(PeerConnectionInterface::kStable);
4734 }
4735
4736 // Update internal objects according to the session description's media
4737 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004738 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004739 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004740 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004741 }
4742
Steve Anton8a006912017-12-04 15:25:56 -08004743 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004744}
4745
Steve Anton8a006912017-12-04 15:25:56 -08004746RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004747 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004748 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004749 const SessionDescriptionInterface* sdesc =
4750 (source == cricket::CS_LOCAL ? local_description()
4751 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004752 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004753
4754 // Push down the new SDP media section for each audio/video transceiver.
4755 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004756 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004757 FindMediaSectionForTransceiver(transceiver, sdesc);
4758 cricket::BaseChannel* channel = transceiver->internal()->channel();
4759 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004760 continue;
4761 }
4762 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004763 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004764 if (!content_desc) {
4765 continue;
4766 }
4767 std::string error;
4768 bool success =
4769 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004770 ? channel->SetLocalContent(content_desc, type, &error)
4771 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004772 if (!success) {
4773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4774 }
4775 }
4776
4777 // If using the RtpDataChannel, push down the new SDP section for it too.
4778 if (rtp_data_channel_) {
4779 const ContentInfo* data_content =
4780 cricket::GetFirstDataContent(sdesc->description());
4781 if (data_content && !data_content->rejected) {
4782 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004783 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004784 if (data_desc) {
4785 std::string error;
4786 bool success =
4787 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004788 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4789 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004790 &error);
4791 if (!success) {
4792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4793 std::move(error));
4794 }
Steve Anton75737c02017-11-06 10:37:17 -08004795 }
4796 }
4797 }
Steve Antoned10bd92017-12-05 10:52:59 -08004798
Steve Anton75737c02017-11-06 10:37:17 -08004799 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4800 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4801 if (sctp_transport_ && local_description() && remote_description() &&
4802 cricket::GetFirstDataContent(local_description()->description()) &&
4803 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004804 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004805 RTC_FROM_HERE,
4806 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004807 if (!success) {
4808 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4809 "Failed to push down SCTP parameters.");
4810 }
Steve Anton75737c02017-11-06 10:37:17 -08004811 }
Steve Antoned10bd92017-12-05 10:52:59 -08004812
Steve Anton8a006912017-12-04 15:25:56 -08004813 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004814}
4815
4816bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4817 RTC_DCHECK(network_thread()->IsCurrent());
4818 RTC_DCHECK(local_description());
4819 RTC_DCHECK(remote_description());
4820 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4821 // When we support "max-message-size", that would also be pushed down here.
4822 return sctp_transport_->Start(
4823 GetSctpPort(local_description()->description()),
4824 GetSctpPort(remote_description()->description()));
4825}
4826
Steve Anton8a006912017-12-04 15:25:56 -08004827RTCError PeerConnection::PushdownTransportDescription(
4828 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004829 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004830 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004831
Steve Anton8a006912017-12-04 15:25:56 -08004832 const SessionDescriptionInterface* sdesc =
4833 (source == cricket::CS_LOCAL ? local_description()
4834 : remote_description());
4835 RTC_DCHECK(sdesc);
4836 for (const cricket::TransportInfo& tinfo :
4837 sdesc->description()->transport_infos()) {
4838 std::string error;
4839 bool success;
4840 if (source == cricket::CS_LOCAL) {
4841 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004842 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004843 } else {
4844 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004845 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004846 }
4847 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004848 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4849 "Failed to push down transport description for " +
4850 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004851 }
4852 }
4853
Steve Anton8a006912017-12-04 15:25:56 -08004854 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004855}
4856
4857bool PeerConnection::GetTransportDescription(
4858 const SessionDescription* description,
4859 const std::string& content_name,
4860 cricket::TransportDescription* tdesc) {
4861 if (!description || !tdesc) {
4862 return false;
4863 }
4864 const TransportInfo* transport_info =
4865 description->GetTransportInfoByName(content_name);
4866 if (!transport_info) {
4867 return false;
4868 }
4869 *tdesc = transport_info->description;
4870 return true;
4871}
4872
4873bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4874 const std::string* first_content_name = bundle.FirstContentName();
4875 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004876 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004877 return false;
4878 }
4879 const std::string& transport_name = *first_content_name;
4880
4881 auto maybe_set_transport = [this, bundle,
4882 transport_name](cricket::BaseChannel* ch) {
4883 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004884 return;
Steve Anton75737c02017-11-06 10:37:17 -08004885 }
4886
4887 std::string old_transport_name = ch->transport_name();
4888 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004889 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4890 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004891 return;
Steve Anton75737c02017-11-06 10:37:17 -08004892 }
4893
4894 cricket::DtlsTransportInternal* rtp_dtls_transport =
4895 transport_controller_->CreateDtlsTransport(
4896 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4897 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4898 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4899 if (need_rtcp) {
4900 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4901 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4902 }
4903
4904 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004905 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4906 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004907 transport_controller_->DestroyDtlsTransport(
4908 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4909 // If the channel needs rtcp, it means that the channel used to have a
4910 // rtcp transport which needs to be deleted now.
4911 if (need_rtcp) {
4912 transport_controller_->DestroyDtlsTransport(
4913 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4914 }
Steve Anton75737c02017-11-06 10:37:17 -08004915 };
4916
Steve Antoned10bd92017-12-05 10:52:59 -08004917 for (auto transceiver : transceivers_) {
4918 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004919 }
Steve Antoned10bd92017-12-05 10:52:59 -08004920 maybe_set_transport(rtp_data_channel_);
4921
Steve Anton75737c02017-11-06 10:37:17 -08004922 // For SCTP, transport creation/deletion happens here instead of in the
4923 // object itself.
4924 if (sctp_transport_) {
4925 RTC_DCHECK(sctp_transport_name_);
4926 RTC_DCHECK(sctp_content_name_);
4927 if (transport_name != *sctp_transport_name_ &&
4928 bundle.HasContentName(*sctp_content_name_)) {
4929 network_thread()->Invoke<void>(
4930 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4931 transport_name));
4932 }
4933 }
4934
4935 return true;
4936}
4937
Steve Anton75737c02017-11-06 10:37:17 -08004938cricket::IceConfig PeerConnection::ParseIceConfig(
4939 const PeerConnectionInterface::RTCConfiguration& config) const {
4940 cricket::ContinualGatheringPolicy gathering_policy;
4941 // TODO(honghaiz): Add the third continual gathering policy in
4942 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4943 switch (config.continual_gathering_policy) {
4944 case PeerConnectionInterface::GATHER_ONCE:
4945 gathering_policy = cricket::GATHER_ONCE;
4946 break;
4947 case PeerConnectionInterface::GATHER_CONTINUALLY:
4948 gathering_policy = cricket::GATHER_CONTINUALLY;
4949 break;
4950 default:
4951 RTC_NOTREACHED();
4952 gathering_policy = cricket::GATHER_ONCE;
4953 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004954
Steve Anton75737c02017-11-06 10:37:17 -08004955 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004956 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4957 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004958 ice_config.prioritize_most_likely_candidate_pairs =
4959 config.prioritize_most_likely_ice_candidate_pairs;
4960 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004961 RTCConfigurationToIceConfigOptionalInt(
4962 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004963 ice_config.continual_gathering_policy = gathering_policy;
4964 ice_config.presume_writable_when_fully_relayed =
4965 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004966 ice_config.ice_check_interval_strong_connectivity =
4967 config.ice_check_interval_strong_connectivity;
4968 ice_config.ice_check_interval_weak_connectivity =
4969 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004970 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004971 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004972 ice_config.regather_all_networks_interval_range =
4973 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004974 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004975 return ice_config;
4976}
4977
Steve Anton75737c02017-11-06 10:37:17 -08004978bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4979 std::string* track_id) {
4980 if (!local_description()) {
4981 return false;
4982 }
4983 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4984 track_id);
4985}
4986
4987bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4988 std::string* track_id) {
4989 if (!remote_description()) {
4990 return false;
4991 }
4992 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4993 track_id);
4994}
4995
4996bool PeerConnection::SendData(const cricket::SendDataParams& params,
4997 const rtc::CopyOnWriteBuffer& payload,
4998 cricket::SendDataResult* result) {
4999 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005000 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005001 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005002 return false;
5003 }
5004 return rtp_data_channel_
5005 ? rtp_data_channel_->SendData(params, payload, result)
5006 : network_thread()->Invoke<bool>(
5007 RTC_FROM_HERE,
5008 Bind(&cricket::SctpTransportInternal::SendData,
5009 sctp_transport_.get(), params, payload, result));
5010}
5011
5012bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5013 if (!rtp_data_channel_ && !sctp_transport_) {
5014 // Don't log an error here, because DataChannels are expected to call
5015 // ConnectDataChannel in this state. It's the only way to initially tell
5016 // whether or not the underlying transport is ready.
5017 return false;
5018 }
5019 if (rtp_data_channel_) {
5020 rtp_data_channel_->SignalReadyToSendData.connect(
5021 webrtc_data_channel, &DataChannel::OnChannelReady);
5022 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5023 &DataChannel::OnDataReceived);
5024 } else {
5025 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5026 &DataChannel::OnChannelReady);
5027 SignalSctpDataReceived.connect(webrtc_data_channel,
5028 &DataChannel::OnDataReceived);
5029 SignalSctpStreamClosedRemotely.connect(
5030 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5031 }
5032 return true;
5033}
5034
5035void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5036 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005037 RTC_LOG(LS_ERROR)
5038 << "DisconnectDataChannel called when rtp_data_channel_ and "
5039 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005040 return;
5041 }
5042 if (rtp_data_channel_) {
5043 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5044 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5045 } else {
5046 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5047 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5048 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5049 }
5050}
5051
5052void PeerConnection::AddSctpDataStream(int sid) {
5053 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005054 RTC_LOG(LS_ERROR)
5055 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005056 return;
5057 }
5058 network_thread()->Invoke<void>(
5059 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5060 sctp_transport_.get(), sid));
5061}
5062
5063void PeerConnection::RemoveSctpDataStream(int sid) {
5064 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005065 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005066 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005067 return;
5068 }
5069 network_thread()->Invoke<void>(
5070 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5071 sctp_transport_.get(), sid));
5072}
5073
5074bool PeerConnection::ReadyToSendData() const {
5075 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5076 sctp_ready_to_send_data_;
5077}
5078
Qingsi Wang72a43a12018-02-20 16:03:18 -08005079cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5080 cricket::CandidateStatsList candidate_states_list;
5081 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5082 return candidate_states_list;
5083}
5084
Steve Anton5dfde182018-02-06 10:34:40 -08005085std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5086 const {
5087 std::map<std::string, std::string> transport_names_by_mid;
5088 for (auto transceiver : transceivers_) {
5089 cricket::BaseChannel* channel = transceiver->internal()->channel();
5090 if (channel) {
5091 transport_names_by_mid[channel->content_name()] =
5092 channel->transport_name();
5093 }
Steve Anton75737c02017-11-06 10:37:17 -08005094 }
Steve Anton5dfde182018-02-06 10:34:40 -08005095 if (rtp_data_channel_) {
5096 transport_names_by_mid[rtp_data_channel_->content_name()] =
5097 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005098 }
5099 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005100 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
Steve Anton5dfde182018-02-06 10:34:40 -08005102 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005103}
5104
Steve Anton5dfde182018-02-06 10:34:40 -08005105std::map<std::string, cricket::TransportStats>
5106PeerConnection::GetTransportStatsByNames(
5107 const std::set<std::string>& transport_names) {
5108 if (!network_thread()->IsCurrent()) {
5109 return network_thread()
5110 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5111 RTC_FROM_HERE,
5112 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005113 }
Steve Anton5dfde182018-02-06 10:34:40 -08005114 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5115 for (const std::string& transport_name : transport_names) {
5116 cricket::TransportStats transport_stats;
5117 bool success =
5118 transport_controller_->GetStats(transport_name, &transport_stats);
5119 if (success) {
5120 transport_stats_by_name[transport_name] = std::move(transport_stats);
5121 } else {
5122 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5123 << transport_name;
5124 }
5125 }
5126 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005127}
5128
5129bool PeerConnection::GetLocalCertificate(
5130 const std::string& transport_name,
5131 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5132 return transport_controller_->GetLocalCertificate(transport_name,
5133 certificate);
5134}
5135
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005136std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005137 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005138 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005139}
5140
5141cricket::DataChannelType PeerConnection::data_channel_type() const {
5142 return data_channel_type_;
5143}
5144
5145bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5146 return pending_ice_restarts_.find(content_name) !=
5147 pending_ice_restarts_.end();
5148}
5149
Steve Anton75737c02017-11-06 10:37:17 -08005150bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5151 return transport_controller_->NeedsIceRestart(content_name);
5152}
5153
5154void PeerConnection::OnCertificateReady(
5155 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5156 transport_controller_->SetLocalCertificate(certificate);
5157}
5158
5159void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005160 SetSessionError(SessionError::kTransport,
5161 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005162}
5163
5164void PeerConnection::OnTransportControllerConnectionState(
5165 cricket::IceConnectionState state) {
5166 switch (state) {
5167 case cricket::kIceConnectionConnecting:
5168 // If the current state is Connected or Completed, then there were
5169 // writable channels but now there are not, so the next state must
5170 // be Disconnected.
5171 // kIceConnectionConnecting is currently used as the default,
5172 // un-connected state by the TransportController, so its only use is
5173 // detecting disconnections.
5174 if (ice_connection_state_ ==
5175 PeerConnectionInterface::kIceConnectionConnected ||
5176 ice_connection_state_ ==
5177 PeerConnectionInterface::kIceConnectionCompleted) {
5178 SetIceConnectionState(
5179 PeerConnectionInterface::kIceConnectionDisconnected);
5180 }
5181 break;
5182 case cricket::kIceConnectionFailed:
5183 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5184 break;
5185 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005187 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005188 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5189 break;
5190 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005191 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005192 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005193 if (ice_connection_state_ !=
5194 PeerConnectionInterface::kIceConnectionConnected) {
5195 // If jumping directly from "checking" to "connected",
5196 // signal "connected" first.
5197 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5198 }
5199 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5200 if (metrics_observer()) {
5201 ReportTransportStats();
5202 }
5203 break;
5204 default:
5205 RTC_NOTREACHED();
5206 }
5207}
5208
5209void PeerConnection::OnTransportControllerCandidatesGathered(
5210 const std::string& transport_name,
5211 const cricket::Candidates& candidates) {
5212 RTC_DCHECK(signaling_thread()->IsCurrent());
5213 int sdp_mline_index;
5214 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005215 RTC_LOG(LS_ERROR)
5216 << "OnTransportControllerCandidatesGathered: content name "
5217 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005218 return;
5219 }
5220
5221 for (cricket::Candidates::const_iterator citer = candidates.begin();
5222 citer != candidates.end(); ++citer) {
5223 // Use transport_name as the candidate media id.
5224 std::unique_ptr<JsepIceCandidate> candidate(
5225 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5226 if (local_description()) {
5227 mutable_local_description()->AddCandidate(candidate.get());
5228 }
5229 OnIceCandidate(std::move(candidate));
5230 }
5231}
5232
5233void PeerConnection::OnTransportControllerCandidatesRemoved(
5234 const std::vector<cricket::Candidate>& candidates) {
5235 RTC_DCHECK(signaling_thread()->IsCurrent());
5236 // Sanity check.
5237 for (const cricket::Candidate& candidate : candidates) {
5238 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005239 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005240 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005241 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005242 return;
5243 }
5244 }
5245
5246 if (local_description()) {
5247 mutable_local_description()->RemoveCandidates(candidates);
5248 }
5249 OnIceCandidatesRemoved(candidates);
5250}
5251
5252void PeerConnection::OnTransportControllerDtlsHandshakeError(
5253 rtc::SSLHandshakeError error) {
5254 if (metrics_observer()) {
5255 metrics_observer()->IncrementEnumCounter(
5256 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5257 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5258 }
5259}
5260
Steve Antoned10bd92017-12-05 10:52:59 -08005261void PeerConnection::EnableSending() {
5262 for (auto transceiver : transceivers_) {
5263 cricket::BaseChannel* channel = transceiver->internal()->channel();
5264 if (channel && !channel->enabled()) {
5265 channel->Enable(true);
5266 }
Steve Anton75737c02017-11-06 10:37:17 -08005267 }
5268
Steve Anton4171afb2017-11-20 10:20:22 -08005269 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005270 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005271 }
Steve Anton75737c02017-11-06 10:37:17 -08005272}
5273
5274// Returns the media index for a local ice candidate given the content name.
5275bool PeerConnection::GetLocalCandidateMediaIndex(
5276 const std::string& content_name,
5277 int* sdp_mline_index) {
5278 if (!local_description() || !sdp_mline_index) {
5279 return false;
5280 }
5281
5282 bool content_found = false;
5283 const ContentInfos& contents = local_description()->description()->contents();
5284 for (size_t index = 0; index < contents.size(); ++index) {
5285 if (contents[index].name == content_name) {
5286 *sdp_mline_index = static_cast<int>(index);
5287 content_found = true;
5288 break;
5289 }
5290 }
5291 return content_found;
5292}
5293
5294bool PeerConnection::UseCandidatesInSessionDescription(
5295 const SessionDescriptionInterface* remote_desc) {
5296 if (!remote_desc) {
5297 return true;
5298 }
5299 bool ret = true;
5300
5301 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5302 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5303 for (size_t n = 0; n < candidates->count(); ++n) {
5304 const IceCandidateInterface* candidate = candidates->at(n);
5305 bool valid = false;
5306 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5307 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005308 RTC_LOG(LS_INFO)
5309 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005310 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005311 }
5312 continue;
5313 }
5314 ret = UseCandidate(candidate);
5315 if (!ret) {
5316 break;
5317 }
5318 }
5319 }
5320 return ret;
5321}
5322
5323bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5324 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5325 size_t remote_content_size =
5326 remote_description()->description()->contents().size();
5327 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005328 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005329 return false;
5330 }
5331
5332 cricket::ContentInfo content =
5333 remote_description()->description()->contents()[mediacontent_index];
5334 std::vector<cricket::Candidate> candidates;
5335 candidates.push_back(candidate->candidate());
5336 // Invoking BaseSession method to handle remote candidates.
5337 std::string error;
5338 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5339 &error)) {
5340 // Candidates successfully submitted for checking.
5341 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5342 ice_connection_state_ ==
5343 PeerConnectionInterface::kIceConnectionDisconnected) {
5344 // If state is New, then the session has just gotten its first remote ICE
5345 // candidates, so go to Checking.
5346 // If state is Disconnected, the session is re-using old candidates or
5347 // receiving additional ones, so go to Checking.
5348 // If state is Connected, stay Connected.
5349 // TODO(bemasc): If state is Connected, and the new candidates are for a
5350 // newly added transport, then the state actually _should_ move to
5351 // checking. Add a way to distinguish that case.
5352 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5353 }
5354 // TODO(bemasc): If state is Completed, go back to Connected.
5355 } else {
5356 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005357 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005358 }
5359 }
5360 return true;
5361}
5362
5363void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005364 // Destroy video channel first since it may have a pointer to the
5365 // voice channel.
5366 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005367 if (!video_info || video_info->rejected) {
5368 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005369 }
5370
Steve Anton6fec8802017-12-04 10:37:29 -08005371 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5372 if (!audio_info || audio_info->rejected) {
5373 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005374 }
5375
5376 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5377 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005378 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005379 }
5380}
5381
Steve Antoneda6ccd2017-12-04 10:21:55 -08005382std::string PeerConnection::GetTransportNameForMediaSection(
5383 const std::string& mid,
5384 const cricket::ContentGroup* bundle_group) const {
5385 if (!bundle_group) {
5386 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005387 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005388 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005389 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005390 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005391 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005392 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005393 if (!bundle_group->HasContentName(mid)) {
5394 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5395 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005396 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005397 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5398 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005399}
5400
Steve Antondcc3c022017-12-22 16:02:54 -08005401RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5402 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005403 const cricket::ContentGroup* bundle_group = nullptr;
5404 if (configuration_.bundle_policy ==
5405 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005406 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005407 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005408 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5409 "max-bundle configured but session description "
5410 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005411 }
5412 }
Steve Antondcc3c022017-12-22 16:02:54 -08005413 return std::move(bundle_group);
5414}
5415
5416RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5417 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5418 if (!bundle_group_or_error.ok()) {
5419 return bundle_group_or_error.MoveError();
5420 }
5421 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005422
Steve Antoneda6ccd2017-12-04 10:21:55 -08005423 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005424 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005425 if (voice && !voice->rejected &&
5426 !GetAudioTransceiver()->internal()->channel()) {
5427 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5428 voice->name,
5429 GetTransportNameForMediaSection(voice->name, bundle_group));
5430 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5432 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005433 }
5434 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5435 }
5436
Steve Antondcc3c022017-12-22 16:02:54 -08005437 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005438 if (video && !video->rejected &&
5439 !GetVideoTransceiver()->internal()->channel()) {
5440 cricket::VideoChannel* video_channel = CreateVideoChannel(
5441 video->name,
5442 GetTransportNameForMediaSection(video->name, bundle_group));
5443 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005444 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5445 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005446 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005447 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005448 }
5449
Steve Antondcc3c022017-12-22 16:02:54 -08005450 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005451 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5452 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005453 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5454 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5456 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458 }
5459
Steve Anton8a006912017-12-04 15:25:56 -08005460 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
Steve Anton4171afb2017-11-20 10:20:22 -08005463// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005464cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5465 const std::string& mid,
5466 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005467 cricket::DtlsTransportInternal* rtp_dtls_transport =
5468 transport_controller_->CreateDtlsTransport(
5469 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5470 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5471 if (configuration_.rtcp_mux_policy !=
5472 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5473 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5474 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5475 }
5476
5477 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5478 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005479 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5480 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005481 if (!voice_channel) {
5482 transport_controller_->DestroyDtlsTransport(
5483 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5484 if (rtcp_dtls_transport) {
5485 transport_controller_->DestroyDtlsTransport(
5486 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5487 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005488 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005489 }
Steve Anton75737c02017-11-06 10:37:17 -08005490 voice_channel->SignalRtcpMuxFullyActive.connect(
5491 this, &PeerConnection::DestroyRtcpTransport_n);
5492 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5493 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005494 voice_channel->SignalSentPacket.connect(this,
5495 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005496 if (uma_observer_) {
5497 voice_channel->SetMetricsObserver(uma_observer_);
5498 }
Steve Anton4171afb2017-11-20 10:20:22 -08005499
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005501}
5502
Steve Anton4171afb2017-11-20 10:20:22 -08005503// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005504cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5505 const std::string& mid,
5506 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005507 cricket::DtlsTransportInternal* rtp_dtls_transport =
5508 transport_controller_->CreateDtlsTransport(
5509 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5510 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5511 if (configuration_.rtcp_mux_policy !=
5512 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5513 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5514 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5515 }
5516
5517 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5518 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005519 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5520 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005521
5522 if (!video_channel) {
5523 transport_controller_->DestroyDtlsTransport(
5524 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5525 if (rtcp_dtls_transport) {
5526 transport_controller_->DestroyDtlsTransport(
5527 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5528 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005529 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005530 }
Steve Anton75737c02017-11-06 10:37:17 -08005531 video_channel->SignalRtcpMuxFullyActive.connect(
5532 this, &PeerConnection::DestroyRtcpTransport_n);
5533 video_channel->SignalDtlsSrtpSetupFailure.connect(
5534 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005535 video_channel->SignalSentPacket.connect(this,
5536 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005537 if (uma_observer_) {
5538 video_channel->SetMetricsObserver(uma_observer_);
5539 }
Steve Anton4171afb2017-11-20 10:20:22 -08005540
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Steve Antoneda6ccd2017-12-04 10:21:55 -08005544bool PeerConnection::CreateDataChannel(const std::string& mid,
5545 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005546 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5547 if (sctp) {
5548 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005549 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005550 << "Trying to create SCTP transport, but didn't compile with "
5551 "SCTP support (HAVE_SCTP)";
5552 return false;
5553 }
5554 if (!network_thread()->Invoke<bool>(
5555 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005556 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005557 return false;
5558 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005559 for (const auto& channel : sctp_data_channels_) {
5560 channel->OnTransportChannelCreated();
5561 }
Steve Anton75737c02017-11-06 10:37:17 -08005562 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005563 cricket::DtlsTransportInternal* rtp_dtls_transport =
5564 transport_controller_->CreateDtlsTransport(
5565 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5566 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5567 if (configuration_.rtcp_mux_policy !=
5568 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5569 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5570 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5571 }
5572
5573 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5574 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005575 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005576
5577 if (!rtp_data_channel_) {
5578 transport_controller_->DestroyDtlsTransport(
5579 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5580 if (rtcp_dtls_transport) {
5581 transport_controller_->DestroyDtlsTransport(
5582 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5583 }
5584 return false;
5585 }
5586
5587 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5588 this, &PeerConnection::DestroyRtcpTransport_n);
5589 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5590 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5591 rtp_data_channel_->SignalSentPacket.connect(
5592 this, &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005593 if (uma_observer_) {
5594 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5595 }
Steve Anton75737c02017-11-06 10:37:17 -08005596 }
5597
Steve Anton75737c02017-11-06 10:37:17 -08005598 return true;
5599}
5600
5601Call::Stats PeerConnection::GetCallStats() {
5602 if (!worker_thread()->IsCurrent()) {
5603 return worker_thread()->Invoke<Call::Stats>(
5604 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5605 }
5606 if (call_) {
5607 return call_->GetStats();
5608 } else {
5609 return Call::Stats();
5610 }
5611}
5612
Steve Anton75737c02017-11-06 10:37:17 -08005613bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5614 const std::string& transport_name) {
5615 RTC_DCHECK(network_thread()->IsCurrent());
5616 RTC_DCHECK(sctp_factory_);
5617 cricket::DtlsTransportInternal* tc =
5618 transport_controller_->CreateDtlsTransport_n(
5619 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5620 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5621 RTC_DCHECK(sctp_transport_);
5622 sctp_invoker_.reset(new rtc::AsyncInvoker());
5623 sctp_transport_->SignalReadyToSendData.connect(
5624 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5625 sctp_transport_->SignalDataReceived.connect(
5626 this, &PeerConnection::OnSctpTransportDataReceived_n);
5627 sctp_transport_->SignalStreamClosedRemotely.connect(
5628 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005629 sctp_transport_name_ = transport_name;
5630 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005631 return true;
5632}
5633
5634void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5635 RTC_DCHECK(network_thread()->IsCurrent());
5636 RTC_DCHECK(sctp_transport_);
5637 RTC_DCHECK(sctp_transport_name_);
5638 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005639 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005640 cricket::DtlsTransportInternal* tc =
5641 transport_controller_->CreateDtlsTransport_n(
5642 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5643 sctp_transport_->SetTransportChannel(tc);
5644 transport_controller_->DestroyDtlsTransport_n(
5645 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5646}
5647
5648void PeerConnection::DestroySctpTransport_n() {
5649 RTC_DCHECK(network_thread()->IsCurrent());
5650 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005651 transport_controller_->DestroyDtlsTransport_n(
5652 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005653 sctp_content_name_.reset();
5654 sctp_transport_name_.reset();
5655 sctp_invoker_.reset(nullptr);
5656 sctp_ready_to_send_data_ = false;
5657}
5658
5659void PeerConnection::OnSctpTransportReadyToSendData_n() {
5660 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5661 RTC_DCHECK(network_thread()->IsCurrent());
5662 // Note: Cannot use rtc::Bind here because it will grab a reference to
5663 // PeerConnection and potentially cause PeerConnection to live longer than
5664 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5665 // be destroyed before PeerConnection is destroyed, and at that point all
5666 // pending tasks will be cleared.
5667 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5668 OnSctpTransportReadyToSendData_s(true);
5669 });
5670}
5671
5672void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5673 RTC_DCHECK(signaling_thread()->IsCurrent());
5674 sctp_ready_to_send_data_ = ready;
5675 SignalSctpReadyToSendData(ready);
5676}
5677
5678void PeerConnection::OnSctpTransportDataReceived_n(
5679 const cricket::ReceiveDataParams& params,
5680 const rtc::CopyOnWriteBuffer& payload) {
5681 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5682 RTC_DCHECK(network_thread()->IsCurrent());
5683 // Note: Cannot use rtc::Bind here because it will grab a reference to
5684 // PeerConnection and potentially cause PeerConnection to live longer than
5685 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5686 // be destroyed before PeerConnection is destroyed, and at that point all
5687 // pending tasks will be cleared.
5688 sctp_invoker_->AsyncInvoke<void>(
5689 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5690 OnSctpTransportDataReceived_s(params, payload);
5691 });
5692}
5693
5694void PeerConnection::OnSctpTransportDataReceived_s(
5695 const cricket::ReceiveDataParams& params,
5696 const rtc::CopyOnWriteBuffer& payload) {
5697 RTC_DCHECK(signaling_thread()->IsCurrent());
5698 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5699 // Received OPEN message; parse and signal that a new data channel should
5700 // be created.
5701 std::string label;
5702 InternalDataChannelInit config;
5703 config.id = params.ssrc;
5704 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005705 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5706 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005707 return;
5708 }
5709 config.open_handshake_role = InternalDataChannelInit::kAcker;
5710 OnDataChannelOpenMessage(label, config);
5711 } else {
5712 // Otherwise just forward the signal.
5713 SignalSctpDataReceived(params, payload);
5714 }
5715}
5716
5717void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5718 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5719 RTC_DCHECK(network_thread()->IsCurrent());
5720 sctp_invoker_->AsyncInvoke<void>(
5721 RTC_FROM_HERE, signaling_thread(),
5722 rtc::Bind(&sigslot::signal1<int>::operator(),
5723 &SignalSctpStreamClosedRemotely, sid));
5724}
5725
5726// Returns false if bundle is enabled and rtcp_mux is disabled.
5727bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5728 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5729 if (!bundle_enabled)
5730 return true;
5731
5732 const cricket::ContentGroup* bundle_group =
5733 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5734 RTC_DCHECK(bundle_group != NULL);
5735
5736 const cricket::ContentInfos& contents = desc->contents();
5737 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5738 citer != contents.end(); ++citer) {
5739 const cricket::ContentInfo* content = (&*citer);
5740 RTC_DCHECK(content != NULL);
5741 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005742 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005743 if (!HasRtcpMuxEnabled(content))
5744 return false;
5745 }
5746 }
5747 // RTCP-MUX is enabled in all the contents.
5748 return true;
5749}
5750
5751bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005752 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005753}
5754
Steve Anton8a006912017-12-04 15:25:56 -08005755RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005756 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005757 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005758 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005759 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761
5762 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765
Steve Anton3828c062017-12-06 10:34:51 -08005766 SdpType type = sdesc->GetType();
5767 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5768 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005769 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005770 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005771 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005772 }
5773
5774 // Verify crypto settings.
5775 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005776 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5777 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005778 RTCError crypto_error =
5779 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005780 if (!crypto_error.ok()) {
5781 return crypto_error;
5782 }
Steve Anton75737c02017-11-06 10:37:17 -08005783 }
5784
5785 // Verify ice-ufrag and ice-pwd.
5786 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5788 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005789 }
5790
5791 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5793 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795
5796 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5797 // m-lines that do not rtcp-mux enabled.
5798
5799 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005800 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005801 // With an answer we want to compare the new answer session description with
5802 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005803 const cricket::SessionDescription* offer_desc =
5804 (source == cricket::CS_LOCAL) ? remote_description()->description()
5805 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5807 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5808 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5810 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005811 }
5812 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005813 // The re-offers should respect the order of m= sections in current
5814 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005815 // With a re-offer, either the current local or current remote descriptions
5816 // could be the most up to date, so we would like to check against both of
5817 // them if they exist. It could be the case that one of them has a 0 port
5818 // for a media section, but the other does not. This is important to check
5819 // against in the case that we are recycling an m= section.
5820 const cricket::SessionDescription* current_desc = nullptr;
5821 const cricket::SessionDescription* secondary_current_desc = nullptr;
5822 if (local_description()) {
5823 current_desc = local_description()->description();
5824 if (remote_description()) {
5825 secondary_current_desc = remote_description()->description();
5826 }
5827 } else if (remote_description()) {
5828 current_desc = remote_description()->description();
5829 }
Steve Anton75737c02017-11-06 10:37:17 -08005830 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005831 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5832 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5834 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005835 }
5836 }
5837
Steve Anton8a006912017-12-04 15:25:56 -08005838 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005839}
5840
Steve Anton3828c062017-12-06 10:34:51 -08005841bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005842 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005843 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005844 return (state == PeerConnectionInterface::kStable) ||
5845 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005846 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005847 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005848 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5849 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5850 }
5851}
5852
Steve Anton3828c062017-12-06 10:34:51 -08005853bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005854 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005855 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005856 return (state == PeerConnectionInterface::kStable) ||
5857 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005858 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005859 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005860 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5861 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5862 }
5863}
5864
Steve Antonf8470812017-12-04 10:46:21 -08005865const char* PeerConnection::SessionErrorToString(SessionError error) const {
5866 switch (error) {
5867 case SessionError::kNone:
5868 return "ERROR_NONE";
5869 case SessionError::kContent:
5870 return "ERROR_CONTENT";
5871 case SessionError::kTransport:
5872 return "ERROR_TRANSPORT";
5873 }
5874 RTC_NOTREACHED();
5875 return "";
5876}
5877
Steve Anton75737c02017-11-06 10:37:17 -08005878std::string PeerConnection::GetSessionErrorMsg() {
5879 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005880 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5881 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005882 return desc.str();
5883}
5884
Steve Anton8e20f172018-03-06 10:55:04 -08005885void PeerConnection::ReportSdpFormatReceived(
5886 const SessionDescriptionInterface& remote_offer) {
5887 if (!uma_observer_) {
5888 return;
5889 }
5890 int num_audio_mlines = 0;
5891 int num_video_mlines = 0;
5892 int num_audio_tracks = 0;
5893 int num_video_tracks = 0;
5894 for (const ContentInfo& content : remote_offer.description()->contents()) {
5895 cricket::MediaType media_type = content.media_description()->type();
5896 int num_tracks = std::max(
5897 1, static_cast<int>(content.media_description()->streams().size()));
5898 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5899 num_audio_mlines += 1;
5900 num_audio_tracks += num_tracks;
5901 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5902 num_video_mlines += 1;
5903 num_video_tracks += num_tracks;
5904 }
5905 }
5906 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5907 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5908 format = kSdpFormatReceivedComplexUnifiedPlan;
5909 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5910 format = kSdpFormatReceivedComplexPlanB;
5911 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5912 format = kSdpFormatReceivedSimple;
5913 }
5914 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5915 kSdpFormatReceivedMax);
5916}
5917
Steve Anton0ffaaa22018-02-23 10:31:30 -08005918void PeerConnection::ReportNegotiatedSdpSemantics(
5919 const SessionDescriptionInterface& answer) {
5920 if (!uma_observer_) {
5921 return;
5922 }
5923 switch (answer.description()->msid_signaling()) {
5924 case 0:
5925 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5926 kSdpSemanticNegotiatedNone,
5927 kSdpSemanticNegotiatedMax);
5928 break;
5929 case cricket::kMsidSignalingMediaSection:
5930 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5931 kSdpSemanticNegotiatedUnifiedPlan,
5932 kSdpSemanticNegotiatedMax);
5933 break;
5934 case cricket::kMsidSignalingSsrcAttribute:
5935 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5936 kSdpSemanticNegotiatedPlanB,
5937 kSdpSemanticNegotiatedMax);
5938 break;
5939 case cricket::kMsidSignalingMediaSection |
5940 cricket::kMsidSignalingSsrcAttribute:
5941 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5942 kSdpSemanticNegotiatedMixed,
5943 kSdpSemanticNegotiatedMax);
5944 break;
5945 default:
5946 RTC_NOTREACHED();
5947 }
5948}
5949
Steve Anton75737c02017-11-06 10:37:17 -08005950// We need to check the local/remote description for the Transport instead of
5951// the session, because a new Transport added during renegotiation may have
5952// them unset while the session has them set from the previous negotiation.
5953// Not doing so may trigger the auto generation of transport description and
5954// mess up DTLS identity information, ICE credential, etc.
5955bool PeerConnection::ReadyToUseRemoteCandidate(
5956 const IceCandidateInterface* candidate,
5957 const SessionDescriptionInterface* remote_desc,
5958 bool* valid) {
5959 *valid = true;
5960
5961 const SessionDescriptionInterface* current_remote_desc =
5962 remote_desc ? remote_desc : remote_description();
5963
5964 if (!current_remote_desc) {
5965 return false;
5966 }
5967
5968 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5969 size_t remote_content_size =
5970 current_remote_desc->description()->contents().size();
5971 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005972 RTC_LOG(LS_ERROR)
5973 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5974 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005975
5976 *valid = false;
5977 return false;
5978 }
5979
5980 cricket::ContentInfo content =
5981 current_remote_desc->description()->contents()[mediacontent_index];
5982
5983 const std::string transport_name = GetTransportName(content.name);
5984 if (transport_name.empty()) {
5985 return false;
5986 }
5987 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5988}
5989
5990bool PeerConnection::SrtpRequired() const {
5991 return dtls_enabled_ ||
5992 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5993}
5994
5995void PeerConnection::OnTransportControllerGatheringState(
5996 cricket::IceGatheringState state) {
5997 RTC_DCHECK(signaling_thread()->IsCurrent());
5998 if (state == cricket::kIceGatheringGathering) {
5999 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6000 } else if (state == cricket::kIceGatheringComplete) {
6001 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6002 }
6003}
6004
6005void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006006 std::map<std::string, std::set<cricket::MediaType>>
6007 media_types_by_transport_name;
6008 for (auto transceiver : transceivers_) {
6009 if (transceiver->internal()->channel()) {
6010 const std::string& transport_name =
6011 transceiver->internal()->channel()->transport_name();
6012 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006013 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006014 }
Steve Anton75737c02017-11-06 10:37:17 -08006015 }
6016 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006017 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6018 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006019 }
6020 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006021 media_types_by_transport_name[*sctp_transport_name_].insert(
6022 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006023 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 for (const auto& entry : media_types_by_transport_name) {
6025 const std::string& transport_name = entry.first;
6026 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006027 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006028 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006029 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006030 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006031 }
6032 }
6033}
6034// Walk through the ConnectionInfos to gather best connection usage
6035// for IPv4 and IPv6.
6036void PeerConnection::ReportBestConnectionState(
6037 const cricket::TransportStats& stats) {
6038 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006039 for (const cricket::TransportChannelStats& channel_stats :
6040 stats.channel_stats) {
6041 for (const cricket::ConnectionInfo& connection_info :
6042 channel_stats.connection_infos) {
6043 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006044 continue;
6045 }
6046
6047 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006048 const cricket::Candidate& local = connection_info.local_candidate;
6049 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006050
6051 // Increment the counter for IceCandidatePairType.
6052 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6053 (local.type() == RELAY_PORT_TYPE &&
6054 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6055 type = kEnumCounterIceCandidatePairTypeTcp;
6056 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6057 type = kEnumCounterIceCandidatePairTypeUdp;
6058 } else {
6059 RTC_CHECK(0);
6060 }
6061 metrics_observer()->IncrementEnumCounter(
6062 type, GetIceCandidatePairCounter(local, remote),
6063 kIceCandidatePairMax);
6064
6065 // Increment the counter for IP type.
6066 if (local.address().family() == AF_INET) {
6067 metrics_observer()->IncrementEnumCounter(
6068 kEnumCounterAddressFamily, kBestConnections_IPv4,
6069 kPeerConnectionAddressFamilyCounter_Max);
6070
6071 } else if (local.address().family() == AF_INET6) {
6072 metrics_observer()->IncrementEnumCounter(
6073 kEnumCounterAddressFamily, kBestConnections_IPv6,
6074 kPeerConnectionAddressFamilyCounter_Max);
6075 } else {
6076 RTC_CHECK(0);
6077 }
6078
6079 return;
6080 }
6081 }
6082}
6083
6084void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006085 const cricket::TransportStats& stats,
6086 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006087 RTC_DCHECK(metrics_observer());
6088 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6089 return;
6090 }
6091
6092 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6093 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6094 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6095 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6096 return;
6097 }
6098
Steve Antonc7b964c2018-02-01 14:39:45 -08006099 for (cricket::MediaType media_type : media_types) {
6100 PeerConnectionEnumCounterType srtp_counter_type;
6101 PeerConnectionEnumCounterType ssl_counter_type;
6102 switch (media_type) {
6103 case cricket::MEDIA_TYPE_AUDIO:
6104 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6105 ssl_counter_type = kEnumCounterAudioSslCipher;
6106 break;
6107 case cricket::MEDIA_TYPE_VIDEO:
6108 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6109 ssl_counter_type = kEnumCounterVideoSslCipher;
6110 break;
6111 case cricket::MEDIA_TYPE_DATA:
6112 srtp_counter_type = kEnumCounterDataSrtpCipher;
6113 ssl_counter_type = kEnumCounterDataSslCipher;
6114 break;
6115 default:
6116 RTC_NOTREACHED();
6117 continue;
6118 }
6119 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6120 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6121 srtp_crypto_suite);
6122 }
6123 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6124 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6125 ssl_cipher_suite);
6126 }
Steve Anton75737c02017-11-06 10:37:17 -08006127 }
6128}
6129
6130void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6131 RTC_DCHECK(worker_thread()->IsCurrent());
6132 RTC_DCHECK(call_);
6133 call_->OnSentPacket(sent_packet);
6134}
6135
6136const std::string PeerConnection::GetTransportName(
6137 const std::string& content_name) {
6138 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006139 if (channel) {
6140 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006141 }
Steve Anton6fec8802017-12-04 10:37:29 -08006142 if (sctp_transport_) {
6143 RTC_DCHECK(sctp_content_name_);
6144 RTC_DCHECK(sctp_transport_name_);
6145 if (content_name == *sctp_content_name_) {
6146 return *sctp_transport_name_;
6147 }
6148 }
6149 // Return an empty string if failed to retrieve the transport name.
6150 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006151}
6152
6153void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6154 RTC_DCHECK(network_thread()->IsCurrent());
6155 transport_controller_->DestroyDtlsTransport_n(
6156 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6157}
6158
Steve Anton6fec8802017-12-04 10:37:29 -08006159void PeerConnection::DestroyTransceiverChannel(
6160 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6161 transceiver) {
6162 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006163
Steve Anton6fec8802017-12-04 10:37:29 -08006164 cricket::BaseChannel* channel = transceiver->internal()->channel();
6165 if (channel) {
6166 transceiver->internal()->SetChannel(nullptr);
6167 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006168 }
6169}
6170
6171void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006172 if (rtp_data_channel_) {
6173 OnDataChannelDestroyed();
6174 DestroyBaseChannel(rtp_data_channel_);
6175 rtp_data_channel_ = nullptr;
6176 }
6177
6178 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6179 // grab a reference to this PeerConnection. If this is called from the
6180 // PeerConnection destructor, the RefCountedObject vtable will have already
6181 // been destroyed (since it is a subclass of PeerConnection) and using
6182 // rtc::Bind will cause "Pure virtual function called" error to appear.
6183
6184 if (sctp_transport_) {
6185 OnDataChannelDestroyed();
6186 network_thread()->Invoke<void>(RTC_FROM_HERE,
6187 [this] { DestroySctpTransport_n(); });
6188 }
6189}
6190
6191void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6192 RTC_DCHECK(channel);
Zhi Huang97d5e5b2018-03-27 00:09:01 +00006193 RTC_DCHECK(channel->rtp_dtls_transport());
6194
Steve Anton6fec8802017-12-04 10:37:29 -08006195 // Need to cache these before destroying the base channel so that we do not
6196 // access uninitialized memory.
Zhi Huang97d5e5b2018-03-27 00:09:01 +00006197 const std::string transport_name =
6198 channel->rtp_dtls_transport()->transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006199 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6200
6201 switch (channel->media_type()) {
6202 case cricket::MEDIA_TYPE_AUDIO:
6203 channel_manager()->DestroyVoiceChannel(
6204 static_cast<cricket::VoiceChannel*>(channel));
6205 break;
6206 case cricket::MEDIA_TYPE_VIDEO:
6207 channel_manager()->DestroyVideoChannel(
6208 static_cast<cricket::VideoChannel*>(channel));
6209 break;
6210 case cricket::MEDIA_TYPE_DATA:
6211 channel_manager()->DestroyRtpDataChannel(
6212 static_cast<cricket::RtpDataChannel*>(channel));
6213 break;
6214 default:
6215 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6216 break;
6217 }
6218
6219 // |channel| can no longer be used.
6220
Steve Anton75737c02017-11-06 10:37:17 -08006221 transport_controller_->DestroyDtlsTransport(
6222 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6223 if (need_to_delete_rtcp) {
6224 transport_controller_->DestroyDtlsTransport(
6225 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6226 }
6227}
6228
Harald Alvestrand89061872018-01-02 14:08:34 +01006229void PeerConnection::ClearStatsCache() {
6230 if (stats_collector_) {
6231 stats_collector_->ClearCachedStatsReport();
6232 }
6233}
6234
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006235} // namespace webrtc