blob: d8ec0c949a1b24f1f375b470af7e3f87f78b402c [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 }
1144 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
Seth Hampson845e8782018-03-02 11:34:10 -08001145 if (stream_ids.size() > 1u) {
Steve Antonf9381f02017-12-14 10:23:57 -08001146 LOG_AND_RETURN_ERROR(
1147 RTCErrorType::UNSUPPORTED_OPERATION,
1148 "AddTrack with more than one stream is not currently supported.");
1149 }
1150 if (IsClosed()) {
1151 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1152 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001153 }
Steve Anton4171afb2017-11-20 10:20:22 -08001154 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001155 LOG_AND_RETURN_ERROR(
1156 RTCErrorType::INVALID_PARAMETER,
1157 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001158 }
Steve Antonf9381f02017-12-14 10:23:57 -08001159 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1160 // one stream. AddTrackInternal will return an error if there is more than one
1161 // stream, but if the caller specifies none then we need to generate a random
Seth Hampson845e8782018-03-02 11:34:10 -08001162 // stream id.
1163 std::vector<std::string> adjusted_stream_ids = stream_ids;
1164 if (stream_ids.empty()) {
1165 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
Steve Antonf9381f02017-12-14 10:23:57 -08001166 }
Seth Hampson845e8782018-03-02 11:34:10 -08001167 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001168 auto sender_or_error =
Seth Hampson845e8782018-03-02 11:34:10 -08001169 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1170 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001171 if (sender_or_error.ok()) {
1172 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001173 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001174 }
1175 return sender_or_error;
1176}
deadbeefe1f9d832016-01-14 15:35:42 -08001177
Steve Antonf9381f02017-12-14 10:23:57 -08001178RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1179PeerConnection::AddTrackPlanB(
1180 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001181 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001182 cricket::MediaType media_type =
1183 (track->kind() == MediaStreamTrackInterface::kAudioKind
1184 ? cricket::MEDIA_TYPE_AUDIO
1185 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001186 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001187 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001188 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001189 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001190 const RtpSenderInfo* sender_info =
1191 FindSenderInfo(local_audio_sender_infos_,
1192 new_sender->internal()->stream_id(), track->id());
1193 if (sender_info) {
1194 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001195 }
Steve Antonf9381f02017-12-14 10:23:57 -08001196 } else {
1197 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001198 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001199 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001200 const RtpSenderInfo* sender_info =
1201 FindSenderInfo(local_video_sender_infos_,
1202 new_sender->internal()->stream_id(), track->id());
1203 if (sender_info) {
1204 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001205 }
deadbeefe1f9d832016-01-14 15:35:42 -08001206 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001207 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001208}
deadbeefe1f9d832016-01-14 15:35:42 -08001209
Steve Antonf9381f02017-12-14 10:23:57 -08001210RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1211PeerConnection::AddTrackUnifiedPlan(
1212 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001213 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001214 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1215 if (transceiver) {
1216 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001217 transceiver->internal()->set_direction(
1218 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001219 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001220 transceiver->internal()->set_direction(
1221 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001222 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001223 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001224 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001225 } else {
1226 cricket::MediaType media_type =
1227 (track->kind() == MediaStreamTrackInterface::kAudioKind
1228 ? cricket::MEDIA_TYPE_AUDIO
1229 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001230 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001231 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1232 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001233 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001235 }
Steve Antonf9381f02017-12-14 10:23:57 -08001236 return transceiver->sender();
1237}
1238
1239rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1240PeerConnection::FindFirstTransceiverForAddedTrack(
1241 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1242 RTC_DCHECK(track);
1243 for (auto transceiver : transceivers_) {
1244 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001245 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001246 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001247 !transceiver->internal()->has_ever_been_used_to_send() &&
1248 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001249 return transceiver;
1250 }
1251 }
1252 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001253}
1254
1255bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1256 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001257 return RemoveTrackInternal(sender).ok();
1258}
1259
1260RTCError PeerConnection::RemoveTrackInternal(
1261 rtc::scoped_refptr<RtpSenderInterface> sender) {
1262 if (!sender) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1264 }
deadbeefe1f9d832016-01-14 15:35:42 -08001265 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1267 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001268 }
Steve Antonf9381f02017-12-14 10:23:57 -08001269 if (IsUnifiedPlan()) {
1270 auto transceiver = FindTransceiverBySender(sender);
1271 if (!transceiver || !sender->track()) {
1272 return RTCError::OK();
1273 }
1274 sender->SetTrack(nullptr);
1275 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001276 transceiver->internal()->set_direction(
1277 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001279 transceiver->internal()->set_direction(
1280 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001281 }
Steve Anton4171afb2017-11-20 10:20:22 -08001282 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001283 bool removed;
1284 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1285 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1286 } else {
1287 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1288 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1289 }
1290 if (!removed) {
1291 LOG_AND_RETURN_ERROR(
1292 RTCErrorType::INVALID_PARAMETER,
1293 "Couldn't find sender " + sender->id() + " to remove.");
1294 }
Steve Anton4171afb2017-11-20 10:20:22 -08001295 }
deadbeefe1f9d832016-01-14 15:35:42 -08001296 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001297 return RTCError::OK();
1298}
1299
1300rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1301PeerConnection::FindTransceiverBySender(
1302 rtc::scoped_refptr<RtpSenderInterface> sender) {
1303 for (auto transceiver : transceivers_) {
1304 if (transceiver->sender() == sender) {
1305 return transceiver;
1306 }
1307 }
1308 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001309}
1310
Steve Anton9158ef62017-11-27 13:01:52 -08001311RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1312PeerConnection::AddTransceiver(
1313 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1314 return AddTransceiver(track, RtpTransceiverInit());
1315}
1316
1317RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1318PeerConnection::AddTransceiver(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1320 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001321 RTC_CHECK(IsUnifiedPlan())
1322 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001323 if (!track) {
1324 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1325 }
1326 cricket::MediaType media_type;
1327 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1328 media_type = cricket::MEDIA_TYPE_AUDIO;
1329 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1330 media_type = cricket::MEDIA_TYPE_VIDEO;
1331 } else {
1332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1333 "Track kind is not audio or video");
1334 }
1335 return AddTransceiver(media_type, track, init);
1336}
1337
1338RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1339PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1340 return AddTransceiver(media_type, RtpTransceiverInit());
1341}
1342
1343RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1344PeerConnection::AddTransceiver(cricket::MediaType media_type,
1345 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001346 RTC_CHECK(IsUnifiedPlan())
1347 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001348 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1349 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1350 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1351 "media type is not audio or video");
1352 }
1353 return AddTransceiver(media_type, nullptr, init);
1354}
1355
1356RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1357PeerConnection::AddTransceiver(
1358 cricket::MediaType media_type,
1359 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001360 const RtpTransceiverInit& init,
1361 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001362 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1363 media_type == cricket::MEDIA_TYPE_VIDEO));
1364 if (track) {
1365 RTC_DCHECK_EQ(media_type,
1366 (track->kind() == MediaStreamTrackInterface::kAudioKind
1367 ? cricket::MEDIA_TYPE_AUDIO
1368 : cricket::MEDIA_TYPE_VIDEO));
1369 }
1370
1371 // TODO(bugs.webrtc.org/7600): Verify init.
1372
Seth Hampson513449e2018-03-06 09:35:56 -08001373 if (init.stream_ids.size() > 1u) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001374 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1375 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001376 }
1377
Seth Hampson513449e2018-03-06 09:35:56 -08001378 std::vector<std::string> stream_ids = {
1379 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
Steve Anton02ee47c2018-01-10 16:26:06 -08001380
Seth Hampson845e8782018-03-02 11:34:10 -08001381 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001382 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1383 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1384 transceiver->internal()->set_direction(init.direction);
1385
Steve Anton22da89f2018-01-25 13:58:07 -08001386 if (fire_callback) {
1387 observer_->OnRenegotiationNeeded();
1388 }
Steve Antonf9381f02017-12-14 10:23:57 -08001389
1390 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1391}
1392
Steve Anton02ee47c2018-01-10 16:26:06 -08001393rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1394PeerConnection::CreateSender(
1395 cricket::MediaType media_type,
1396 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001397 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001398 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1400 RTC_DCHECK(!track ||
1401 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1402 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1403 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001404 new AudioRtpSender(worker_thread(),
1405 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001406 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001407 } else {
1408 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1409 RTC_DCHECK(!track ||
1410 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1411 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1412 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001413 new VideoRtpSender(worker_thread(),
1414 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001415 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 }
Seth Hampson845e8782018-03-02 11:34:10 -08001417 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001418 return sender;
1419}
1420
1421rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1422PeerConnection::CreateReceiver(cricket::MediaType media_type,
1423 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1425 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001427 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001428 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001429 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001430 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001432 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1433 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001434 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001435 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001436 return receiver;
1437}
1438
1439rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1440PeerConnection::CreateAndAddTransceiver(
1441 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443 receiver) {
1444 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1445 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001446 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001447 transceiver->internal()->SignalNegotiationNeeded.connect(
1448 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001449 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001450}
1451
Steve Anton52d86772018-02-20 15:48:12 -08001452void PeerConnection::OnNegotiationNeeded() {
1453 RTC_DCHECK_RUN_ON(signaling_thread());
1454 RTC_DCHECK(!IsClosed());
1455 observer_->OnRenegotiationNeeded();
1456}
1457
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001458rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001460 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001461 if (IsClosed()) {
1462 return nullptr;
1463 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001465 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001466 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 }
Steve Anton4171afb2017-11-20 10:20:22 -08001468 auto track_sender = FindSenderForTrack(track);
1469 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001470 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001471 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 }
1473
Steve Anton4171afb2017-11-20 10:20:22 -08001474 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475}
1476
deadbeeffac06552015-11-25 11:26:01 -08001477rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001478 const std::string& kind,
1479 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001480 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1481 "Plan SdpSemantics. Please use AddTransceiver "
1482 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001483 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001484 if (IsClosed()) {
1485 return nullptr;
1486 }
Steve Anton4171afb2017-11-20 10:20:22 -08001487
Seth Hampson845e8782018-03-02 11:34:10 -08001488 std::vector<std::string> stream_ids;
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001490 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001491 }
1492
Steve Anton4171afb2017-11-20 10:20:22 -08001493 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001494 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001495 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001496 auto* audio_sender =
1497 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001498 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001499 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001501 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001502 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001503 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001504 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001505 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001506 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001507 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001508 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001509 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001510 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001511 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001512 }
Steve Anton4171afb2017-11-20 10:20:22 -08001513
deadbeefe1f9d832016-01-14 15:35:42 -08001514 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001515}
1516
deadbeef70ab1a12015-09-28 16:53:55 -07001517std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1518 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001519 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001520 for (auto sender : GetSendersInternal()) {
1521 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001522 }
1523 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001524}
1525
Steve Anton4171afb2017-11-20 10:20:22 -08001526std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1527PeerConnection::GetSendersInternal() const {
1528 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1529 all_senders;
1530 for (auto transceiver : transceivers_) {
1531 auto senders = transceiver->internal()->senders();
1532 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1533 }
1534 return all_senders;
1535}
1536
deadbeef70ab1a12015-09-28 16:53:55 -07001537std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1538PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001539 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001540 for (const auto& receiver : GetReceiversInternal()) {
1541 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001542 }
1543 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001544}
1545
Steve Anton4171afb2017-11-20 10:20:22 -08001546std::vector<
1547 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1548PeerConnection::GetReceiversInternal() const {
1549 std::vector<
1550 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1551 all_receivers;
1552 for (auto transceiver : transceivers_) {
1553 auto receivers = transceiver->internal()->receivers();
1554 all_receivers.insert(all_receivers.end(), receivers.begin(),
1555 receivers.end());
1556 }
1557 return all_receivers;
1558}
1559
Steve Anton9158ef62017-11-27 13:01:52 -08001560std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1561PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001562 RTC_CHECK(IsUnifiedPlan())
1563 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001564 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1565 for (auto transceiver : transceivers_) {
1566 all_transceivers.push_back(transceiver);
1567 }
1568 return all_transceivers;
1569}
1570
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001572 MediaStreamTrackInterface* track,
1573 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001574 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001575 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001576 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001577 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001578 return false;
1579 }
1580
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001581 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001582 // The StatsCollector is used to tell if a track is valid because it may
1583 // remember tracks that the PeerConnection previously removed.
1584 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001585 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1586 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001587 return false;
1588 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001589 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001590 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591 return true;
1592}
1593
hbos74e1a4f2016-09-15 23:33:01 -07001594void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1595 RTC_DCHECK(stats_collector_);
1596 stats_collector_->GetStatsReport(callback);
1597}
1598
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001599PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1600 return signaling_state_;
1601}
1602
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603PeerConnectionInterface::IceConnectionState
1604PeerConnection::ice_connection_state() {
1605 return ice_connection_state_;
1606}
1607
1608PeerConnectionInterface::IceGatheringState
1609PeerConnection::ice_gathering_state() {
1610 return ice_gathering_state_;
1611}
1612
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001613rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614PeerConnection::CreateDataChannel(
1615 const std::string& label,
1616 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001617 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001618
deadbeefab9b2d12015-10-14 11:33:11 -07001619 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001620
kwibergd1fe2812016-04-27 06:47:29 -07001621 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001622 if (config) {
1623 internal_config.reset(new InternalDataChannelInit(*config));
1624 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001625 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001626 InternalCreateDataChannel(label, internal_config.get()));
1627 if (!channel.get()) {
1628 return nullptr;
1629 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001631 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1632 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001633 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001634 observer_->OnRenegotiationNeeded();
1635 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001636
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637 return DataChannelProxy::Create(signaling_thread(), channel.get());
1638}
1639
1640void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1641 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001642 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001643
zhihuang1c378ed2017-08-17 14:10:50 -07001644 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1645 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1646 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1647 // compares the mandatory fields parsed with the mandatory fields added in the
1648 // |constraints| and some downstream applications might create offers with
1649 // mandatory fields which would not be parsed in the helper method. For
1650 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1651 // |constraints| as a mandatory field but it is not parsed.
1652 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001653
zhihuang1c378ed2017-08-17 14:10:50 -07001654 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001655}
1656
1657void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1658 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001659 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001660
nisse7ce109a2017-01-31 00:57:56 -08001661 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001662 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001663 return;
1664 }
deadbeefab9b2d12015-10-14 11:33:11 -07001665
Steve Anton8d3444d2017-10-20 15:30:51 -07001666 if (IsClosed()) {
1667 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001668 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001669 PostCreateSessionDescriptionFailure(
1670 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001671 return;
1672 }
1673
zhihuang1c378ed2017-08-17 14:10:50 -07001674 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001675 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001676 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001677 PostCreateSessionDescriptionFailure(
1678 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001679 return;
1680 }
1681
Steve Anton22da89f2018-01-25 13:58:07 -08001682 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1683 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1684 if (IsUnifiedPlan()) {
1685 RTCError error = HandleLegacyOfferOptions(options);
1686 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001687 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001688 return;
1689 }
1690 }
1691
zhihuang1c378ed2017-08-17 14:10:50 -07001692 cricket::MediaSessionOptions session_options;
1693 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001694 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695}
1696
Steve Anton22da89f2018-01-25 13:58:07 -08001697RTCError PeerConnection::HandleLegacyOfferOptions(
1698 const RTCOfferAnswerOptions& options) {
1699 RTC_DCHECK(IsUnifiedPlan());
1700
1701 if (options.offer_to_receive_audio == 0) {
1702 RemoveRecvDirectionFromReceivingTransceiversOfType(
1703 cricket::MEDIA_TYPE_AUDIO);
1704 } else if (options.offer_to_receive_audio == 1) {
1705 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1706 } else if (options.offer_to_receive_audio > 1) {
1707 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1708 "offer_to_receive_audio > 1 is not supported.");
1709 }
1710
1711 if (options.offer_to_receive_video == 0) {
1712 RemoveRecvDirectionFromReceivingTransceiversOfType(
1713 cricket::MEDIA_TYPE_VIDEO);
1714 } else if (options.offer_to_receive_video == 1) {
1715 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1716 } else if (options.offer_to_receive_video > 1) {
1717 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1718 "offer_to_receive_video > 1 is not supported.");
1719 }
1720
1721 return RTCError::OK();
1722}
1723
1724void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1725 cricket::MediaType media_type) {
1726 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1727 transceiver->internal()->set_direction(
1728 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1729 }
1730}
1731
1732void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1733 cricket::MediaType media_type) {
1734 if (GetReceivingTransceiversOfType(media_type).empty()) {
1735 RtpTransceiverInit init;
1736 init.direction = RtpTransceiverDirection::kRecvOnly;
1737 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1738 }
1739}
1740
1741std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1742PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1743 std::vector<
1744 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1745 receiving_transceivers;
1746 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001747 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001748 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1749 receiving_transceivers.push_back(transceiver);
1750 }
1751 }
1752 return receiving_transceivers;
1753}
1754
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755void PeerConnection::CreateAnswer(
1756 CreateSessionDescriptionObserver* observer,
1757 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001758 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001759
nisse7ce109a2017-01-31 00:57:56 -08001760 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762 return;
1763 }
deadbeefab9b2d12015-10-14 11:33:11 -07001764
zhihuang1c378ed2017-08-17 14:10:50 -07001765 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1766 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1767 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001768 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001769 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001770 PostCreateSessionDescriptionFailure(
1771 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001772 return;
1773 }
1774
Steve Anton8d3444d2017-10-20 15:30:51 -07001775 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001776}
1777
1778void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1779 const RTCOfferAnswerOptions& options) {
1780 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001781 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001783 return;
1784 }
1785
Steve Antondffead82018-02-06 10:31:29 -08001786 if (!(signaling_state_ == kHaveRemoteOffer ||
1787 signaling_state_ == kHaveLocalPrAnswer)) {
1788 std::string error =
1789 "PeerConnection cannot create an answer in a state other than "
1790 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001791 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001792 PostCreateSessionDescriptionFailure(
1793 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001794 return;
1795 }
1796
Steve Antondffead82018-02-06 10:31:29 -08001797 // The remote description should be set if we're in the right state.
1798 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001799
Steve Anton22da89f2018-01-25 13:58:07 -08001800 if (IsUnifiedPlan()) {
1801 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1802 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1803 "supported with Unified Plan semantics. Use the "
1804 "RtpTransceiver API instead.";
1805 }
1806 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1807 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1808 "supported with Unified Plan semantics. Use the "
1809 "RtpTransceiver API instead.";
1810 }
1811 }
1812
htaa2a49d92016-03-04 02:51:39 -08001813 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001814 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001815
Steve Antond25da372017-11-06 14:50:29 -08001816 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817}
1818
1819void PeerConnection::SetLocalDescription(
1820 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001821 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001822 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001823
Steve Anton80dd7b52018-02-16 17:08:42 -08001824 // The SetLocalDescription contract is that we take ownership of the session
1825 // description regardless of the outcome, so wrap it in a unique_ptr right
1826 // away. Ideally, SetLocalDescription's signature will be changed to take the
1827 // description as a unique_ptr argument to formalize this agreement.
1828 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1829
nisse7ce109a2017-01-31 00:57:56 -08001830 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 return;
1833 }
Steve Anton8a006912017-12-04 15:25:56 -08001834
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001835 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001836 PostSetSessionDescriptionFailure(
1837 observer,
1838 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 return;
1840 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001841
Steve Anton80dd7b52018-02-16 17:08:42 -08001842 // If a session error has occurred the PeerConnection is in a possibly
1843 // inconsistent state so fail right away.
1844 if (session_error() != SessionError::kNone) {
1845 std::string error_message = GetSessionErrorMsg();
1846 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001847 PostSetSessionDescriptionFailure(
1848 observer,
1849 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001850 return;
1851 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001852
Steve Anton80dd7b52018-02-16 17:08:42 -08001853 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1854 if (!error.ok()) {
1855 std::string error_message = GetSetDescriptionErrorMessage(
1856 cricket::CS_LOCAL, desc->GetType(), error);
1857 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001858 PostSetSessionDescriptionFailure(
1859 observer,
1860 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001861 return;
1862 }
1863
1864 // Grab the description type before moving ownership to ApplyLocalDescription,
1865 // which may destroy it before returning.
1866 const SdpType type = desc->GetType();
1867
1868 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001869 // |desc| may be destroyed at this point.
1870
1871 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001872 // If ApplyLocalDescription fails, the PeerConnection could be in an
1873 // inconsistent state, so act conservatively here and set the session error
1874 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1875 SetSessionError(SessionError::kContent, error.message());
1876 std::string error_message =
1877 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1878 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001879 PostSetSessionDescriptionFailure(
1880 observer,
1881 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001882 return;
1883 }
Steve Anton8a006912017-12-04 15:25:56 -08001884 RTC_DCHECK(local_description());
1885
1886 PostSetSessionDescriptionSuccess(observer);
1887
1888 // According to JSEP, after setLocalDescription, changing the candidate pool
1889 // size is not allowed, and changing the set of ICE servers will not result
1890 // in new candidates being gathered.
1891 port_allocator_->FreezeCandidatePool();
1892
1893 // MaybeStartGathering needs to be called after posting
1894 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1895 // before signaling that SetLocalDescription completed.
1896 transport_controller_->MaybeStartGathering();
1897
Steve Antona3a92c22017-12-07 10:27:41 -08001898 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001899 // TODO(deadbeef): We already had to hop to the network thread for
1900 // MaybeStartGathering...
1901 network_thread()->Invoke<void>(
1902 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1903 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001904 // Make UMA notes about what was agreed to.
1905 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001906 }
1907}
1908
1909RTCError PeerConnection::ApplyLocalDescription(
1910 std::unique_ptr<SessionDescriptionInterface> desc) {
1911 RTC_DCHECK_RUN_ON(signaling_thread());
1912 RTC_DCHECK(desc);
1913
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 // Update stats here so that we have the most recent stats for tracks and
1915 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001916 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001917
1918 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001919 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001920 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001921 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001922 if (*initial_offerer_) {
1923 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1924 } else {
1925 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1926 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 }
Steve Anton8a006912017-12-04 15:25:56 -08001928
Steve Antondcc3c022017-12-22 16:02:54 -08001929 // Take a reference to the old local description since it's used below to
1930 // compare against the new local description. When setting the new local
1931 // description, grab ownership of the replaced session description in case it
1932 // is the same as |old_local_description|, to keep it alive for the duration
1933 // of the method.
1934 const SessionDescriptionInterface* old_local_description =
1935 local_description();
1936 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001937 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001938 replaced_local_description = pending_local_description_
1939 ? std::move(pending_local_description_)
1940 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001941 current_local_description_ = std::move(desc);
1942 pending_local_description_ = nullptr;
1943 current_remote_description_ = std::move(pending_remote_description_);
1944 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001945 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001946 pending_local_description_ = std::move(desc);
1947 }
1948 // The session description to apply now must be accessed by
1949 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001950 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001951
Steve Antondcc3c022017-12-22 16:02:54 -08001952 if (IsUnifiedPlan()) {
1953 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001954 cricket::CS_LOCAL, *local_description(), old_local_description,
1955 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001956 if (!error.ok()) {
1957 return error;
1958 }
Steve Antondcc3c022017-12-22 16:02:54 -08001959 for (auto transceiver : transceivers_) {
1960 const ContentInfo* content =
1961 FindMediaSectionForTransceiver(transceiver, local_description());
1962 if (!content) {
1963 continue;
1964 }
1965 const MediaContentDescription* media_desc = content->media_description();
1966 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1967 transceiver->internal()->set_current_direction(media_desc->direction());
1968 }
1969 if (content->rejected && !transceiver->stopped()) {
1970 transceiver->Stop();
1971 }
1972 }
1973 } else {
1974 // Transport and Media channels will be created only when offer is set.
1975 if (type == SdpType::kOffer) {
1976 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1977 // description is applied. Restore back to old description.
1978 RTCError error = CreateChannels(*local_description()->description());
1979 if (!error.ok()) {
1980 return error;
1981 }
1982 }
Steve Anton8a006912017-12-04 15:25:56 -08001983
Steve Antondcc3c022017-12-22 16:02:54 -08001984 // Remove unused channels if MediaContentDescription is rejected.
1985 RemoveUnusedChannels(local_description()->description());
1986 }
Steve Anton8a006912017-12-04 15:25:56 -08001987
Steve Anton80dd7b52018-02-16 17:08:42 -08001988 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001989 if (!error.ok()) {
1990 return error;
1991 }
Steve Antondcc3c022017-12-22 16:02:54 -08001992
Steve Anton8a006912017-12-04 15:25:56 -08001993 if (remote_description()) {
1994 // Now that we have a local description, we can push down remote candidates.
1995 UseCandidatesInSessionDescription(remote_description());
1996 }
1997
1998 pending_ice_restarts_.clear();
1999 if (session_error() != SessionError::kNone) {
2000 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2001 }
2002
deadbeefab9b2d12015-10-14 11:33:11 -07002003 // If setting the description decided our SSL role, allocate any necessary
2004 // SCTP sids.
2005 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002006 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002007 AllocateSctpSids(role);
2008 }
2009
Steve Antond3679212018-01-17 17:41:02 -08002010 if (IsUnifiedPlan()) {
2011 for (auto transceiver : transceivers_) {
2012 const ContentInfo* content =
2013 FindMediaSectionForTransceiver(transceiver, local_description());
2014 if (!content) {
2015 continue;
2016 }
2017 if (content->rejected && !transceiver->stopped()) {
2018 transceiver->Stop();
2019 }
Steve Anton74255ff2018-01-24 18:32:57 -08002020 const auto& streams = content->media_description()->streams();
2021 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002022 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002023 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002024 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002025 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002026 }
2027 }
2028 } else {
2029 // Plan B semantics.
2030
Steve Antondcc3c022017-12-22 16:02:54 -08002031 // Update state and SSRC of local MediaStreams and DataChannels based on the
2032 // local session description.
2033 const cricket::ContentInfo* audio_content =
2034 GetFirstAudioContent(local_description()->description());
2035 if (audio_content) {
2036 if (audio_content->rejected) {
2037 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2038 } else {
2039 const cricket::AudioContentDescription* audio_desc =
2040 audio_content->media_description()->as_audio();
2041 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2042 }
deadbeeffaac4972015-11-12 15:33:07 -08002043 }
deadbeefab9b2d12015-10-14 11:33:11 -07002044
Steve Antondcc3c022017-12-22 16:02:54 -08002045 const cricket::ContentInfo* video_content =
2046 GetFirstVideoContent(local_description()->description());
2047 if (video_content) {
2048 if (video_content->rejected) {
2049 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2050 } else {
2051 const cricket::VideoContentDescription* video_desc =
2052 video_content->media_description()->as_video();
2053 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2054 }
deadbeeffaac4972015-11-12 15:33:07 -08002055 }
deadbeefab9b2d12015-10-14 11:33:11 -07002056 }
2057
2058 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002059 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002060 if (data_content) {
2061 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002062 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002063 if (rtc::starts_with(data_desc->protocol().data(),
2064 cricket::kMediaProtocolRtpPrefix)) {
2065 UpdateLocalRtpDataChannels(data_desc->streams());
2066 }
2067 }
2068
Steve Anton8a006912017-12-04 15:25:56 -08002069 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002070}
2071
2072void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002073 SetSessionDescriptionObserver* observer,
2074 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002075 SetRemoteDescription(
2076 std::unique_ptr<SessionDescriptionInterface>(desc),
2077 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2078 new SetRemoteDescriptionObserverAdapter(this, observer)));
2079}
2080
2081void PeerConnection::SetRemoteDescription(
2082 std::unique_ptr<SessionDescriptionInterface> desc,
2083 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002084 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002085
nisse7ce109a2017-01-31 00:57:56 -08002086 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002087 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 return;
2089 }
Steve Anton8a006912017-12-04 15:25:56 -08002090
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002091 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002092 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002093 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094 return;
2095 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002096
Steve Anton80dd7b52018-02-16 17:08:42 -08002097 // If a session error has occurred the PeerConnection is in a possibly
2098 // inconsistent state so fail right away.
2099 if (session_error() != SessionError::kNone) {
2100 std::string error_message = GetSessionErrorMsg();
2101 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2102 observer->OnSetRemoteDescriptionComplete(
2103 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2104 return;
2105 }
Steve Anton71439a62018-02-15 11:53:06 -08002106
Steve Anton80dd7b52018-02-16 17:08:42 -08002107 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002108 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002109 std::string error_message = GetSetDescriptionErrorMessage(
2110 cricket::CS_REMOTE, desc->GetType(), error);
2111 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002112 observer->OnSetRemoteDescriptionComplete(
2113 RTCError(error.type(), std::move(error_message)));
2114 return;
2115 }
Steve Anton71439a62018-02-15 11:53:06 -08002116
Steve Anton80dd7b52018-02-16 17:08:42 -08002117 // Grab the description type before moving ownership to
2118 // ApplyRemoteDescription, which may destroy it before returning.
2119 const SdpType type = desc->GetType();
2120
2121 error = ApplyRemoteDescription(std::move(desc));
2122 // |desc| may be destroyed at this point.
2123
2124 if (!error.ok()) {
2125 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2126 // inconsistent state, so act conservatively here and set the session error
2127 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2128 SetSessionError(SessionError::kContent, error.message());
2129 std::string error_message =
2130 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2131 RTC_LOG(LS_ERROR) << error_message;
2132 observer->OnSetRemoteDescriptionComplete(
2133 RTCError(error.type(), std::move(error_message)));
2134 return;
2135 }
2136 RTC_DCHECK(remote_description());
2137
Steve Anton8e20f172018-03-06 10:55:04 -08002138 if (type == SdpType::kOffer) {
2139 // Report to UMA the format of the received offer.
2140 ReportSdpFormatReceived(*remote_description());
2141 }
2142
Steve Anton80dd7b52018-02-16 17:08:42 -08002143 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002144 // TODO(deadbeef): We already had to hop to the network thread for
2145 // MaybeStartGathering...
2146 network_thread()->Invoke<void>(
2147 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2148 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002149 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002150 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002151 }
2152
2153 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2154}
2155
2156RTCError PeerConnection::ApplyRemoteDescription(
2157 std::unique_ptr<SessionDescriptionInterface> desc) {
2158 RTC_DCHECK_RUN_ON(signaling_thread());
2159 RTC_DCHECK(desc);
2160
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 // Update stats here so that we have the most recent stats for tracks and
2162 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002163 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002164
Steve Antondcc3c022017-12-22 16:02:54 -08002165 // Take a reference to the old remote description since it's used below to
2166 // compare against the new remote description. When setting the new remote
2167 // description, grab ownership of the replaced session description in case it
2168 // is the same as |old_remote_description|, to keep it alive for the duration
2169 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002170 const SessionDescriptionInterface* old_remote_description =
2171 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002172 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002173 SdpType type = desc->GetType();
2174 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002175 replaced_remote_description = pending_remote_description_
2176 ? std::move(pending_remote_description_)
2177 : std::move(current_remote_description_);
2178 current_remote_description_ = std::move(desc);
2179 pending_remote_description_ = nullptr;
2180 current_local_description_ = std::move(pending_local_description_);
2181 } else {
2182 replaced_remote_description = std::move(pending_remote_description_);
2183 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 }
Steve Anton8a006912017-12-04 15:25:56 -08002185 // The session description to apply now must be accessed by
2186 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002187 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188
Steve Anton8a006912017-12-04 15:25:56 -08002189 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002190 if (IsUnifiedPlan()) {
2191 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002192 cricket::CS_REMOTE, *remote_description(), local_description(),
2193 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002194 if (!error.ok()) {
2195 return error;
2196 }
Steve Antondcc3c022017-12-22 16:02:54 -08002197 } else {
2198 if (type == SdpType::kOffer) {
2199 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2200 // description is applied. Restore back to old description.
2201 RTCError error = CreateChannels(*remote_description()->description());
2202 if (!error.ok()) {
2203 return error;
2204 }
2205 }
Steve Anton8a006912017-12-04 15:25:56 -08002206
Steve Antondcc3c022017-12-22 16:02:54 -08002207 // Remove unused channels if MediaContentDescription is rejected.
2208 RemoveUnusedChannels(remote_description()->description());
2209 }
Steve Anton8a006912017-12-04 15:25:56 -08002210
2211 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2212 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002213 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002214 if (!error.ok()) {
2215 return error;
2216 }
2217
2218 if (local_description() &&
2219 !UseCandidatesInSessionDescription(remote_description())) {
2220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2221 }
2222
2223 if (old_remote_description) {
2224 for (const cricket::ContentInfo& content :
2225 old_remote_description->description()->contents()) {
2226 // Check if this new SessionDescription contains new ICE ufrag and
2227 // password that indicates the remote peer requests an ICE restart.
2228 // TODO(deadbeef): When we start storing both the current and pending
2229 // remote description, this should reset pending_ice_restarts and compare
2230 // against the current description.
2231 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2232 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002233 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002234 pending_ice_restarts_.insert(content.name);
2235 }
2236 } else {
2237 // We retain all received candidates only if ICE is not restarted.
2238 // When ICE is restarted, all previous candidates belong to an old
2239 // generation and should not be kept.
2240 // TODO(deadbeef): This goes against the W3C spec which says the remote
2241 // description should only contain candidates from the last set remote
2242 // description plus any candidates added since then. We should remove
2243 // this once we're sure it won't break anything.
2244 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2245 old_remote_description, content.name, mutable_remote_description());
2246 }
2247 }
2248 }
2249
2250 if (session_error() != SessionError::kNone) {
2251 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2252 }
2253
2254 // Set the the ICE connection state to connecting since the connection may
2255 // become writable with peer reflexive candidates before any remote candidate
2256 // is signaled.
2257 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2258 // is to have a new signal the indicates a change in checking state from the
2259 // transport and expose a new checking() member from transport that can be
2260 // read to determine the current checking state. The existing SignalConnecting
2261 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002262 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002263 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2264 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2265 }
2266
deadbeefab9b2d12015-10-14 11:33:11 -07002267 // If setting the description decided our SSL role, allocate any necessary
2268 // SCTP sids.
2269 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002270 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002271 AllocateSctpSids(role);
2272 }
2273
Steve Antondcc3c022017-12-22 16:02:54 -08002274 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002275 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2276 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002277 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002278 for (auto transceiver : transceivers_) {
2279 const ContentInfo* content =
2280 FindMediaSectionForTransceiver(transceiver, remote_description());
2281 if (!content) {
2282 continue;
2283 }
2284 const MediaContentDescription* media_desc = content->media_description();
2285 RtpTransceiverDirection local_direction =
2286 RtpTransceiverDirectionReversed(media_desc->direction());
2287 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2288 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2289 // transceiver's current direction is neither sendrecv nor recvonly,
2290 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002291 //
2292 // Create a sync label in the case of an unsignalled msid.
2293 std::string sync_label = rtc::CreateRandomUuid();
2294 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002295 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002296 if (!stream_params.stream_ids().empty()) {
2297 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002298 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002299 }
Steve Antondcc3c022017-12-22 16:02:54 -08002300 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2301 (!transceiver->current_direction() ||
2302 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002303 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002304 rtc::scoped_refptr<MediaStreamInterface> stream =
2305 remote_streams_->find(sync_label);
2306 if (!stream) {
2307 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2308 MediaStream::Create(sync_label));
2309 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002310 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002311 }
2312 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002313 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002314 }
2315 // If direction is sendonly or inactive, and transceiver's current
2316 // direction is neither sendonly nor inactive, process the removal of a
2317 // remote track for the media description.
2318 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002319 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002320 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002321 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002322 }
2323 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2324 transceiver->internal()->set_current_direction(local_direction);
2325 }
2326 if (content->rejected && !transceiver->stopped()) {
2327 transceiver->Stop();
2328 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002329 if (!content->rejected &&
2330 RtpTransceiverDirectionHasRecv(local_direction)) {
2331 // Set ssrc to 0 in the case of an unsignalled ssrc.
2332 uint32_t ssrc = 0;
2333 if (!media_desc->streams().empty()) {
2334 ssrc = media_desc->streams()[0].first_ssrc();
2335 }
2336 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002337 }
Steve Antondcc3c022017-12-22 16:02:54 -08002338 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002339 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002340 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002341 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002342 observer_->OnTrack(transceiver);
2343 observer_->OnAddTrack(transceiver->receiver(),
2344 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002345 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002346 for (auto stream : added_streams) {
2347 observer_->OnAddStream(stream);
2348 }
Steve Antondcc3c022017-12-22 16:02:54 -08002349 }
2350
Henrik Boströmfdb92012017-11-09 19:55:44 +01002351 const cricket::ContentInfo* audio_content =
2352 GetFirstAudioContent(remote_description()->description());
2353 const cricket::ContentInfo* video_content =
2354 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002355 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002356 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002357 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002358 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002359 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002360 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002361
2362 // Check if the descriptions include streams, just in case the peer supports
2363 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002364 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002365 (audio_desc && !audio_desc->streams().empty()) ||
2366 (video_desc && !video_desc->streams().empty())) {
2367 remote_peer_supports_msid_ = true;
2368 }
deadbeefab9b2d12015-10-14 11:33:11 -07002369
2370 // We wait to signal new streams until we finish processing the description,
2371 // since only at that point will new streams have all their tracks.
2372 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2373
Steve Antondcc3c022017-12-22 16:02:54 -08002374 if (!IsUnifiedPlan()) {
2375 // TODO(steveanton): When removing RTP senders/receivers in response to a
2376 // rejected media section, there is some cleanup logic that expects the
2377 // voice/ video channel to still be set. But in this method the voice/video
2378 // channel would have been destroyed by the SetRemoteDescription caller
2379 // above so the cleanup that relies on them fails to run. The RemoveSenders
2380 // calls should be moved to right before the DestroyChannel calls to fix
2381 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002382
Steve Antondcc3c022017-12-22 16:02:54 -08002383 // Find all audio rtp streams and create corresponding remote AudioTracks
2384 // and MediaStreams.
2385 if (audio_content) {
2386 if (audio_content->rejected) {
2387 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2388 } else {
2389 bool default_audio_track_needed =
2390 !remote_peer_supports_msid_ &&
2391 RtpTransceiverDirectionHasSend(audio_desc->direction());
2392 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2393 default_audio_track_needed, audio_desc->type(),
2394 new_streams);
2395 }
deadbeeffaac4972015-11-12 15:33:07 -08002396 }
deadbeefab9b2d12015-10-14 11:33:11 -07002397
Steve Antondcc3c022017-12-22 16:02:54 -08002398 // Find all video rtp streams and create corresponding remote VideoTracks
2399 // and MediaStreams.
2400 if (video_content) {
2401 if (video_content->rejected) {
2402 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2403 } else {
2404 bool default_video_track_needed =
2405 !remote_peer_supports_msid_ &&
2406 RtpTransceiverDirectionHasSend(video_desc->direction());
2407 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2408 default_video_track_needed, video_desc->type(),
2409 new_streams);
2410 }
deadbeeffaac4972015-11-12 15:33:07 -08002411 }
deadbeefab9b2d12015-10-14 11:33:11 -07002412
Steve Antondcc3c022017-12-22 16:02:54 -08002413 // Update the DataChannels with the information from the remote peer.
2414 if (data_desc) {
2415 if (rtc::starts_with(data_desc->protocol().data(),
2416 cricket::kMediaProtocolRtpPrefix)) {
2417 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2418 }
deadbeefab9b2d12015-10-14 11:33:11 -07002419 }
deadbeefab9b2d12015-10-14 11:33:11 -07002420
Steve Antondcc3c022017-12-22 16:02:54 -08002421 // Iterate new_streams and notify the observer about new MediaStreams.
2422 for (size_t i = 0; i < new_streams->count(); ++i) {
2423 MediaStreamInterface* new_stream = new_streams->at(i);
2424 stats_->AddStream(new_stream);
2425 observer_->OnAddStream(
2426 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2427 }
deadbeefab9b2d12015-10-14 11:33:11 -07002428
Steve Antondcc3c022017-12-22 16:02:54 -08002429 UpdateEndedRemoteMediaStreams();
2430 }
deadbeefab9b2d12015-10-14 11:33:11 -07002431
Steve Anton8a006912017-12-04 15:25:56 -08002432 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002433}
2434
Steve Antondcc3c022017-12-22 16:02:54 -08002435RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2436 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002437 const SessionDescriptionInterface& new_session,
2438 const SessionDescriptionInterface* old_local_description,
2439 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002440 RTC_DCHECK(IsUnifiedPlan());
2441
Steve Anton7464fca2018-01-19 11:10:37 -08002442 const cricket::ContentGroup* bundle_group = nullptr;
2443 if (new_session.GetType() == SdpType::kOffer) {
2444 auto bundle_group_or_error =
2445 GetEarlyBundleGroup(*new_session.description());
2446 if (!bundle_group_or_error.ok()) {
2447 return bundle_group_or_error.MoveError();
2448 }
2449 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002450 }
Steve Antondcc3c022017-12-22 16:02:54 -08002451
Steve Antondcc3c022017-12-22 16:02:54 -08002452 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002453 for (size_t i = 0; i < new_contents.size(); ++i) {
2454 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002455 cricket::MediaType media_type = new_content.media_description()->type();
2456 seen_mids_.insert(new_content.name);
2457 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2458 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002459 const cricket::ContentInfo* old_local_content = nullptr;
2460 if (old_local_description &&
2461 i < old_local_description->description()->contents().size()) {
2462 old_local_content =
2463 &old_local_description->description()->contents()[i];
2464 }
2465 const cricket::ContentInfo* old_remote_content = nullptr;
2466 if (old_remote_description &&
2467 i < old_remote_description->description()->contents().size()) {
2468 old_remote_content =
2469 &old_remote_description->description()->contents()[i];
2470 }
Steve Antondcc3c022017-12-22 16:02:54 -08002471 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002472 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2473 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002474 if (!transceiver_or_error.ok()) {
2475 return transceiver_or_error.MoveError();
2476 }
2477 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002478 RTCError error =
2479 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2480 if (!error.ok()) {
2481 return error;
2482 }
2483 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002484 if (GetDataMid() && new_content.name != *GetDataMid()) {
2485 // Ignore all but the first data section.
2486 continue;
2487 }
2488 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2489 if (!error.ok()) {
2490 return error;
2491 }
Steve Antondcc3c022017-12-22 16:02:54 -08002492 } else {
2493 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2494 "Unknown section type.");
2495 }
2496 }
2497
2498 return RTCError::OK();
2499}
2500
2501RTCError PeerConnection::UpdateTransceiverChannel(
2502 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2503 transceiver,
2504 const cricket::ContentInfo& content,
2505 const cricket::ContentGroup* bundle_group) {
2506 RTC_DCHECK(IsUnifiedPlan());
2507 RTC_DCHECK(transceiver);
2508 cricket::BaseChannel* channel = transceiver->internal()->channel();
2509 if (content.rejected) {
2510 if (channel) {
2511 transceiver->internal()->SetChannel(nullptr);
2512 DestroyBaseChannel(channel);
2513 }
2514 } else {
2515 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002516 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002517 channel = CreateVoiceChannel(
2518 content.name,
2519 GetTransportNameForMediaSection(content.name, bundle_group));
2520 } else {
Steve Anton69470252018-02-09 11:43:08 -08002521 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002522 channel = CreateVideoChannel(
2523 content.name,
2524 GetTransportNameForMediaSection(content.name, bundle_group));
2525 }
2526 if (!channel) {
2527 LOG_AND_RETURN_ERROR(
2528 RTCErrorType::INTERNAL_ERROR,
2529 "Failed to create channel for mid=" + content.name);
2530 }
2531 transceiver->internal()->SetChannel(channel);
2532 }
2533 }
2534 return RTCError::OK();
2535}
2536
Steve Antonfa2260d2017-12-28 16:38:23 -08002537RTCError PeerConnection::UpdateDataChannel(
2538 cricket::ContentSource source,
2539 const cricket::ContentInfo& content,
2540 const cricket::ContentGroup* bundle_group) {
2541 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002542 // If data channels are disabled, ignore this media section. CreateAnswer
2543 // will take care of rejecting it.
2544 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002545 }
2546 if (content.rejected) {
2547 DestroyDataChannel();
2548 } else {
2549 if (!rtp_data_channel_ && !sctp_transport_) {
2550 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2551 content.name, bundle_group))) {
2552 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2553 "Failed to create data channel.");
2554 }
2555 }
2556 if (source == cricket::CS_REMOTE) {
2557 const MediaContentDescription* data_desc = content.media_description();
2558 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2559 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2560 }
2561 }
2562 }
2563 return RTCError::OK();
2564}
2565
Steve Antondcc3c022017-12-22 16:02:54 -08002566RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2567PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002568 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002569 size_t mline_index,
2570 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002571 const ContentInfo* old_local_content,
2572 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002573 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002574 // If this is an offer then the m= section might be recycled. If the m=
2575 // section is being recycled (defined as: rejected in the current local or
2576 // remote description and not rejected in new description), dissociate the
2577 // currently associated RtpTransceiver by setting its mid property to null,
2578 // and discard the mapping between the transceiver and its m= section index.
2579 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2580 old_remote_content)) {
2581 // We want to dissociate the transceiver that has the rejected mid.
2582 const std::string& old_mid =
2583 (old_local_content && old_local_content->rejected)
2584 ? old_local_content->name
2585 : old_remote_content->name;
2586 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002587 if (old_transceiver) {
2588 old_transceiver->internal()->set_mid(rtc::nullopt);
2589 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2590 }
2591 }
2592 const MediaContentDescription* media_desc = content.media_description();
2593 auto transceiver = GetAssociatedTransceiver(content.name);
2594 if (source == cricket::CS_LOCAL) {
2595 // Find the RtpTransceiver that corresponds to this m= section, using the
2596 // mapping between transceivers and m= section indices established when
2597 // creating the offer.
2598 if (!transceiver) {
2599 transceiver = GetTransceiverByMLineIndex(mline_index);
2600 }
2601 if (!transceiver) {
2602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2603 "Unknown transceiver");
2604 }
2605 } else {
2606 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2607 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2608 // of the same type...
2609 if (!transceiver &&
2610 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2611 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2612 }
2613 // If no RtpTransceiver was found in the previous step, create one with a
2614 // recvonly direction.
2615 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002616 auto sender =
2617 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002618 std::string receiver_id;
2619 if (!media_desc->streams().empty()) {
2620 receiver_id = media_desc->streams()[0].id;
2621 } else {
2622 receiver_id = rtc::CreateRandomUuid();
2623 }
2624 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002625 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002626 transceiver->internal()->set_direction(
2627 RtpTransceiverDirection::kRecvOnly);
2628 }
2629 }
2630 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002631 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002632 LOG_AND_RETURN_ERROR(
2633 RTCErrorType::INVALID_PARAMETER,
2634 "Transceiver type does not match media description type.");
2635 }
2636 // Associate the found or created RtpTransceiver with the m= section by
2637 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2638 // section, and establish a mapping between the transceiver and the index of
2639 // the m= section.
2640 transceiver->internal()->set_mid(content.name);
2641 transceiver->internal()->set_mline_index(mline_index);
2642 return std::move(transceiver);
2643}
2644
2645rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2646PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2647 RTC_DCHECK(IsUnifiedPlan());
2648 for (auto transceiver : transceivers_) {
2649 if (transceiver->mid() == mid) {
2650 return transceiver;
2651 }
2652 }
2653 return nullptr;
2654}
2655
2656rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2657PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2658 RTC_DCHECK(IsUnifiedPlan());
2659 for (auto transceiver : transceivers_) {
2660 if (transceiver->internal()->mline_index() == mline_index) {
2661 return transceiver;
2662 }
2663 }
2664 return nullptr;
2665}
2666
2667rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2668PeerConnection::FindAvailableTransceiverToReceive(
2669 cricket::MediaType media_type) const {
2670 RTC_DCHECK(IsUnifiedPlan());
2671 // From JSEP section 5.10 (Applying a Remote Description):
2672 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2673 // the same type that were added to the PeerConnection by addTrack and are not
2674 // associated with any m= section and are not stopped, find the first such
2675 // RtpTransceiver.
2676 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002677 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002678 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2679 !transceiver->stopped()) {
2680 return transceiver;
2681 }
2682 }
2683 return nullptr;
2684}
2685
Steve Antoned10bd92017-12-05 10:52:59 -08002686const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2687 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2688 transceiver,
2689 const SessionDescriptionInterface* sdesc) const {
2690 RTC_DCHECK(transceiver);
2691 RTC_DCHECK(sdesc);
2692 if (IsUnifiedPlan()) {
2693 if (!transceiver->internal()->mid()) {
2694 // This transceiver is not associated with a media section yet.
2695 return nullptr;
2696 }
2697 return sdesc->description()->GetContentByName(
2698 *transceiver->internal()->mid());
2699 } else {
2700 // Plan B only allows at most one audio and one video section, so use the
2701 // first media section of that type.
2702 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002703 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002704 }
2705}
2706
deadbeef46c73892016-11-16 19:42:04 -08002707PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2708 return configuration_;
2709}
2710
deadbeef293e9262017-01-11 12:28:30 -08002711bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2712 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002713 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002714
Steve Anton75737c02017-11-06 10:37:17 -08002715 if (local_description() && configuration.ice_candidate_pool_size !=
2716 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002717 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2718 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002719 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002720 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002721
deadbeef293e9262017-01-11 12:28:30 -08002722 // The simplest (and most future-compatible) way to tell if the config was
2723 // modified in an invalid way is to copy each property we do support
2724 // modifying, then use operator==. There are far more properties we don't
2725 // support modifying than those we do, and more could be added.
2726 RTCConfiguration modified_config = configuration_;
2727 modified_config.servers = configuration.servers;
2728 modified_config.type = configuration.type;
2729 modified_config.ice_candidate_pool_size =
2730 configuration.ice_candidate_pool_size;
2731 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002732 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002733 modified_config.ice_check_interval_strong_connectivity =
2734 configuration.ice_check_interval_strong_connectivity;
2735 modified_config.ice_check_interval_weak_connectivity =
2736 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002737 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2738 modified_config.ice_unwritable_min_checks =
2739 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002740 modified_config.stun_candidate_keepalive_interval =
2741 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002742 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002743 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002744 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002745 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002746 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2747 }
2748
Steve Anton038834f2017-07-14 15:59:59 -07002749 // Validate the modified configuration.
2750 RTCError validate_error = ValidateConfiguration(modified_config);
2751 if (!validate_error.ok()) {
2752 return SafeSetError(std::move(validate_error), error);
2753 }
2754
deadbeef293e9262017-01-11 12:28:30 -08002755 // Note that this isn't possible through chromium, since it's an unsigned
2756 // short in WebIDL.
2757 if (configuration.ice_candidate_pool_size < 0 ||
2758 configuration.ice_candidate_pool_size > UINT16_MAX) {
2759 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2760 }
2761
2762 // Parse ICE servers before hopping to network thread.
2763 cricket::ServerAddresses stun_servers;
2764 std::vector<cricket::RelayServerConfig> turn_servers;
2765 RTCErrorType parse_error =
2766 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2767 if (parse_error != RTCErrorType::NONE) {
2768 return SafeSetError(parse_error, error);
2769 }
2770
2771 // In theory this shouldn't fail.
2772 if (!network_thread()->Invoke<bool>(
2773 RTC_FROM_HERE,
2774 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2775 stun_servers, turn_servers, modified_config.type,
2776 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002777 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002778 modified_config.turn_customizer,
2779 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002780 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002781 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2782 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002783
deadbeefd1a38b52016-12-10 13:15:33 -08002784 // As described in JSEP, calling setConfiguration with new ICE servers or
2785 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2786 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002787 if (modified_config.servers != configuration_.servers ||
2788 modified_config.type != configuration_.type ||
2789 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002790 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002791 }
skvladd1f5fda2017-02-03 16:54:05 -08002792
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002793 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002794
deadbeef293e9262017-01-11 12:28:30 -08002795 configuration_ = modified_config;
2796 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002797}
2798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799bool PeerConnection::AddIceCandidate(
2800 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002801 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002802 if (IsClosed()) {
2803 return false;
2804 }
Steve Antond25da372017-11-06 14:50:29 -08002805
2806 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002807 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002808 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002809 return false;
2810 }
2811
2812 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002813 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002814 return false;
2815 }
2816
2817 bool valid = false;
2818 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2819 if (!valid) {
2820 return false;
2821 }
2822
2823 // Add this candidate to the remote session description.
2824 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002825 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002826 return false;
2827 }
2828
2829 if (ready) {
2830 return UseCandidate(ice_candidate);
2831 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002832 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002833 return true;
2834 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835}
2836
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002837bool PeerConnection::RemoveIceCandidates(
2838 const std::vector<cricket::Candidate>& candidates) {
2839 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002840 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002841 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002842 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002843 return false;
2844 }
2845
2846 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002847 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002848 return false;
2849 }
2850
2851 size_t number_removed =
2852 mutable_remote_description()->RemoveCandidates(candidates);
2853 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002854 RTC_LOG(LS_ERROR)
2855 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002856 "Requested "
2857 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002858 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002859 }
2860
2861 // Remove the candidates from the transport controller.
2862 std::string error;
2863 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2864 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002865 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002866 }
2867 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002868}
2869
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002870void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002871 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002872 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002873
Steve Anton75737c02017-11-06 10:37:17 -08002874 if (transport_controller()) {
2875 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002876 }
2877
Steve Antondb67ba12018-03-19 17:41:42 -07002878 for (auto transceiver : transceivers_) {
2879 auto* channel = transceiver->internal()->channel();
2880 if (channel) {
2881 channel->SetMetricsObserver(uma_observer_);
2882 }
2883 }
2884
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002885 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002886 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002887 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002888 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002889 uma_observer_->IncrementEnumCounter(
2890 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2891 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002892 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002893 uma_observer_->IncrementEnumCounter(
2894 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2895 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002896 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002897 // Send information about the requested SDP semantics.
2898 switch (configuration_.sdp_semantics) {
2899 case SdpSemantics::kDefault:
2900 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2901 kSdpSemanticRequestDefault,
2902 kSdpSemanticRequestMax);
2903
2904 break;
2905 case SdpSemantics::kPlanB:
2906 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2907 kSdpSemanticRequestPlanB,
2908 kSdpSemanticRequestMax);
2909 break;
2910 case SdpSemantics::kUnifiedPlan:
2911 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2912 kSdpSemanticRequestUnifiedPlan,
2913 kSdpSemanticRequestMax);
2914 break;
2915 default:
2916 RTC_NOTREACHED();
2917 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002918 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002919}
2920
zstein4b979802017-06-02 14:37:37 -07002921RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002922 if (!worker_thread()->IsCurrent()) {
2923 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002924 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2925 }
2926
2927 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2928 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2929 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2930 if (has_min && *bitrate.min_bitrate_bps < 0) {
2931 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2932 "min_bitrate_bps <= 0");
2933 }
2934 if (has_current) {
2935 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2936 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2937 "current_bitrate_bps < min_bitrate_bps");
2938 } else if (*bitrate.current_bitrate_bps < 0) {
2939 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2940 "curent_bitrate_bps < 0");
2941 }
2942 }
2943 if (has_max) {
2944 if (has_current &&
2945 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2946 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2947 "max_bitrate_bps < current_bitrate_bps");
2948 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2949 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2950 "max_bitrate_bps < min_bitrate_bps");
2951 } else if (*bitrate.max_bitrate_bps < 0) {
2952 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2953 "max_bitrate_bps < 0");
2954 }
2955 }
2956
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002957 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002958 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2959 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2960 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2961
2962 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002963 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002964
2965 return RTCError::OK();
2966}
2967
Alex Narest78609d52017-10-20 10:37:47 +02002968void PeerConnection::SetBitrateAllocationStrategy(
2969 std::unique_ptr<rtc::BitrateAllocationStrategy>
2970 bitrate_allocation_strategy) {
2971 rtc::Thread* worker_thread = factory_->worker_thread();
2972 if (!worker_thread->IsCurrent()) {
2973 rtc::BitrateAllocationStrategy* strategy_raw =
2974 bitrate_allocation_strategy.release();
2975 auto functor = [this, strategy_raw]() {
2976 call_->SetBitrateAllocationStrategy(
2977 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2978 };
2979 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2980 return;
2981 }
2982 RTC_DCHECK(call_.get());
2983 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2984}
2985
henrika5f6bf242017-11-01 11:06:56 +01002986void PeerConnection::SetAudioPlayout(bool playout) {
2987 if (!worker_thread()->IsCurrent()) {
2988 worker_thread()->Invoke<void>(
2989 RTC_FROM_HERE,
2990 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2991 return;
2992 }
2993 auto audio_state =
2994 factory_->channel_manager()->media_engine()->GetAudioState();
2995 audio_state->SetPlayout(playout);
2996}
2997
2998void PeerConnection::SetAudioRecording(bool recording) {
2999 if (!worker_thread()->IsCurrent()) {
3000 worker_thread()->Invoke<void>(
3001 RTC_FROM_HERE,
3002 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3003 return;
3004 }
3005 auto audio_state =
3006 factory_->channel_manager()->media_engine()->GetAudioState();
3007 audio_state->SetRecording(recording);
3008}
3009
Steve Anton8c0f7a72017-10-03 10:03:10 -07003010std::unique_ptr<rtc::SSLCertificate>
3011PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003012 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3013 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003014 return nullptr;
3015 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003016 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003017}
3018
Zhi Huang70b820f2018-01-27 14:16:15 -08003019std::unique_ptr<rtc::SSLCertChain>
3020PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003021 auto audio_transceiver = GetFirstAudioTransceiver();
3022 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003023 return nullptr;
3024 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003025 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003026 audio_transceiver->internal()->channel()->transport_name());
3027}
3028
3029rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3030PeerConnection::GetFirstAudioTransceiver() const {
3031 for (auto transceiver : transceivers_) {
3032 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3033 return transceiver;
3034 }
3035 }
3036 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003037}
3038
ivoc14d5dbe2016-07-04 07:06:55 -07003039bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3040 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003041 // TODO(eladalon): It would be better to not allow negative values into PC.
3042 const size_t max_size = (max_size_bytes < 0)
3043 ? RtcEventLog::kUnlimitedOutput
3044 : rtc::saturated_cast<size_t>(max_size_bytes);
3045 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003046 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3047 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003048}
3049
Bjorn Tereliusde939432017-11-20 17:38:14 +01003050bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3051 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003052 // TODO(eladalon): In C++14, this can be done with a lambda.
3053 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003054 bool operator()() {
3055 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3056 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003057 PeerConnection* const pc;
3058 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003059 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003060 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003061 return worker_thread()->Invoke<bool>(
3062 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003063}
3064
3065void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003066 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003067 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3068}
3069
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003071 return pending_local_description_ ? pending_local_description_.get()
3072 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003073}
3074
3075const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003076 return pending_remote_description_ ? pending_remote_description_.get()
3077 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078}
3079
deadbeeffe4a8a42016-12-20 17:56:17 -08003080const SessionDescriptionInterface* PeerConnection::current_local_description()
3081 const {
Steve Anton75737c02017-11-06 10:37:17 -08003082 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003083}
3084
3085const SessionDescriptionInterface* PeerConnection::current_remote_description()
3086 const {
Steve Anton75737c02017-11-06 10:37:17 -08003087 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003088}
3089
3090const SessionDescriptionInterface* PeerConnection::pending_local_description()
3091 const {
Steve Anton75737c02017-11-06 10:37:17 -08003092 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003093}
3094
3095const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3096 const {
Steve Anton75737c02017-11-06 10:37:17 -08003097 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003098}
3099
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003101 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 // Update stats here so that we have the most recent stats for tracks and
3103 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003104 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003105
Steve Anton75737c02017-11-06 10:37:17 -08003106 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003107
Steve Anton8af21862017-12-15 11:20:13 -08003108 for (auto transceiver : transceivers_) {
3109 transceiver->Stop();
3110 }
3111 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003112
Qingsi Wang93a84392018-01-30 17:13:09 -08003113 // The event log is used in the transport controller, which must be outlived
3114 // by the former. CreateOffer by the peer connection is implemented
3115 // asynchronously and if the peer connection is closed without resetting the
3116 // WebRTC session description factory, the session description factory would
3117 // call the transport controller.
3118 webrtc_session_desc_factory_.reset();
3119 transport_controller_.reset();
3120
deadbeef42a42632017-03-10 15:18:00 -08003121 network_thread()->Invoke<void>(
3122 RTC_FROM_HERE,
3123 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3124 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003125
Steve Anton978b8762017-09-29 12:15:02 -07003126 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003127 call_.reset();
3128 // The event log must outlive call (and any other object that uses it).
3129 event_log_.reset();
3130 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003131}
3132
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003133void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003135 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3136 SetSessionDescriptionMsg* param =
3137 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3138 param->observer->OnSuccess();
3139 delete param;
3140 break;
3141 }
3142 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3143 SetSessionDescriptionMsg* param =
3144 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003145 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 delete param;
3147 break;
3148 }
deadbeefab9b2d12015-10-14 11:33:11 -07003149 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3150 CreateSessionDescriptionMsg* param =
3151 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003152 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003153 delete param;
3154 break;
3155 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156 case MSG_GETSTATS: {
3157 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003158 StatsReports reports;
3159 stats_->GetStats(param->track, &reports);
3160 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161 delete param;
3162 break;
3163 }
deadbeefbd292462015-12-14 18:15:29 -08003164 case MSG_FREE_DATACHANNELS: {
3165 sctp_data_channels_to_free_.clear();
3166 break;
3167 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003169 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170 break;
3171 }
3172}
3173
Steve Antonafb0bb72018-02-20 11:35:37 -08003174cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3175 RTC_DCHECK(!IsUnifiedPlan());
3176 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3177 GetAudioTransceiver()->internal()->channel());
3178 if (voice_channel) {
3179 return voice_channel->media_channel();
3180 } else {
3181 return nullptr;
3182 }
3183}
3184
3185cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3186 RTC_DCHECK(!IsUnifiedPlan());
3187 auto* video_channel = static_cast<cricket::VideoChannel*>(
3188 GetVideoTransceiver()->internal()->channel());
3189 if (video_channel) {
3190 return video_channel->media_channel();
3191 } else {
3192 return nullptr;
3193 }
3194}
3195
Steve Anton4171afb2017-11-20 10:20:22 -08003196void PeerConnection::CreateAudioReceiver(
3197 MediaStreamInterface* stream,
3198 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003199 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3200 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003201 auto* audio_receiver = new AudioRtpReceiver(
3202 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003203 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003204 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3205 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3206 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003207 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003208 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003209}
3210
Steve Anton4171afb2017-11-20 10:20:22 -08003211void PeerConnection::CreateVideoReceiver(
3212 MediaStreamInterface* stream,
3213 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003214 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3215 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003216 auto* video_receiver = new VideoRtpReceiver(
3217 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003218 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003219 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3220 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3221 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003222 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003223 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224}
3225
deadbeef70ab1a12015-09-28 16:53:55 -07003226// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3227// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003228rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003229 const RtpSenderInfo& remote_sender_info) {
3230 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3231 if (!receiver) {
3232 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3233 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003234 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003235 }
Steve Anton4171afb2017-11-20 10:20:22 -08003236 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3237 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3238 } else {
3239 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3240 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003241 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242}
3243
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003244void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3245 MediaStreamInterface* stream) {
3246 RTC_DCHECK(!IsClosed());
3247 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003248 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003249 // We already have a sender for this track, so just change the stream_id
3250 // so that it's correct in the next call to CreateOffer.
Seth Hampson13b8bad2018-03-13 16:05:28 -07003251 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003252 return;
3253 }
3254
3255 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003256 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003257 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003258 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003259 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003260 // If the sender has already been configured in SDP, we call SetSsrc,
3261 // which will connect the sender to the underlying transport. This can
3262 // occur if a local session description that contains the ID of the sender
3263 // is set before AddStream is called. It can also occur if the local
3264 // session description is not changed and RemoveStream is called, and
3265 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003266 const RtpSenderInfo* sender_info =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003267 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003268 if (sender_info) {
3269 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003270 }
3271}
3272
3273// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3274// indefinitely, when we have unified plan SDP.
3275void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3276 MediaStreamInterface* stream) {
3277 RTC_DCHECK(!IsClosed());
3278 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003279 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003280 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3281 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003282 return;
3283 }
Steve Anton4171afb2017-11-20 10:20:22 -08003284 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003285}
3286
3287void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3288 MediaStreamInterface* stream) {
3289 RTC_DCHECK(!IsClosed());
3290 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003291 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003292 // We already have a sender for this track, so just change the stream_id
3293 // so that it's correct in the next call to CreateOffer.
Seth Hampson13b8bad2018-03-13 16:05:28 -07003294 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003295 return;
3296 }
3297
3298 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003299 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003300 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003301 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003302 GetVideoTransceiver()->internal()->AddSender(new_sender);
3303 const RtpSenderInfo* sender_info =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003304 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003305 if (sender_info) {
3306 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003307 }
3308}
3309
3310void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3311 MediaStreamInterface* stream) {
3312 RTC_DCHECK(!IsClosed());
3313 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003314 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003315 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3316 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003317 return;
3318 }
Steve Anton4171afb2017-11-20 10:20:22 -08003319 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003320}
3321
Steve Antonba818672017-11-06 10:21:57 -08003322void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003323 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003324 if (ice_connection_state_ == new_state) {
3325 return;
3326 }
3327
deadbeefcbecd352015-09-23 11:50:27 -07003328 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003329 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003330 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003331 return;
3332 }
Steve Antonba818672017-11-06 10:21:57 -08003333
Mirko Bonadei675513b2017-11-09 11:09:25 +01003334 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3335 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003336 RTC_DCHECK(ice_connection_state_ !=
3337 PeerConnectionInterface::kIceConnectionClosed);
3338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003340 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341}
3342
3343void PeerConnection::OnIceGatheringChange(
3344 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003345 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 if (IsClosed()) {
3347 return;
3348 }
3349 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003350 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003351}
3352
jbauch81bf7b02017-03-25 08:31:12 -07003353void PeerConnection::OnIceCandidate(
3354 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003355 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003356 if (IsClosed()) {
3357 return;
3358 }
jbauch81bf7b02017-03-25 08:31:12 -07003359 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003360}
3361
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003362void PeerConnection::OnIceCandidatesRemoved(
3363 const std::vector<cricket::Candidate>& candidates) {
3364 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003365 if (IsClosed()) {
3366 return;
3367 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003368 observer_->OnIceCandidatesRemoved(candidates);
3369}
3370
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371void PeerConnection::ChangeSignalingState(
3372 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003373 RTC_DCHECK(signaling_thread()->IsCurrent());
3374 if (signaling_state_ == signaling_state) {
3375 return;
3376 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003377 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3378 << GetSignalingStateString(signaling_state_)
3379 << " New state: "
3380 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381 signaling_state_ = signaling_state;
3382 if (signaling_state == kClosed) {
3383 ice_connection_state_ = kIceConnectionClosed;
3384 observer_->OnIceConnectionChange(ice_connection_state_);
3385 if (ice_gathering_state_ != kIceGatheringComplete) {
3386 ice_gathering_state_ = kIceGatheringComplete;
3387 observer_->OnIceGatheringChange(ice_gathering_state_);
3388 }
3389 }
3390 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391}
3392
deadbeefeb459812015-12-15 19:24:43 -08003393void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3394 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003395 if (IsClosed()) {
3396 return;
3397 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003398 AddAudioTrack(track, stream);
3399 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003400}
3401
deadbeefeb459812015-12-15 19:24:43 -08003402void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3403 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003404 if (IsClosed()) {
3405 return;
3406 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003407 RemoveAudioTrack(track, stream);
3408 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003409}
3410
3411void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3412 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003413 if (IsClosed()) {
3414 return;
3415 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003416 AddVideoTrack(track, stream);
3417 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003418}
3419
3420void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3421 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003422 if (IsClosed()) {
3423 return;
3424 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003425 RemoveVideoTrack(track, stream);
3426 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003427}
3428
Henrik Boström31638672017-11-23 17:48:32 +01003429void PeerConnection::PostSetSessionDescriptionSuccess(
3430 SetSessionDescriptionObserver* observer) {
3431 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3432 signaling_thread()->Post(RTC_FROM_HERE, this,
3433 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3434}
3435
deadbeefab9b2d12015-10-14 11:33:11 -07003436void PeerConnection::PostSetSessionDescriptionFailure(
3437 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003438 RTCError&& error) {
3439 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003440 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003441 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003442 signaling_thread()->Post(RTC_FROM_HERE, this,
3443 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003444}
3445
3446void PeerConnection::PostCreateSessionDescriptionFailure(
3447 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003448 RTCError error) {
3449 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003450 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003451 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003452 signaling_thread()->Post(RTC_FROM_HERE, this,
3453 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003454}
3455
zhihuang1c378ed2017-08-17 14:10:50 -07003456void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003457 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003458 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003459 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003460
Steve Antondcc3c022017-12-22 16:02:54 -08003461 if (IsUnifiedPlan()) {
3462 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3463 } else {
3464 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3465 }
3466
Steve Antonfa2260d2017-12-28 16:38:23 -08003467 // Intentionally unset the data channel type for RTP data channel with the
3468 // second condition. Otherwise the RTP data channels would be successfully
3469 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3470 // when building with chromium. We want to leave RTP data channels broken, so
3471 // people won't try to use them.
3472 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3473 session_options->data_channel_type = data_channel_type();
3474 }
3475
Steve Antondcc3c022017-12-22 16:02:54 -08003476 // Apply ICE restart flag and renomination flag.
3477 for (auto& options : session_options->media_description_options) {
3478 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3479 options.transport_options.enable_ice_renomination =
3480 configuration_.enable_ice_renomination;
3481 }
3482
3483 session_options->rtcp_cname = rtcp_cname_;
3484 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003485 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003486}
3487
3488void PeerConnection::GetOptionsForPlanBOffer(
3489 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3490 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003491 // Figure out transceiver directional preferences.
3492 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3493 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3494
3495 // By default, generate sendrecv/recvonly m= sections.
3496 bool recv_audio = true;
3497 bool recv_video = true;
3498
3499 // By default, only offer a new m= section if we have media to send with it.
3500 bool offer_new_audio_description = send_audio;
3501 bool offer_new_video_description = send_video;
3502 bool offer_new_data_description = HasDataChannels();
3503
3504 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003505 if (offer_answer_options.offer_to_receive_audio !=
3506 RTCOfferAnswerOptions::kUndefined) {
3507 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003508 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003509 offer_new_audio_description ||
3510 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003511 }
Steve Antondcc3c022017-12-22 16:02:54 -08003512 if (offer_answer_options.offer_to_receive_video !=
3513 RTCOfferAnswerOptions::kUndefined) {
3514 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003515 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003516 offer_new_video_description ||
3517 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003518 }
3519
3520 rtc::Optional<size_t> audio_index;
3521 rtc::Optional<size_t> video_index;
3522 rtc::Optional<size_t> data_index;
3523 // If a current description exists, generate m= sections in the same order,
3524 // using the first audio/video/data section that appears and rejecting
3525 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003526 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003527 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003528 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003529 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3530 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3531 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003532 }
3533
zhihuang1c378ed2017-08-17 14:10:50 -07003534 // Add audio/video/data m= sections to the end if needed.
3535 if (!audio_index && offer_new_audio_description) {
3536 session_options->media_description_options.push_back(
3537 cricket::MediaDescriptionOptions(
3538 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003539 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3540 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003541 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003542 }
zhihuang1c378ed2017-08-17 14:10:50 -07003543 if (!video_index && offer_new_video_description) {
3544 session_options->media_description_options.push_back(
3545 cricket::MediaDescriptionOptions(
3546 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003547 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3548 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003549 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003550 }
zhihuang1c378ed2017-08-17 14:10:50 -07003551 if (!data_index && offer_new_data_description) {
3552 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003553 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003554 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003555 }
3556
3557 cricket::MediaDescriptionOptions* audio_media_description_options =
3558 !audio_index ? nullptr
3559 : &session_options->media_description_options[*audio_index];
3560 cricket::MediaDescriptionOptions* video_media_description_options =
3561 !video_index ? nullptr
3562 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003563
Steve Anton4171afb2017-11-20 10:20:22 -08003564 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003565 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003566}
3567
3568// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3569// and return a reference to it.
3570// Generated MIDs should be no more than 3 bytes long to take up less space in
3571// the RTP packet.
3572static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3573 RTC_DCHECK(used_mids);
3574 // We're boring: just generate MIDs 0, 1, 2, ...
3575 size_t i = 0;
3576 std::set<std::string>::iterator it;
3577 bool inserted;
3578 do {
3579 std::string mid = rtc::ToString(i++);
3580 auto insert_result = used_mids->insert(mid);
3581 it = insert_result.first;
3582 inserted = insert_result.second;
3583 } while (!inserted);
3584 return *it;
3585}
3586
3587static cricket::MediaDescriptionOptions
3588GetMediaDescriptionOptionsForTransceiver(
3589 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3590 transceiver,
3591 const std::string& mid) {
3592 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003593 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003594 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003595 // This behavior is specified in JSEP. The gist is that:
3596 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3597 // sendrecv.
3598 // 2. If the MSID is included, then it must be included in any subsequent
3599 // offer/answer exactly the same until the RtpTransceiver is stopped.
3600 if (!transceiver->stopped() &&
3601 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3602 transceiver->internal()->has_ever_been_used_to_send())) {
3603 cricket::SenderOptions sender_options;
3604 sender_options.track_id = transceiver->sender()->id();
3605 sender_options.stream_ids = transceiver->sender()->stream_ids();
3606 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3607 // set in the RTP parameters when the transceiver was added.
3608 sender_options.num_sim_layers = 1;
3609 media_description_options.sender_options.push_back(sender_options);
3610 }
Steve Antondcc3c022017-12-22 16:02:54 -08003611 return media_description_options;
3612}
3613
3614void PeerConnection::GetOptionsForUnifiedPlanOffer(
3615 const RTCOfferAnswerOptions& offer_answer_options,
3616 cricket::MediaSessionOptions* session_options) {
3617 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3618 // Offers) and 5.2.2 (Subsequent Offers).
3619 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3620 const ContentInfos& local_contents =
3621 (local_description() ? local_description()->description()->contents()
3622 : ContentInfos());
3623 const ContentInfos& remote_contents =
3624 (remote_description() ? remote_description()->description()->contents()
3625 : ContentInfos());
3626 // The mline indices that can be recycled. New transceivers should reuse these
3627 // slots first.
3628 std::queue<size_t> recycleable_mline_indices;
3629 // Track the MIDs used in previous offer/answer exchanges and the current
3630 // offer so that new, unique MIDs are generated.
3631 std::set<std::string> used_mids = seen_mids_;
3632 // First, go through each media section that exists in either the local or
3633 // remote description and generate a media section in this offer for the
3634 // associated transceiver. If a media section can be recycled, generate a
3635 // default, rejected media section here that can be later overwritten.
3636 for (size_t i = 0;
3637 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3638 // Either |local_content| or |remote_content| is non-null.
3639 const ContentInfo* local_content =
3640 (i < local_contents.size() ? &local_contents[i] : nullptr);
3641 const ContentInfo* remote_content =
3642 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3643 bool had_been_rejected = (local_content && local_content->rejected) ||
3644 (remote_content && remote_content->rejected);
3645 const std::string& mid =
3646 (local_content ? local_content->name : remote_content->name);
3647 cricket::MediaType media_type =
3648 (local_content ? local_content->media_description()->type()
3649 : remote_content->media_description()->type());
3650 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3651 media_type == cricket::MEDIA_TYPE_VIDEO) {
3652 auto transceiver = GetAssociatedTransceiver(mid);
3653 RTC_CHECK(transceiver);
3654 // A media section is considered eligible for recycling if it is marked as
3655 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003656 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003657 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003658 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3659 RtpTransceiverDirection::kInactive,
3660 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003661 recycleable_mline_indices.push(i);
3662 } else {
3663 session_options->media_description_options.push_back(
3664 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3665 // CreateOffer shouldn't really cause any state changes in
3666 // PeerConnection, but we need a way to match new transceivers to new
3667 // media sections in SetLocalDescription and JSEP specifies this is done
3668 // by recording the index of the media section generated for the
3669 // transceiver in the offer.
3670 transceiver->internal()->set_mline_index(i);
3671 }
3672 } else {
3673 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003674 RTC_CHECK(GetDataMid());
3675 if (had_been_rejected || mid != *GetDataMid()) {
3676 session_options->media_description_options.push_back(
3677 GetMediaDescriptionOptionsForRejectedData(mid));
3678 } else {
3679 session_options->media_description_options.push_back(
3680 GetMediaDescriptionOptionsForActiveData(mid));
3681 }
Steve Antondcc3c022017-12-22 16:02:54 -08003682 }
3683 }
3684 // Next, look for transceivers that are newly added (that is, are not stopped
3685 // and not associated). Reuse media sections marked as recyclable first,
3686 // otherwise append to the end of the offer. New media sections should be
3687 // added in the order they were added to the PeerConnection.
3688 for (auto transceiver : transceivers_) {
3689 if (transceiver->mid() || transceiver->stopped()) {
3690 continue;
3691 }
3692 size_t mline_index;
3693 if (!recycleable_mline_indices.empty()) {
3694 mline_index = recycleable_mline_indices.front();
3695 recycleable_mline_indices.pop();
3696 session_options->media_description_options[mline_index] =
3697 GetMediaDescriptionOptionsForTransceiver(transceiver,
3698 AllocateMid(&used_mids));
3699 } else {
3700 mline_index = session_options->media_description_options.size();
3701 session_options->media_description_options.push_back(
3702 GetMediaDescriptionOptionsForTransceiver(transceiver,
3703 AllocateMid(&used_mids)));
3704 }
3705 // See comment above for why CreateOffer changes the transceiver's state.
3706 transceiver->internal()->set_mline_index(mline_index);
3707 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003708 // Lastly, add a m-section if we have local data channels and an m section
3709 // does not already exist.
3710 if (!GetDataMid() && HasDataChannels()) {
3711 session_options->media_description_options.push_back(
3712 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3713 }
Steve Antondcc3c022017-12-22 16:02:54 -08003714}
3715
3716void PeerConnection::GetOptionsForAnswer(
3717 const RTCOfferAnswerOptions& offer_answer_options,
3718 cricket::MediaSessionOptions* session_options) {
3719 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3720
3721 if (IsUnifiedPlan()) {
3722 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3723 } else {
3724 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3725 }
3726
Steve Antonfa2260d2017-12-28 16:38:23 -08003727 // Intentionally unset the data channel type for RTP data channel. Otherwise
3728 // the RTP data channels would be successfully negotiated by default and the
3729 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3730 // We want to leave RTP data channels broken, so people won't try to use them.
3731 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3732 session_options->data_channel_type = data_channel_type();
3733 }
3734
Steve Antondcc3c022017-12-22 16:02:54 -08003735 // Apply ICE renomination flag.
3736 for (auto& options : session_options->media_description_options) {
3737 options.transport_options.enable_ice_renomination =
3738 configuration_.enable_ice_renomination;
3739 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003740
3741 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003742 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003743 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003744}
3745
Steve Antondcc3c022017-12-22 16:02:54 -08003746void PeerConnection::GetOptionsForPlanBAnswer(
3747 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003748 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003749 // Figure out transceiver directional preferences.
3750 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3751 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3752
3753 // By default, generate sendrecv/recvonly m= sections. The direction is also
3754 // restricted by the direction in the offer.
3755 bool recv_audio = true;
3756 bool recv_video = true;
3757
3758 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003759 if (offer_answer_options.offer_to_receive_audio !=
3760 RTCOfferAnswerOptions::kUndefined) {
3761 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003762 }
Steve Antondcc3c022017-12-22 16:02:54 -08003763 if (offer_answer_options.offer_to_receive_video !=
3764 RTCOfferAnswerOptions::kUndefined) {
3765 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003766 }
3767
3768 rtc::Optional<size_t> audio_index;
3769 rtc::Optional<size_t> video_index;
3770 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003771
3772 // Generate m= sections that match those in the offer.
3773 // Note that mediasession.cc will handle intersection our preferred
3774 // direction with the offered direction.
3775 GenerateMediaDescriptionOptions(
3776 remote_description(),
3777 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3778 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3779 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003780
3781 cricket::MediaDescriptionOptions* audio_media_description_options =
3782 !audio_index ? nullptr
3783 : &session_options->media_description_options[*audio_index];
3784 cricket::MediaDescriptionOptions* video_media_description_options =
3785 !video_index ? nullptr
3786 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003787
Steve Anton4171afb2017-11-20 10:20:22 -08003788 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003789 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003790}
zhihuangaf388472016-11-02 16:49:48 -07003791
Steve Antondcc3c022017-12-22 16:02:54 -08003792void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3793 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3794 cricket::MediaSessionOptions* session_options) {
3795 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3796 // Answers) and 5.3.2 (Subsequent Answers).
3797 RTC_DCHECK(remote_description());
3798 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3799 for (const ContentInfo& content :
3800 remote_description()->description()->contents()) {
3801 cricket::MediaType media_type = content.media_description()->type();
3802 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3803 media_type == cricket::MEDIA_TYPE_VIDEO) {
3804 auto transceiver = GetAssociatedTransceiver(content.name);
3805 RTC_CHECK(transceiver);
3806 session_options->media_description_options.push_back(
3807 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3808 } else {
3809 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003810 // Reject all data sections if data channels are disabled.
3811 // Reject a data section if it has already been rejected.
3812 // Reject all data sections except for the first one.
3813 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3814 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003815 session_options->media_description_options.push_back(
3816 GetMediaDescriptionOptionsForRejectedData(content.name));
3817 } else {
3818 session_options->media_description_options.push_back(
3819 GetMediaDescriptionOptionsForActiveData(content.name));
3820 }
Steve Antondcc3c022017-12-22 16:02:54 -08003821 }
3822 }
htaa2a49d92016-03-04 02:51:39 -08003823}
3824
zhihuang1c378ed2017-08-17 14:10:50 -07003825void PeerConnection::GenerateMediaDescriptionOptions(
3826 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003827 RtpTransceiverDirection audio_direction,
3828 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003829 rtc::Optional<size_t>* audio_index,
3830 rtc::Optional<size_t>* video_index,
3831 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003832 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003833 for (const cricket::ContentInfo& content :
3834 session_desc->description()->contents()) {
3835 if (IsAudioContent(&content)) {
3836 // If we already have an audio m= section, reject this extra one.
3837 if (*audio_index) {
3838 session_options->media_description_options.push_back(
3839 cricket::MediaDescriptionOptions(
3840 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003841 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003842 } else {
3843 session_options->media_description_options.push_back(
3844 cricket::MediaDescriptionOptions(
3845 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003846 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003847 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003848 }
3849 } else if (IsVideoContent(&content)) {
3850 // If we already have an video m= section, reject this extra one.
3851 if (*video_index) {
3852 session_options->media_description_options.push_back(
3853 cricket::MediaDescriptionOptions(
3854 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003855 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003856 } else {
3857 session_options->media_description_options.push_back(
3858 cricket::MediaDescriptionOptions(
3859 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003860 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003861 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003862 }
3863 } else {
3864 RTC_DCHECK(IsDataContent(&content));
3865 // If we already have an data m= section, reject this extra one.
3866 if (*data_index) {
3867 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003868 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003869 } else {
3870 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003871 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003872 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003873 }
3874 }
htaa2a49d92016-03-04 02:51:39 -08003875 }
deadbeefab9b2d12015-10-14 11:33:11 -07003876}
3877
Steve Antonfa2260d2017-12-28 16:38:23 -08003878cricket::MediaDescriptionOptions
3879PeerConnection::GetMediaDescriptionOptionsForActiveData(
3880 const std::string& mid) const {
3881 // Direction for data sections is meaningless, but legacy endpoints might
3882 // expect sendrecv.
3883 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3884 RtpTransceiverDirection::kSendRecv,
3885 /*stopped=*/false);
3886 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3887 return options;
3888}
3889
3890cricket::MediaDescriptionOptions
3891PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3892 const std::string& mid) const {
3893 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3894 RtpTransceiverDirection::kInactive,
3895 /*stopped=*/true);
3896 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3897 return options;
3898}
3899
3900rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3901 switch (data_channel_type_) {
3902 case cricket::DCT_RTP:
3903 if (!rtp_data_channel_) {
3904 return rtc::nullopt;
3905 }
3906 return rtp_data_channel_->content_name();
3907 case cricket::DCT_SCTP:
3908 return sctp_content_name_;
3909 default:
3910 return rtc::nullopt;
3911 }
3912}
3913
Steve Anton4171afb2017-11-20 10:20:22 -08003914void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3915 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3916 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003917 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003918}
3919
Steve Anton4171afb2017-11-20 10:20:22 -08003920void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003921 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003922 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003923 cricket::MediaType media_type,
3924 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003925 std::vector<RtpSenderInfo>* current_senders =
3926 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003927
Steve Anton4171afb2017-11-20 10:20:22 -08003928 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003929 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003930 for (auto sender_it = current_senders->begin();
3931 sender_it != current_senders->end();
3932 /* incremented manually */) {
3933 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003934 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003935 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3936 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003937 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003938 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003939 sender_exists) {
3940 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003941 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003942 OnRemoteSenderRemoved(info, media_type);
3943 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003944 }
3945 }
3946
Steve Anton4171afb2017-11-20 10:20:22 -08003947 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003948 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08003949 // |params.id| is the sender id and the stream id uses the first of
3950 // |params.stream_ids|.
3951 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
3952 const std::string& stream_id =
3953 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003954 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003955 uint32_t ssrc = params.first_ssrc();
3956
3957 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003958 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003959 if (!stream) {
3960 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003961 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08003962 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07003963 remote_streams_->AddStream(stream);
3964 new_streams->AddStream(stream);
3965 }
3966
Steve Anton4171afb2017-11-20 10:20:22 -08003967 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08003968 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003969 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08003970 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08003971 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003972 }
3973 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003974
Steve Anton4171afb2017-11-20 10:20:22 -08003975 // Add default sender if necessary.
3976 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003977 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003978 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08003979 if (!default_stream) {
3980 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003981 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08003982 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08003983 remote_streams_->AddStream(default_stream);
3984 new_streams->AddStream(default_stream);
3985 }
Steve Anton4171afb2017-11-20 10:20:22 -08003986 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3987 ? kDefaultAudioSenderId
3988 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08003989 const RtpSenderInfo* default_sender_info =
3990 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003991 if (!default_sender_info) {
3992 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08003993 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08003994 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003995 }
3996 }
deadbeefab9b2d12015-10-14 11:33:11 -07003997}
3998
Steve Anton4171afb2017-11-20 10:20:22 -08003999void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4000 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004001 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004002
4003 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004004 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004005 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004006 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004007 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004008 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004009 }
4010}
4011
Steve Anton4171afb2017-11-20 10:20:22 -08004012void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4013 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004014 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004015
Henrik Boström933d8b02017-10-10 10:05:16 -07004016 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004017 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004018 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4019 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004020 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004021 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004022 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004023 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004024 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004025 }
4026 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004027 // Stopping or destroying a VideoRtpReceiver will end the
4028 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004029 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004030 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004031 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004032 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004033 // There's no guarantee the track is still available, e.g. the track may
4034 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004035 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004036 }
4037 } else {
nisseede5da42017-01-12 05:15:36 -08004038 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004039 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004040 if (receiver) {
4041 observer_->OnRemoveTrack(receiver);
4042 }
deadbeefab9b2d12015-10-14 11:33:11 -07004043}
4044
4045void PeerConnection::UpdateEndedRemoteMediaStreams() {
4046 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4047 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4048 MediaStreamInterface* stream = remote_streams_->at(i);
4049 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4050 streams_to_remove.push_back(stream);
4051 }
4052 }
4053
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004054 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004055 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004056 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004057 }
4058}
4059
Steve Anton4171afb2017-11-20 10:20:22 -08004060void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004061 const std::vector<cricket::StreamParams>& streams,
4062 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004063 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004064
Seth Hampson845e8782018-03-02 11:34:10 -08004065 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004066 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004067 for (auto sender_it = current_senders->begin();
4068 sender_it != current_senders->end();
4069 /* incremented manually */) {
4070 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004071 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004072 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4073 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004074 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004075 OnLocalSenderRemoved(info, media_type);
4076 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004077 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004078 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004079 }
4080 }
4081
Steve Anton4171afb2017-11-20 10:20:22 -08004082 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004083 for (const cricket::StreamParams& params : streams) {
4084 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004085 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004086 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004087 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004088 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004089 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08004090 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004091 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004092 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004093 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004094 }
4095 }
4096}
4097
Steve Anton4171afb2017-11-20 10:20:22 -08004098void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4099 cricket::MediaType media_type) {
4100 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004101 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004102 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4103 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004104 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004105 return;
4106 }
4107
deadbeeffac06552015-11-25 11:26:01 -08004108 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004110 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004111 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004112 }
deadbeeffac06552015-11-25 11:26:01 -08004113
Seth Hampson845e8782018-03-02 11:34:10 -08004114 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004115 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004116}
4117
Steve Anton4171afb2017-11-20 10:20:22 -08004118void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4119 cricket::MediaType media_type) {
4120 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004121 if (!sender) {
4122 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004123 // SessionDescriptions has been renegotiated.
4124 return;
4125 }
deadbeeffac06552015-11-25 11:26:01 -08004126
4127 // A sender has been removed from the SessionDescription but it's still
4128 // associated with the PeerConnection. This only occurs if the SDP doesn't
4129 // match with the calls to CreateSender, AddStream and RemoveStream.
4130 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004131 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004132 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004133 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004134 }
deadbeeffac06552015-11-25 11:26:01 -08004135
Steve Anton4171afb2017-11-20 10:20:22 -08004136 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004137}
4138
4139void PeerConnection::UpdateLocalRtpDataChannels(
4140 const cricket::StreamParamsVec& streams) {
4141 std::vector<std::string> existing_channels;
4142
4143 // Find new and active data channels.
4144 for (const cricket::StreamParams& params : streams) {
4145 // |it->sync_label| is actually the data channel label. The reason is that
4146 // we use the same naming of data channels as we do for
4147 // MediaStreams and Tracks.
4148 // For MediaStreams, the sync_label is the MediaStream label and the
4149 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004150 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004151 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004152 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004153 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004154 continue;
4155 }
4156 // Set the SSRC the data channel should use for sending.
4157 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4158 existing_channels.push_back(data_channel_it->first);
4159 }
4160
4161 UpdateClosingRtpDataChannels(existing_channels, true);
4162}
4163
4164void PeerConnection::UpdateRemoteRtpDataChannels(
4165 const cricket::StreamParamsVec& streams) {
4166 std::vector<std::string> existing_channels;
4167
4168 // Find new and active data channels.
4169 for (const cricket::StreamParams& params : streams) {
4170 // The data channel label is either the mslabel or the SSRC if the mslabel
4171 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004172 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004173 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004174 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004175 auto data_channel_it = rtp_data_channels_.find(label);
4176 if (data_channel_it == rtp_data_channels_.end()) {
4177 // This is a new data channel.
4178 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4179 } else {
4180 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4181 }
4182 existing_channels.push_back(label);
4183 }
4184
4185 UpdateClosingRtpDataChannels(existing_channels, false);
4186}
4187
4188void PeerConnection::UpdateClosingRtpDataChannels(
4189 const std::vector<std::string>& active_channels,
4190 bool is_local_update) {
4191 auto it = rtp_data_channels_.begin();
4192 while (it != rtp_data_channels_.end()) {
4193 DataChannel* data_channel = it->second;
4194 if (std::find(active_channels.begin(), active_channels.end(),
4195 data_channel->label()) != active_channels.end()) {
4196 ++it;
4197 continue;
4198 }
4199
4200 if (is_local_update) {
4201 data_channel->SetSendSsrc(0);
4202 } else {
4203 data_channel->RemotePeerRequestClose();
4204 }
4205
4206 if (data_channel->state() == DataChannel::kClosed) {
4207 rtp_data_channels_.erase(it);
4208 it = rtp_data_channels_.begin();
4209 } else {
4210 ++it;
4211 }
4212 }
4213}
4214
4215void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4216 uint32_t remote_ssrc) {
4217 rtc::scoped_refptr<DataChannel> channel(
4218 InternalCreateDataChannel(label, nullptr));
4219 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004220 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004221 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004222 return;
4223 }
4224 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004225 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4226 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004227 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004228}
4229
4230rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4231 const std::string& label,
4232 const InternalDataChannelInit* config) {
4233 if (IsClosed()) {
4234 return nullptr;
4235 }
Steve Anton75737c02017-11-06 10:37:17 -08004236 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004237 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004238 << "InternalCreateDataChannel: Data is not supported in this call.";
4239 return nullptr;
4240 }
4241 InternalDataChannelInit new_config =
4242 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004243 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004244 if (new_config.id < 0) {
4245 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004246 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004247 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004248 RTC_LOG(LS_ERROR)
4249 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004250 return nullptr;
4251 }
4252 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004253 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004254 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004255 return nullptr;
4256 }
4257 }
4258
Steve Anton75737c02017-11-06 10:37:17 -08004259 rtc::scoped_refptr<DataChannel> channel(
4260 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004261 if (!channel) {
4262 sid_allocator_.ReleaseSid(new_config.id);
4263 return nullptr;
4264 }
4265
4266 if (channel->data_channel_type() == cricket::DCT_RTP) {
4267 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004268 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4269 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004270 return nullptr;
4271 }
4272 rtp_data_channels_[channel->label()] = channel;
4273 } else {
4274 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4275 sctp_data_channels_.push_back(channel);
4276 channel->SignalClosed.connect(this,
4277 &PeerConnection::OnSctpDataChannelClosed);
4278 }
4279
Steve Anton2d8609c2018-01-23 16:38:46 -08004280 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004281 return channel;
4282}
4283
4284bool PeerConnection::HasDataChannels() const {
4285 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4286}
4287
4288void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4289 for (const auto& channel : sctp_data_channels_) {
4290 if (channel->id() < 0) {
4291 int sid;
4292 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004293 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004294 continue;
4295 }
4296 channel->SetSctpSid(sid);
4297 }
4298 }
4299}
4300
4301void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004302 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004303 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4304 ++it) {
4305 if (it->get() == channel) {
4306 if (channel->id() >= 0) {
4307 sid_allocator_.ReleaseSid(channel->id());
4308 }
deadbeefbd292462015-12-14 18:15:29 -08004309 // Since this method is triggered by a signal from the DataChannel,
4310 // we can't free it directly here; we need to free it asynchronously.
4311 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004312 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004313 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4314 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004315 return;
4316 }
4317 }
4318}
4319
deadbeefab9b2d12015-10-14 11:33:11 -07004320void PeerConnection::OnDataChannelDestroyed() {
4321 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4322 // DataChannel may callback to us and try to modify the list.
4323 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4324 temp_rtp_dcs.swap(rtp_data_channels_);
4325 for (const auto& kv : temp_rtp_dcs) {
4326 kv.second->OnTransportChannelDestroyed();
4327 }
4328
4329 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4330 temp_sctp_dcs.swap(sctp_data_channels_);
4331 for (const auto& channel : temp_sctp_dcs) {
4332 channel->OnTransportChannelDestroyed();
4333 }
4334}
4335
4336void PeerConnection::OnDataChannelOpenMessage(
4337 const std::string& label,
4338 const InternalDataChannelInit& config) {
4339 rtc::scoped_refptr<DataChannel> channel(
4340 InternalCreateDataChannel(label, &config));
4341 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004342 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004343 return;
4344 }
4345
deadbeefa601f5c2016-06-06 14:27:39 -07004346 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4347 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004348 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004349}
4350
Steve Anton4171afb2017-11-20 10:20:22 -08004351rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4352PeerConnection::GetAudioTransceiver() const {
4353 // This method only works with Plan B SDP, where there is a single
4354 // audio/video transceiver.
4355 RTC_DCHECK(!IsUnifiedPlan());
4356 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004357 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004358 return transceiver;
4359 }
4360 }
4361 RTC_NOTREACHED();
4362 return nullptr;
4363}
4364
4365rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4366PeerConnection::GetVideoTransceiver() const {
4367 // This method only works with Plan B SDP, where there is a single
4368 // audio/video transceiver.
4369 RTC_DCHECK(!IsUnifiedPlan());
4370 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004371 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004372 return transceiver;
4373 }
4374 }
4375 RTC_NOTREACHED();
4376 return nullptr;
4377}
4378
4379// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4380// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004381bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004382 switch (type) {
4383 case cricket::MEDIA_TYPE_AUDIO:
4384 return !GetAudioTransceiver()->internal()->senders().empty();
4385 case cricket::MEDIA_TYPE_VIDEO:
4386 return !GetVideoTransceiver()->internal()->senders().empty();
4387 case cricket::MEDIA_TYPE_DATA:
4388 return false;
4389 }
4390 RTC_NOTREACHED();
4391 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004392}
4393
Steve Anton4171afb2017-11-20 10:20:22 -08004394rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4395PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4396 for (auto transceiver : transceivers_) {
4397 for (auto sender : transceiver->internal()->senders()) {
4398 if (sender->track() == track) {
4399 return sender;
4400 }
4401 }
4402 }
4403 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004404}
4405
Steve Anton4171afb2017-11-20 10:20:22 -08004406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4407PeerConnection::FindSenderById(const std::string& sender_id) const {
4408 for (auto transceiver : transceivers_) {
4409 for (auto sender : transceiver->internal()->senders()) {
4410 if (sender->id() == sender_id) {
4411 return sender;
4412 }
4413 }
4414 }
4415 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004416}
4417
Steve Anton4171afb2017-11-20 10:20:22 -08004418rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4419PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4420 for (auto transceiver : transceivers_) {
4421 for (auto receiver : transceiver->internal()->receivers()) {
4422 if (receiver->id() == receiver_id) {
4423 return receiver;
4424 }
4425 }
4426 }
4427 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004428}
4429
Steve Anton4171afb2017-11-20 10:20:22 -08004430std::vector<PeerConnection::RtpSenderInfo>*
4431PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4432 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4433 media_type == cricket::MEDIA_TYPE_VIDEO);
4434 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4435 ? &remote_audio_sender_infos_
4436 : &remote_video_sender_infos_;
4437}
4438
4439std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004440 cricket::MediaType media_type) {
4441 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4442 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004443 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4444 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004445}
4446
Steve Anton4171afb2017-11-20 10:20:22 -08004447const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4448 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Seth Hampson845e8782018-03-02 11:34:10 -08004449 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004450 const std::string sender_id) const {
4451 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson845e8782018-03-02 11:34:10 -08004452 if (sender_info.stream_id == stream_id &&
Steve Anton4171afb2017-11-20 10:20:22 -08004453 sender_info.sender_id == sender_id) {
4454 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004455 }
4456 }
4457 return nullptr;
4458}
4459
4460DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4461 for (const auto& channel : sctp_data_channels_) {
4462 if (channel->id() == sid) {
4463 return channel;
4464 }
4465 }
4466 return nullptr;
4467}
4468
deadbeef91dd5672016-05-18 16:55:30 -07004469bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004470 const RTCConfiguration& configuration) {
4471 cricket::ServerAddresses stun_servers;
4472 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004473 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4474 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004475 return false;
4476 }
4477
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004478 port_allocator_->Initialize();
4479
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004480 // To handle both internal and externally created port allocator, we will
4481 // enable BUNDLE here.
4482 int portallocator_flags = port_allocator_->flags();
4483 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004484 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4485 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004486 // If the disable-IPv6 flag was specified, we'll not override it
4487 // by experiment.
4488 if (configuration.disable_ipv6) {
4489 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004490 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4491 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004492 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4493 }
4494
zhihuangb09b3f92017-03-07 14:40:51 -08004495 if (configuration.disable_ipv6_on_wifi) {
4496 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004497 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004498 }
4499
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004500 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4501 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004502 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004503 }
4504
honghaiz60347052016-05-31 18:29:12 -07004505 if (configuration.candidate_network_policy ==
4506 kCandidateNetworkPolicyLowCost) {
4507 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004508 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004509 }
4510
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004511 if (configuration.disable_link_local_networks) {
4512 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4513 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4514 }
4515
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004516 port_allocator_->set_flags(portallocator_flags);
4517 // No step delay is used while allocating ports.
4518 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4519 port_allocator_->set_candidate_filter(
4520 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004521 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004522
4523 // Call this last since it may create pooled allocator sessions using the
4524 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004525 port_allocator_->SetConfiguration(
4526 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4527 configuration.prune_turn_ports, configuration.turn_customizer,
4528 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004529 return true;
4530}
4531
deadbeef91dd5672016-05-18 16:55:30 -07004532bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004533 const cricket::ServerAddresses& stun_servers,
4534 const std::vector<cricket::RelayServerConfig>& turn_servers,
4535 IceTransportsType type,
4536 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004537 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004538 webrtc::TurnCustomizer* turn_customizer,
4539 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004540 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004541 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004542 // Call this last since it may create pooled allocator sessions using the
4543 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004544 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004545 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004546 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004547}
4548
Steve Antonba818672017-11-06 10:21:57 -08004549cricket::ChannelManager* PeerConnection::channel_manager() const {
4550 return factory_->channel_manager();
4551}
4552
4553MetricsObserverInterface* PeerConnection::metrics_observer() const {
4554 return uma_observer_;
4555}
4556
Elad Alon99c3fe52017-10-13 16:29:40 +02004557bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004558 std::unique_ptr<RtcEventLogOutput> output,
4559 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004560 if (!event_log_) {
4561 return false;
4562 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004563 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004564}
4565
4566void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004567 if (event_log_) {
4568 event_log_->StopLogging();
4569 }
ivoc14d5dbe2016-07-04 07:06:55 -07004570}
nisseeaabdf62017-05-05 02:23:02 -07004571
Steve Anton75737c02017-11-06 10:37:17 -08004572cricket::BaseChannel* PeerConnection::GetChannel(
4573 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004574 for (auto transceiver : transceivers_) {
4575 cricket::BaseChannel* channel = transceiver->internal()->channel();
4576 if (channel && channel->content_name() == content_name) {
4577 return channel;
4578 }
Steve Anton75737c02017-11-06 10:37:17 -08004579 }
4580 if (rtp_data_channel() &&
4581 rtp_data_channel()->content_name() == content_name) {
4582 return rtp_data_channel();
4583 }
4584 return nullptr;
4585}
4586
4587bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4588 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004589 RTC_LOG(LS_INFO)
4590 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004591 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004592 return false;
4593 }
4594 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004595 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004596 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004597 return false;
4598 }
4599
4600 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4601}
4602
4603bool PeerConnection::GetSslRole(const std::string& content_name,
4604 rtc::SSLRole* role) {
4605 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004606 RTC_LOG(LS_INFO)
4607 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004608 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004609 return false;
4610 }
4611
4612 return transport_controller_->GetSslRole(GetTransportName(content_name),
4613 role);
4614}
4615
Steve Antonf8470812017-12-04 10:46:21 -08004616void PeerConnection::SetSessionError(SessionError error,
4617 const std::string& error_desc) {
4618 RTC_DCHECK_RUN_ON(signaling_thread());
4619 if (error != session_error_) {
4620 session_error_ = error;
4621 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004622 }
4623}
4624
Steve Anton3828c062017-12-06 10:34:51 -08004625RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004626 cricket::ContentSource source) {
4627 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004628
4629 // If there's already a pending error then no state transition should happen.
4630 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004631 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004632
4633 // If this is an answer then we know whether to BUNDLE or not. If both the
4634 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004635 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004636 const cricket::ContentGroup* local_bundle =
4637 local_description()->description()->GetGroupByName(
4638 cricket::GROUP_TYPE_BUNDLE);
4639 const cricket::ContentGroup* remote_bundle =
4640 remote_description()->description()->GetGroupByName(
4641 cricket::GROUP_TYPE_BUNDLE);
4642 if (local_bundle && remote_bundle) {
4643 // The answerer decides the transport to bundle on.
4644 const cricket::ContentGroup* answer_bundle =
4645 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4646 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4648 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004649 }
4650 }
Steve Anton75737c02017-11-06 10:37:17 -08004651 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004652
4653 // Only push down the transport description after potentially enabling BUNDLE;
4654 // we don't want to push down a description on a transport about to be
4655 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004656 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004657 if (!error.ok()) {
4658 return error;
4659 }
4660
4661 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004662 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004663 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004664 }
4665
4666 // Update the signaling state according to the specified state machine (see
4667 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004668 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004669 ChangeSignalingState(source == cricket::CS_LOCAL
4670 ? PeerConnectionInterface::kHaveLocalOffer
4671 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004672 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004673 ChangeSignalingState(source == cricket::CS_LOCAL
4674 ? PeerConnectionInterface::kHaveLocalPrAnswer
4675 : PeerConnectionInterface::kHaveRemotePrAnswer);
4676 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004677 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004678 ChangeSignalingState(PeerConnectionInterface::kStable);
4679 }
4680
4681 // Update internal objects according to the session description's media
4682 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004683 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004684 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004685 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004686 }
4687
Steve Anton8a006912017-12-04 15:25:56 -08004688 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004689}
4690
Steve Anton8a006912017-12-04 15:25:56 -08004691RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004692 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004693 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004694 const SessionDescriptionInterface* sdesc =
4695 (source == cricket::CS_LOCAL ? local_description()
4696 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004697 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004698
4699 // Push down the new SDP media section for each audio/video transceiver.
4700 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004701 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004702 FindMediaSectionForTransceiver(transceiver, sdesc);
4703 cricket::BaseChannel* channel = transceiver->internal()->channel();
4704 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004705 continue;
4706 }
4707 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004708 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004709 if (!content_desc) {
4710 continue;
4711 }
4712 std::string error;
4713 bool success =
4714 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004715 ? channel->SetLocalContent(content_desc, type, &error)
4716 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004717 if (!success) {
4718 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4719 }
4720 }
4721
4722 // If using the RtpDataChannel, push down the new SDP section for it too.
4723 if (rtp_data_channel_) {
4724 const ContentInfo* data_content =
4725 cricket::GetFirstDataContent(sdesc->description());
4726 if (data_content && !data_content->rejected) {
4727 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004728 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004729 if (data_desc) {
4730 std::string error;
4731 bool success =
4732 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004733 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4734 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004735 &error);
4736 if (!success) {
4737 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4738 std::move(error));
4739 }
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
4741 }
4742 }
Steve Antoned10bd92017-12-05 10:52:59 -08004743
Steve Anton75737c02017-11-06 10:37:17 -08004744 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4745 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4746 if (sctp_transport_ && local_description() && remote_description() &&
4747 cricket::GetFirstDataContent(local_description()->description()) &&
4748 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004749 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004750 RTC_FROM_HERE,
4751 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004752 if (!success) {
4753 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4754 "Failed to push down SCTP parameters.");
4755 }
Steve Anton75737c02017-11-06 10:37:17 -08004756 }
Steve Antoned10bd92017-12-05 10:52:59 -08004757
Steve Anton8a006912017-12-04 15:25:56 -08004758 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004759}
4760
4761bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4762 RTC_DCHECK(network_thread()->IsCurrent());
4763 RTC_DCHECK(local_description());
4764 RTC_DCHECK(remote_description());
4765 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4766 // When we support "max-message-size", that would also be pushed down here.
4767 return sctp_transport_->Start(
4768 GetSctpPort(local_description()->description()),
4769 GetSctpPort(remote_description()->description()));
4770}
4771
Steve Anton8a006912017-12-04 15:25:56 -08004772RTCError PeerConnection::PushdownTransportDescription(
4773 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004774 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004775 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004776
Steve Anton8a006912017-12-04 15:25:56 -08004777 const SessionDescriptionInterface* sdesc =
4778 (source == cricket::CS_LOCAL ? local_description()
4779 : remote_description());
4780 RTC_DCHECK(sdesc);
4781 for (const cricket::TransportInfo& tinfo :
4782 sdesc->description()->transport_infos()) {
4783 std::string error;
4784 bool success;
4785 if (source == cricket::CS_LOCAL) {
4786 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004787 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004788 } else {
4789 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004790 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004791 }
4792 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004793 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4794 "Failed to push down transport description for " +
4795 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004796 }
4797 }
4798
Steve Anton8a006912017-12-04 15:25:56 -08004799 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004800}
4801
4802bool PeerConnection::GetTransportDescription(
4803 const SessionDescription* description,
4804 const std::string& content_name,
4805 cricket::TransportDescription* tdesc) {
4806 if (!description || !tdesc) {
4807 return false;
4808 }
4809 const TransportInfo* transport_info =
4810 description->GetTransportInfoByName(content_name);
4811 if (!transport_info) {
4812 return false;
4813 }
4814 *tdesc = transport_info->description;
4815 return true;
4816}
4817
4818bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4819 const std::string* first_content_name = bundle.FirstContentName();
4820 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004821 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004822 return false;
4823 }
4824 const std::string& transport_name = *first_content_name;
4825
4826 auto maybe_set_transport = [this, bundle,
4827 transport_name](cricket::BaseChannel* ch) {
4828 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004829 return;
Steve Anton75737c02017-11-06 10:37:17 -08004830 }
4831
4832 std::string old_transport_name = ch->transport_name();
4833 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004834 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4835 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004836 return;
Steve Anton75737c02017-11-06 10:37:17 -08004837 }
4838
4839 cricket::DtlsTransportInternal* rtp_dtls_transport =
4840 transport_controller_->CreateDtlsTransport(
4841 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4842 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4843 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4844 if (need_rtcp) {
4845 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4846 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4847 }
4848
4849 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004850 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4851 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004852 transport_controller_->DestroyDtlsTransport(
4853 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4854 // If the channel needs rtcp, it means that the channel used to have a
4855 // rtcp transport which needs to be deleted now.
4856 if (need_rtcp) {
4857 transport_controller_->DestroyDtlsTransport(
4858 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4859 }
Steve Anton75737c02017-11-06 10:37:17 -08004860 };
4861
Steve Antoned10bd92017-12-05 10:52:59 -08004862 for (auto transceiver : transceivers_) {
4863 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004864 }
Steve Antoned10bd92017-12-05 10:52:59 -08004865 maybe_set_transport(rtp_data_channel_);
4866
Steve Anton75737c02017-11-06 10:37:17 -08004867 // For SCTP, transport creation/deletion happens here instead of in the
4868 // object itself.
4869 if (sctp_transport_) {
4870 RTC_DCHECK(sctp_transport_name_);
4871 RTC_DCHECK(sctp_content_name_);
4872 if (transport_name != *sctp_transport_name_ &&
4873 bundle.HasContentName(*sctp_content_name_)) {
4874 network_thread()->Invoke<void>(
4875 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4876 transport_name));
4877 }
4878 }
4879
4880 return true;
4881}
4882
Steve Anton75737c02017-11-06 10:37:17 -08004883cricket::IceConfig PeerConnection::ParseIceConfig(
4884 const PeerConnectionInterface::RTCConfiguration& config) const {
4885 cricket::ContinualGatheringPolicy gathering_policy;
4886 // TODO(honghaiz): Add the third continual gathering policy in
4887 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4888 switch (config.continual_gathering_policy) {
4889 case PeerConnectionInterface::GATHER_ONCE:
4890 gathering_policy = cricket::GATHER_ONCE;
4891 break;
4892 case PeerConnectionInterface::GATHER_CONTINUALLY:
4893 gathering_policy = cricket::GATHER_CONTINUALLY;
4894 break;
4895 default:
4896 RTC_NOTREACHED();
4897 gathering_policy = cricket::GATHER_ONCE;
4898 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004899
Steve Anton75737c02017-11-06 10:37:17 -08004900 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004901 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4902 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004903 ice_config.prioritize_most_likely_candidate_pairs =
4904 config.prioritize_most_likely_ice_candidate_pairs;
4905 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004906 RTCConfigurationToIceConfigOptionalInt(
4907 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004908 ice_config.continual_gathering_policy = gathering_policy;
4909 ice_config.presume_writable_when_fully_relayed =
4910 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004911 ice_config.ice_check_interval_strong_connectivity =
4912 config.ice_check_interval_strong_connectivity;
4913 ice_config.ice_check_interval_weak_connectivity =
4914 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004915 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004916 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004917 ice_config.regather_all_networks_interval_range =
4918 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004919 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004920 return ice_config;
4921}
4922
Steve Anton75737c02017-11-06 10:37:17 -08004923bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4924 std::string* track_id) {
4925 if (!local_description()) {
4926 return false;
4927 }
4928 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4929 track_id);
4930}
4931
4932bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4933 std::string* track_id) {
4934 if (!remote_description()) {
4935 return false;
4936 }
4937 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4938 track_id);
4939}
4940
4941bool PeerConnection::SendData(const cricket::SendDataParams& params,
4942 const rtc::CopyOnWriteBuffer& payload,
4943 cricket::SendDataResult* result) {
4944 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004945 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004946 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004947 return false;
4948 }
4949 return rtp_data_channel_
4950 ? rtp_data_channel_->SendData(params, payload, result)
4951 : network_thread()->Invoke<bool>(
4952 RTC_FROM_HERE,
4953 Bind(&cricket::SctpTransportInternal::SendData,
4954 sctp_transport_.get(), params, payload, result));
4955}
4956
4957bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4958 if (!rtp_data_channel_ && !sctp_transport_) {
4959 // Don't log an error here, because DataChannels are expected to call
4960 // ConnectDataChannel in this state. It's the only way to initially tell
4961 // whether or not the underlying transport is ready.
4962 return false;
4963 }
4964 if (rtp_data_channel_) {
4965 rtp_data_channel_->SignalReadyToSendData.connect(
4966 webrtc_data_channel, &DataChannel::OnChannelReady);
4967 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4968 &DataChannel::OnDataReceived);
4969 } else {
4970 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4971 &DataChannel::OnChannelReady);
4972 SignalSctpDataReceived.connect(webrtc_data_channel,
4973 &DataChannel::OnDataReceived);
4974 SignalSctpStreamClosedRemotely.connect(
4975 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4976 }
4977 return true;
4978}
4979
4980void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4981 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004982 RTC_LOG(LS_ERROR)
4983 << "DisconnectDataChannel called when rtp_data_channel_ and "
4984 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004985 return;
4986 }
4987 if (rtp_data_channel_) {
4988 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4989 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4990 } else {
4991 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4992 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4993 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4994 }
4995}
4996
4997void PeerConnection::AddSctpDataStream(int sid) {
4998 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_ERROR)
5000 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005001 return;
5002 }
5003 network_thread()->Invoke<void>(
5004 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5005 sctp_transport_.get(), sid));
5006}
5007
5008void PeerConnection::RemoveSctpDataStream(int sid) {
5009 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005010 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005011 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005012 return;
5013 }
5014 network_thread()->Invoke<void>(
5015 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5016 sctp_transport_.get(), sid));
5017}
5018
5019bool PeerConnection::ReadyToSendData() const {
5020 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5021 sctp_ready_to_send_data_;
5022}
5023
Qingsi Wang72a43a12018-02-20 16:03:18 -08005024cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5025 cricket::CandidateStatsList candidate_states_list;
5026 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5027 return candidate_states_list;
5028}
5029
Steve Anton5dfde182018-02-06 10:34:40 -08005030std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5031 const {
5032 std::map<std::string, std::string> transport_names_by_mid;
5033 for (auto transceiver : transceivers_) {
5034 cricket::BaseChannel* channel = transceiver->internal()->channel();
5035 if (channel) {
5036 transport_names_by_mid[channel->content_name()] =
5037 channel->transport_name();
5038 }
Steve Anton75737c02017-11-06 10:37:17 -08005039 }
Steve Anton5dfde182018-02-06 10:34:40 -08005040 if (rtp_data_channel_) {
5041 transport_names_by_mid[rtp_data_channel_->content_name()] =
5042 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005043 }
5044 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005045 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005046 }
Steve Anton5dfde182018-02-06 10:34:40 -08005047 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005048}
5049
Steve Anton5dfde182018-02-06 10:34:40 -08005050std::map<std::string, cricket::TransportStats>
5051PeerConnection::GetTransportStatsByNames(
5052 const std::set<std::string>& transport_names) {
5053 if (!network_thread()->IsCurrent()) {
5054 return network_thread()
5055 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5056 RTC_FROM_HERE,
5057 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005058 }
Steve Anton5dfde182018-02-06 10:34:40 -08005059 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5060 for (const std::string& transport_name : transport_names) {
5061 cricket::TransportStats transport_stats;
5062 bool success =
5063 transport_controller_->GetStats(transport_name, &transport_stats);
5064 if (success) {
5065 transport_stats_by_name[transport_name] = std::move(transport_stats);
5066 } else {
5067 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5068 << transport_name;
5069 }
5070 }
5071 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005072}
5073
5074bool PeerConnection::GetLocalCertificate(
5075 const std::string& transport_name,
5076 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5077 return transport_controller_->GetLocalCertificate(transport_name,
5078 certificate);
5079}
5080
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005081std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005082 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005083 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005084}
5085
5086cricket::DataChannelType PeerConnection::data_channel_type() const {
5087 return data_channel_type_;
5088}
5089
5090bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5091 return pending_ice_restarts_.find(content_name) !=
5092 pending_ice_restarts_.end();
5093}
5094
Steve Anton75737c02017-11-06 10:37:17 -08005095bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5096 return transport_controller_->NeedsIceRestart(content_name);
5097}
5098
5099void PeerConnection::OnCertificateReady(
5100 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5101 transport_controller_->SetLocalCertificate(certificate);
5102}
5103
5104void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005105 SetSessionError(SessionError::kTransport,
5106 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005107}
5108
5109void PeerConnection::OnTransportControllerConnectionState(
5110 cricket::IceConnectionState state) {
5111 switch (state) {
5112 case cricket::kIceConnectionConnecting:
5113 // If the current state is Connected or Completed, then there were
5114 // writable channels but now there are not, so the next state must
5115 // be Disconnected.
5116 // kIceConnectionConnecting is currently used as the default,
5117 // un-connected state by the TransportController, so its only use is
5118 // detecting disconnections.
5119 if (ice_connection_state_ ==
5120 PeerConnectionInterface::kIceConnectionConnected ||
5121 ice_connection_state_ ==
5122 PeerConnectionInterface::kIceConnectionCompleted) {
5123 SetIceConnectionState(
5124 PeerConnectionInterface::kIceConnectionDisconnected);
5125 }
5126 break;
5127 case cricket::kIceConnectionFailed:
5128 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5129 break;
5130 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005133 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5134 break;
5135 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005136 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005137 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005138 if (ice_connection_state_ !=
5139 PeerConnectionInterface::kIceConnectionConnected) {
5140 // If jumping directly from "checking" to "connected",
5141 // signal "connected" first.
5142 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5143 }
5144 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5145 if (metrics_observer()) {
5146 ReportTransportStats();
5147 }
5148 break;
5149 default:
5150 RTC_NOTREACHED();
5151 }
5152}
5153
5154void PeerConnection::OnTransportControllerCandidatesGathered(
5155 const std::string& transport_name,
5156 const cricket::Candidates& candidates) {
5157 RTC_DCHECK(signaling_thread()->IsCurrent());
5158 int sdp_mline_index;
5159 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_ERROR)
5161 << "OnTransportControllerCandidatesGathered: content name "
5162 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005163 return;
5164 }
5165
5166 for (cricket::Candidates::const_iterator citer = candidates.begin();
5167 citer != candidates.end(); ++citer) {
5168 // Use transport_name as the candidate media id.
5169 std::unique_ptr<JsepIceCandidate> candidate(
5170 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5171 if (local_description()) {
5172 mutable_local_description()->AddCandidate(candidate.get());
5173 }
5174 OnIceCandidate(std::move(candidate));
5175 }
5176}
5177
5178void PeerConnection::OnTransportControllerCandidatesRemoved(
5179 const std::vector<cricket::Candidate>& candidates) {
5180 RTC_DCHECK(signaling_thread()->IsCurrent());
5181 // Sanity check.
5182 for (const cricket::Candidate& candidate : candidates) {
5183 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005184 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005185 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005187 return;
5188 }
5189 }
5190
5191 if (local_description()) {
5192 mutable_local_description()->RemoveCandidates(candidates);
5193 }
5194 OnIceCandidatesRemoved(candidates);
5195}
5196
5197void PeerConnection::OnTransportControllerDtlsHandshakeError(
5198 rtc::SSLHandshakeError error) {
5199 if (metrics_observer()) {
5200 metrics_observer()->IncrementEnumCounter(
5201 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5202 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5203 }
5204}
5205
Steve Antoned10bd92017-12-05 10:52:59 -08005206void PeerConnection::EnableSending() {
5207 for (auto transceiver : transceivers_) {
5208 cricket::BaseChannel* channel = transceiver->internal()->channel();
5209 if (channel && !channel->enabled()) {
5210 channel->Enable(true);
5211 }
Steve Anton75737c02017-11-06 10:37:17 -08005212 }
5213
Steve Anton4171afb2017-11-20 10:20:22 -08005214 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005215 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005216 }
Steve Anton75737c02017-11-06 10:37:17 -08005217}
5218
5219// Returns the media index for a local ice candidate given the content name.
5220bool PeerConnection::GetLocalCandidateMediaIndex(
5221 const std::string& content_name,
5222 int* sdp_mline_index) {
5223 if (!local_description() || !sdp_mline_index) {
5224 return false;
5225 }
5226
5227 bool content_found = false;
5228 const ContentInfos& contents = local_description()->description()->contents();
5229 for (size_t index = 0; index < contents.size(); ++index) {
5230 if (contents[index].name == content_name) {
5231 *sdp_mline_index = static_cast<int>(index);
5232 content_found = true;
5233 break;
5234 }
5235 }
5236 return content_found;
5237}
5238
5239bool PeerConnection::UseCandidatesInSessionDescription(
5240 const SessionDescriptionInterface* remote_desc) {
5241 if (!remote_desc) {
5242 return true;
5243 }
5244 bool ret = true;
5245
5246 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5247 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5248 for (size_t n = 0; n < candidates->count(); ++n) {
5249 const IceCandidateInterface* candidate = candidates->at(n);
5250 bool valid = false;
5251 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5252 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005253 RTC_LOG(LS_INFO)
5254 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005255 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005256 }
5257 continue;
5258 }
5259 ret = UseCandidate(candidate);
5260 if (!ret) {
5261 break;
5262 }
5263 }
5264 }
5265 return ret;
5266}
5267
5268bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5269 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5270 size_t remote_content_size =
5271 remote_description()->description()->contents().size();
5272 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005273 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005274 return false;
5275 }
5276
5277 cricket::ContentInfo content =
5278 remote_description()->description()->contents()[mediacontent_index];
5279 std::vector<cricket::Candidate> candidates;
5280 candidates.push_back(candidate->candidate());
5281 // Invoking BaseSession method to handle remote candidates.
5282 std::string error;
5283 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5284 &error)) {
5285 // Candidates successfully submitted for checking.
5286 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5287 ice_connection_state_ ==
5288 PeerConnectionInterface::kIceConnectionDisconnected) {
5289 // If state is New, then the session has just gotten its first remote ICE
5290 // candidates, so go to Checking.
5291 // If state is Disconnected, the session is re-using old candidates or
5292 // receiving additional ones, so go to Checking.
5293 // If state is Connected, stay Connected.
5294 // TODO(bemasc): If state is Connected, and the new candidates are for a
5295 // newly added transport, then the state actually _should_ move to
5296 // checking. Add a way to distinguish that case.
5297 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5298 }
5299 // TODO(bemasc): If state is Completed, go back to Connected.
5300 } else {
5301 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005302 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005303 }
5304 }
5305 return true;
5306}
5307
5308void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005309 // Destroy video channel first since it may have a pointer to the
5310 // voice channel.
5311 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005312 if (!video_info || video_info->rejected) {
5313 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005314 }
5315
Steve Anton6fec8802017-12-04 10:37:29 -08005316 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5317 if (!audio_info || audio_info->rejected) {
5318 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005319 }
5320
5321 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5322 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005323 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005324 }
5325}
5326
Steve Antoneda6ccd2017-12-04 10:21:55 -08005327std::string PeerConnection::GetTransportNameForMediaSection(
5328 const std::string& mid,
5329 const cricket::ContentGroup* bundle_group) const {
5330 if (!bundle_group) {
5331 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005332 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005333 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005334 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005335 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005336 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005337 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005338 if (!bundle_group->HasContentName(mid)) {
5339 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5340 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005341 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005342 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5343 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005344}
5345
Steve Antondcc3c022017-12-22 16:02:54 -08005346RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5347 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005348 const cricket::ContentGroup* bundle_group = nullptr;
5349 if (configuration_.bundle_policy ==
5350 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005351 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005352 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5354 "max-bundle configured but session description "
5355 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005356 }
5357 }
Steve Antondcc3c022017-12-22 16:02:54 -08005358 return std::move(bundle_group);
5359}
5360
5361RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5362 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5363 if (!bundle_group_or_error.ok()) {
5364 return bundle_group_or_error.MoveError();
5365 }
5366 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005367
Steve Antoneda6ccd2017-12-04 10:21:55 -08005368 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005369 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005370 if (voice && !voice->rejected &&
5371 !GetAudioTransceiver()->internal()->channel()) {
5372 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5373 voice->name,
5374 GetTransportNameForMediaSection(voice->name, bundle_group));
5375 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005376 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5377 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005378 }
5379 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5380 }
5381
Steve Antondcc3c022017-12-22 16:02:54 -08005382 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005383 if (video && !video->rejected &&
5384 !GetVideoTransceiver()->internal()->channel()) {
5385 cricket::VideoChannel* video_channel = CreateVideoChannel(
5386 video->name,
5387 GetTransportNameForMediaSection(video->name, bundle_group));
5388 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005389 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5390 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005391 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005392 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005393 }
5394
Steve Antondcc3c022017-12-22 16:02:54 -08005395 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005396 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5397 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005398 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5399 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005400 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5401 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005402 }
5403 }
5404
Steve Anton8a006912017-12-04 15:25:56 -08005405 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005406}
5407
Steve Anton4171afb2017-11-20 10:20:22 -08005408// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005409cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5410 const std::string& mid,
5411 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005412 cricket::DtlsTransportInternal* rtp_dtls_transport =
5413 transport_controller_->CreateDtlsTransport(
5414 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5415 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5416 if (configuration_.rtcp_mux_policy !=
5417 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5418 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5419 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5420 }
5421
5422 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5423 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005424 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5425 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005426 if (!voice_channel) {
5427 transport_controller_->DestroyDtlsTransport(
5428 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5429 if (rtcp_dtls_transport) {
5430 transport_controller_->DestroyDtlsTransport(
5431 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5432 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005433 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
Steve Anton75737c02017-11-06 10:37:17 -08005435 voice_channel->SignalRtcpMuxFullyActive.connect(
5436 this, &PeerConnection::DestroyRtcpTransport_n);
5437 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5438 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005439 voice_channel->SignalSentPacket.connect(this,
5440 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005441 if (uma_observer_) {
5442 voice_channel->SetMetricsObserver(uma_observer_);
5443 }
Steve Anton4171afb2017-11-20 10:20:22 -08005444
Steve Antoneda6ccd2017-12-04 10:21:55 -08005445 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005446}
5447
Steve Anton4171afb2017-11-20 10:20:22 -08005448// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005449cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5450 const std::string& mid,
5451 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005452 cricket::DtlsTransportInternal* rtp_dtls_transport =
5453 transport_controller_->CreateDtlsTransport(
5454 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5455 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5456 if (configuration_.rtcp_mux_policy !=
5457 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5458 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5459 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5460 }
5461
5462 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5463 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005464 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5465 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005466
5467 if (!video_channel) {
5468 transport_controller_->DestroyDtlsTransport(
5469 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5470 if (rtcp_dtls_transport) {
5471 transport_controller_->DestroyDtlsTransport(
5472 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5473 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005474 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005475 }
Steve Anton75737c02017-11-06 10:37:17 -08005476 video_channel->SignalRtcpMuxFullyActive.connect(
5477 this, &PeerConnection::DestroyRtcpTransport_n);
5478 video_channel->SignalDtlsSrtpSetupFailure.connect(
5479 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005480 video_channel->SignalSentPacket.connect(this,
5481 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005482 if (uma_observer_) {
5483 video_channel->SetMetricsObserver(uma_observer_);
5484 }
Steve Anton4171afb2017-11-20 10:20:22 -08005485
Steve Antoneda6ccd2017-12-04 10:21:55 -08005486 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005487}
5488
Steve Antoneda6ccd2017-12-04 10:21:55 -08005489bool PeerConnection::CreateDataChannel(const std::string& mid,
5490 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005491 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5492 if (sctp) {
5493 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005494 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005495 << "Trying to create SCTP transport, but didn't compile with "
5496 "SCTP support (HAVE_SCTP)";
5497 return false;
5498 }
5499 if (!network_thread()->Invoke<bool>(
5500 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005501 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005502 return false;
5503 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005504 for (const auto& channel : sctp_data_channels_) {
5505 channel->OnTransportChannelCreated();
5506 }
Steve Anton75737c02017-11-06 10:37:17 -08005507 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005508 cricket::DtlsTransportInternal* rtp_dtls_transport =
5509 transport_controller_->CreateDtlsTransport(
5510 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5511 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5512 if (configuration_.rtcp_mux_policy !=
5513 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5514 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5515 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5516 }
5517
5518 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5519 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005520 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005521
5522 if (!rtp_data_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 }
5529 return false;
5530 }
5531
5532 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5533 this, &PeerConnection::DestroyRtcpTransport_n);
5534 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5535 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5536 rtp_data_channel_->SignalSentPacket.connect(
5537 this, &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005538 if (uma_observer_) {
5539 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5540 }
Steve Anton75737c02017-11-06 10:37:17 -08005541 }
5542
Steve Anton75737c02017-11-06 10:37:17 -08005543 return true;
5544}
5545
5546Call::Stats PeerConnection::GetCallStats() {
5547 if (!worker_thread()->IsCurrent()) {
5548 return worker_thread()->Invoke<Call::Stats>(
5549 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5550 }
5551 if (call_) {
5552 return call_->GetStats();
5553 } else {
5554 return Call::Stats();
5555 }
5556}
5557
Steve Anton75737c02017-11-06 10:37:17 -08005558bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5559 const std::string& transport_name) {
5560 RTC_DCHECK(network_thread()->IsCurrent());
5561 RTC_DCHECK(sctp_factory_);
5562 cricket::DtlsTransportInternal* tc =
5563 transport_controller_->CreateDtlsTransport_n(
5564 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5565 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5566 RTC_DCHECK(sctp_transport_);
5567 sctp_invoker_.reset(new rtc::AsyncInvoker());
5568 sctp_transport_->SignalReadyToSendData.connect(
5569 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5570 sctp_transport_->SignalDataReceived.connect(
5571 this, &PeerConnection::OnSctpTransportDataReceived_n);
5572 sctp_transport_->SignalStreamClosedRemotely.connect(
5573 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005574 sctp_transport_name_ = transport_name;
5575 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005576 return true;
5577}
5578
5579void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5580 RTC_DCHECK(network_thread()->IsCurrent());
5581 RTC_DCHECK(sctp_transport_);
5582 RTC_DCHECK(sctp_transport_name_);
5583 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005584 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005585 cricket::DtlsTransportInternal* tc =
5586 transport_controller_->CreateDtlsTransport_n(
5587 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5588 sctp_transport_->SetTransportChannel(tc);
5589 transport_controller_->DestroyDtlsTransport_n(
5590 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5591}
5592
5593void PeerConnection::DestroySctpTransport_n() {
5594 RTC_DCHECK(network_thread()->IsCurrent());
5595 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005596 transport_controller_->DestroyDtlsTransport_n(
5597 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005598 sctp_content_name_.reset();
5599 sctp_transport_name_.reset();
5600 sctp_invoker_.reset(nullptr);
5601 sctp_ready_to_send_data_ = false;
5602}
5603
5604void PeerConnection::OnSctpTransportReadyToSendData_n() {
5605 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5606 RTC_DCHECK(network_thread()->IsCurrent());
5607 // Note: Cannot use rtc::Bind here because it will grab a reference to
5608 // PeerConnection and potentially cause PeerConnection to live longer than
5609 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5610 // be destroyed before PeerConnection is destroyed, and at that point all
5611 // pending tasks will be cleared.
5612 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5613 OnSctpTransportReadyToSendData_s(true);
5614 });
5615}
5616
5617void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5618 RTC_DCHECK(signaling_thread()->IsCurrent());
5619 sctp_ready_to_send_data_ = ready;
5620 SignalSctpReadyToSendData(ready);
5621}
5622
5623void PeerConnection::OnSctpTransportDataReceived_n(
5624 const cricket::ReceiveDataParams& params,
5625 const rtc::CopyOnWriteBuffer& payload) {
5626 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5627 RTC_DCHECK(network_thread()->IsCurrent());
5628 // Note: Cannot use rtc::Bind here because it will grab a reference to
5629 // PeerConnection and potentially cause PeerConnection to live longer than
5630 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5631 // be destroyed before PeerConnection is destroyed, and at that point all
5632 // pending tasks will be cleared.
5633 sctp_invoker_->AsyncInvoke<void>(
5634 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5635 OnSctpTransportDataReceived_s(params, payload);
5636 });
5637}
5638
5639void PeerConnection::OnSctpTransportDataReceived_s(
5640 const cricket::ReceiveDataParams& params,
5641 const rtc::CopyOnWriteBuffer& payload) {
5642 RTC_DCHECK(signaling_thread()->IsCurrent());
5643 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5644 // Received OPEN message; parse and signal that a new data channel should
5645 // be created.
5646 std::string label;
5647 InternalDataChannelInit config;
5648 config.id = params.ssrc;
5649 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005650 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5651 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005652 return;
5653 }
5654 config.open_handshake_role = InternalDataChannelInit::kAcker;
5655 OnDataChannelOpenMessage(label, config);
5656 } else {
5657 // Otherwise just forward the signal.
5658 SignalSctpDataReceived(params, payload);
5659 }
5660}
5661
5662void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5663 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5664 RTC_DCHECK(network_thread()->IsCurrent());
5665 sctp_invoker_->AsyncInvoke<void>(
5666 RTC_FROM_HERE, signaling_thread(),
5667 rtc::Bind(&sigslot::signal1<int>::operator(),
5668 &SignalSctpStreamClosedRemotely, sid));
5669}
5670
5671// Returns false if bundle is enabled and rtcp_mux is disabled.
5672bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5673 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5674 if (!bundle_enabled)
5675 return true;
5676
5677 const cricket::ContentGroup* bundle_group =
5678 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5679 RTC_DCHECK(bundle_group != NULL);
5680
5681 const cricket::ContentInfos& contents = desc->contents();
5682 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5683 citer != contents.end(); ++citer) {
5684 const cricket::ContentInfo* content = (&*citer);
5685 RTC_DCHECK(content != NULL);
5686 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005687 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005688 if (!HasRtcpMuxEnabled(content))
5689 return false;
5690 }
5691 }
5692 // RTCP-MUX is enabled in all the contents.
5693 return true;
5694}
5695
5696bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005697 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005698}
5699
Steve Anton8a006912017-12-04 15:25:56 -08005700RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005701 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005702 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005703 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005704 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
5706
5707 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005708 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005709 }
5710
Steve Anton3828c062017-12-06 10:34:51 -08005711 SdpType type = sdesc->GetType();
5712 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5713 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005714 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005715 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005716 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005717 }
5718
5719 // Verify crypto settings.
5720 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005721 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5722 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005723 RTCError crypto_error =
5724 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005725 if (!crypto_error.ok()) {
5726 return crypto_error;
5727 }
Steve Anton75737c02017-11-06 10:37:17 -08005728 }
5729
5730 // Verify ice-ufrag and ice-pwd.
5731 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5733 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005734 }
5735
5736 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005737 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5738 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005739 }
5740
5741 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5742 // m-lines that do not rtcp-mux enabled.
5743
5744 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005745 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005746 // With an answer we want to compare the new answer session description with
5747 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005748 const cricket::SessionDescription* offer_desc =
5749 (source == cricket::CS_LOCAL) ? remote_description()->description()
5750 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005751 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5752 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5753 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005754 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5755 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005758 // The re-offers should respect the order of m= sections in current
5759 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005760 // With a re-offer, either the current local or current remote descriptions
5761 // could be the most up to date, so we would like to check against both of
5762 // them if they exist. It could be the case that one of them has a 0 port
5763 // for a media section, but the other does not. This is important to check
5764 // against in the case that we are recycling an m= section.
5765 const cricket::SessionDescription* current_desc = nullptr;
5766 const cricket::SessionDescription* secondary_current_desc = nullptr;
5767 if (local_description()) {
5768 current_desc = local_description()->description();
5769 if (remote_description()) {
5770 secondary_current_desc = remote_description()->description();
5771 }
5772 } else if (remote_description()) {
5773 current_desc = remote_description()->description();
5774 }
Steve Anton75737c02017-11-06 10:37:17 -08005775 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005776 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5777 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5779 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005780 }
5781 }
5782
Steve Anton8a006912017-12-04 15:25:56 -08005783 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005784}
5785
Steve Anton3828c062017-12-06 10:34:51 -08005786bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005787 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005788 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005789 return (state == PeerConnectionInterface::kStable) ||
5790 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005791 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005792 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005793 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5794 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5795 }
5796}
5797
Steve Anton3828c062017-12-06 10:34:51 -08005798bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005799 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005800 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005801 return (state == PeerConnectionInterface::kStable) ||
5802 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005803 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005804 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005805 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5806 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5807 }
5808}
5809
Steve Antonf8470812017-12-04 10:46:21 -08005810const char* PeerConnection::SessionErrorToString(SessionError error) const {
5811 switch (error) {
5812 case SessionError::kNone:
5813 return "ERROR_NONE";
5814 case SessionError::kContent:
5815 return "ERROR_CONTENT";
5816 case SessionError::kTransport:
5817 return "ERROR_TRANSPORT";
5818 }
5819 RTC_NOTREACHED();
5820 return "";
5821}
5822
Steve Anton75737c02017-11-06 10:37:17 -08005823std::string PeerConnection::GetSessionErrorMsg() {
5824 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005825 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5826 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005827 return desc.str();
5828}
5829
Steve Anton8e20f172018-03-06 10:55:04 -08005830void PeerConnection::ReportSdpFormatReceived(
5831 const SessionDescriptionInterface& remote_offer) {
5832 if (!uma_observer_) {
5833 return;
5834 }
5835 int num_audio_mlines = 0;
5836 int num_video_mlines = 0;
5837 int num_audio_tracks = 0;
5838 int num_video_tracks = 0;
5839 for (const ContentInfo& content : remote_offer.description()->contents()) {
5840 cricket::MediaType media_type = content.media_description()->type();
5841 int num_tracks = std::max(
5842 1, static_cast<int>(content.media_description()->streams().size()));
5843 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5844 num_audio_mlines += 1;
5845 num_audio_tracks += num_tracks;
5846 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5847 num_video_mlines += 1;
5848 num_video_tracks += num_tracks;
5849 }
5850 }
5851 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5852 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5853 format = kSdpFormatReceivedComplexUnifiedPlan;
5854 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5855 format = kSdpFormatReceivedComplexPlanB;
5856 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5857 format = kSdpFormatReceivedSimple;
5858 }
5859 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5860 kSdpFormatReceivedMax);
5861}
5862
Steve Anton0ffaaa22018-02-23 10:31:30 -08005863void PeerConnection::ReportNegotiatedSdpSemantics(
5864 const SessionDescriptionInterface& answer) {
5865 if (!uma_observer_) {
5866 return;
5867 }
5868 switch (answer.description()->msid_signaling()) {
5869 case 0:
5870 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5871 kSdpSemanticNegotiatedNone,
5872 kSdpSemanticNegotiatedMax);
5873 break;
5874 case cricket::kMsidSignalingMediaSection:
5875 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5876 kSdpSemanticNegotiatedUnifiedPlan,
5877 kSdpSemanticNegotiatedMax);
5878 break;
5879 case cricket::kMsidSignalingSsrcAttribute:
5880 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5881 kSdpSemanticNegotiatedPlanB,
5882 kSdpSemanticNegotiatedMax);
5883 break;
5884 case cricket::kMsidSignalingMediaSection |
5885 cricket::kMsidSignalingSsrcAttribute:
5886 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5887 kSdpSemanticNegotiatedMixed,
5888 kSdpSemanticNegotiatedMax);
5889 break;
5890 default:
5891 RTC_NOTREACHED();
5892 }
5893}
5894
Steve Anton75737c02017-11-06 10:37:17 -08005895// We need to check the local/remote description for the Transport instead of
5896// the session, because a new Transport added during renegotiation may have
5897// them unset while the session has them set from the previous negotiation.
5898// Not doing so may trigger the auto generation of transport description and
5899// mess up DTLS identity information, ICE credential, etc.
5900bool PeerConnection::ReadyToUseRemoteCandidate(
5901 const IceCandidateInterface* candidate,
5902 const SessionDescriptionInterface* remote_desc,
5903 bool* valid) {
5904 *valid = true;
5905
5906 const SessionDescriptionInterface* current_remote_desc =
5907 remote_desc ? remote_desc : remote_description();
5908
5909 if (!current_remote_desc) {
5910 return false;
5911 }
5912
5913 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5914 size_t remote_content_size =
5915 current_remote_desc->description()->contents().size();
5916 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005917 RTC_LOG(LS_ERROR)
5918 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5919 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005920
5921 *valid = false;
5922 return false;
5923 }
5924
5925 cricket::ContentInfo content =
5926 current_remote_desc->description()->contents()[mediacontent_index];
5927
5928 const std::string transport_name = GetTransportName(content.name);
5929 if (transport_name.empty()) {
5930 return false;
5931 }
5932 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5933}
5934
5935bool PeerConnection::SrtpRequired() const {
5936 return dtls_enabled_ ||
5937 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5938}
5939
5940void PeerConnection::OnTransportControllerGatheringState(
5941 cricket::IceGatheringState state) {
5942 RTC_DCHECK(signaling_thread()->IsCurrent());
5943 if (state == cricket::kIceGatheringGathering) {
5944 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5945 } else if (state == cricket::kIceGatheringComplete) {
5946 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5947 }
5948}
5949
5950void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005951 std::map<std::string, std::set<cricket::MediaType>>
5952 media_types_by_transport_name;
5953 for (auto transceiver : transceivers_) {
5954 if (transceiver->internal()->channel()) {
5955 const std::string& transport_name =
5956 transceiver->internal()->channel()->transport_name();
5957 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005958 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005959 }
Steve Anton75737c02017-11-06 10:37:17 -08005960 }
5961 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005962 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5963 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005964 }
5965 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005966 media_types_by_transport_name[*sctp_transport_name_].insert(
5967 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005968 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005969 for (const auto& entry : media_types_by_transport_name) {
5970 const std::string& transport_name = entry.first;
5971 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005972 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005973 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005974 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005975 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005976 }
5977 }
5978}
5979// Walk through the ConnectionInfos to gather best connection usage
5980// for IPv4 and IPv6.
5981void PeerConnection::ReportBestConnectionState(
5982 const cricket::TransportStats& stats) {
5983 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005984 for (const cricket::TransportChannelStats& channel_stats :
5985 stats.channel_stats) {
5986 for (const cricket::ConnectionInfo& connection_info :
5987 channel_stats.connection_infos) {
5988 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005989 continue;
5990 }
5991
5992 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005993 const cricket::Candidate& local = connection_info.local_candidate;
5994 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005995
5996 // Increment the counter for IceCandidatePairType.
5997 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5998 (local.type() == RELAY_PORT_TYPE &&
5999 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6000 type = kEnumCounterIceCandidatePairTypeTcp;
6001 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6002 type = kEnumCounterIceCandidatePairTypeUdp;
6003 } else {
6004 RTC_CHECK(0);
6005 }
6006 metrics_observer()->IncrementEnumCounter(
6007 type, GetIceCandidatePairCounter(local, remote),
6008 kIceCandidatePairMax);
6009
6010 // Increment the counter for IP type.
6011 if (local.address().family() == AF_INET) {
6012 metrics_observer()->IncrementEnumCounter(
6013 kEnumCounterAddressFamily, kBestConnections_IPv4,
6014 kPeerConnectionAddressFamilyCounter_Max);
6015
6016 } else if (local.address().family() == AF_INET6) {
6017 metrics_observer()->IncrementEnumCounter(
6018 kEnumCounterAddressFamily, kBestConnections_IPv6,
6019 kPeerConnectionAddressFamilyCounter_Max);
6020 } else {
6021 RTC_CHECK(0);
6022 }
6023
6024 return;
6025 }
6026 }
6027}
6028
6029void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006030 const cricket::TransportStats& stats,
6031 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006032 RTC_DCHECK(metrics_observer());
6033 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6034 return;
6035 }
6036
6037 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6038 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6039 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6040 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6041 return;
6042 }
6043
Steve Antonc7b964c2018-02-01 14:39:45 -08006044 for (cricket::MediaType media_type : media_types) {
6045 PeerConnectionEnumCounterType srtp_counter_type;
6046 PeerConnectionEnumCounterType ssl_counter_type;
6047 switch (media_type) {
6048 case cricket::MEDIA_TYPE_AUDIO:
6049 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6050 ssl_counter_type = kEnumCounterAudioSslCipher;
6051 break;
6052 case cricket::MEDIA_TYPE_VIDEO:
6053 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6054 ssl_counter_type = kEnumCounterVideoSslCipher;
6055 break;
6056 case cricket::MEDIA_TYPE_DATA:
6057 srtp_counter_type = kEnumCounterDataSrtpCipher;
6058 ssl_counter_type = kEnumCounterDataSslCipher;
6059 break;
6060 default:
6061 RTC_NOTREACHED();
6062 continue;
6063 }
6064 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6065 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6066 srtp_crypto_suite);
6067 }
6068 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6069 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6070 ssl_cipher_suite);
6071 }
Steve Anton75737c02017-11-06 10:37:17 -08006072 }
6073}
6074
6075void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6076 RTC_DCHECK(worker_thread()->IsCurrent());
6077 RTC_DCHECK(call_);
6078 call_->OnSentPacket(sent_packet);
6079}
6080
6081const std::string PeerConnection::GetTransportName(
6082 const std::string& content_name) {
6083 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006084 if (channel) {
6085 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006086 }
Steve Anton6fec8802017-12-04 10:37:29 -08006087 if (sctp_transport_) {
6088 RTC_DCHECK(sctp_content_name_);
6089 RTC_DCHECK(sctp_transport_name_);
6090 if (content_name == *sctp_content_name_) {
6091 return *sctp_transport_name_;
6092 }
6093 }
6094 // Return an empty string if failed to retrieve the transport name.
6095 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006096}
6097
6098void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6099 RTC_DCHECK(network_thread()->IsCurrent());
6100 transport_controller_->DestroyDtlsTransport_n(
6101 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6102}
6103
Steve Anton6fec8802017-12-04 10:37:29 -08006104void PeerConnection::DestroyTransceiverChannel(
6105 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6106 transceiver) {
6107 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006108
Steve Anton6fec8802017-12-04 10:37:29 -08006109 cricket::BaseChannel* channel = transceiver->internal()->channel();
6110 if (channel) {
6111 transceiver->internal()->SetChannel(nullptr);
6112 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006113 }
6114}
6115
6116void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006117 if (rtp_data_channel_) {
6118 OnDataChannelDestroyed();
6119 DestroyBaseChannel(rtp_data_channel_);
6120 rtp_data_channel_ = nullptr;
6121 }
6122
6123 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6124 // grab a reference to this PeerConnection. If this is called from the
6125 // PeerConnection destructor, the RefCountedObject vtable will have already
6126 // been destroyed (since it is a subclass of PeerConnection) and using
6127 // rtc::Bind will cause "Pure virtual function called" error to appear.
6128
6129 if (sctp_transport_) {
6130 OnDataChannelDestroyed();
6131 network_thread()->Invoke<void>(RTC_FROM_HERE,
6132 [this] { DestroySctpTransport_n(); });
6133 }
6134}
6135
6136void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6137 RTC_DCHECK(channel);
6138 RTC_DCHECK(channel->rtp_dtls_transport());
6139
6140 // Need to cache these before destroying the base channel so that we do not
6141 // access uninitialized memory.
6142 const std::string transport_name =
6143 channel->rtp_dtls_transport()->transport_name();
6144 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6145
6146 switch (channel->media_type()) {
6147 case cricket::MEDIA_TYPE_AUDIO:
6148 channel_manager()->DestroyVoiceChannel(
6149 static_cast<cricket::VoiceChannel*>(channel));
6150 break;
6151 case cricket::MEDIA_TYPE_VIDEO:
6152 channel_manager()->DestroyVideoChannel(
6153 static_cast<cricket::VideoChannel*>(channel));
6154 break;
6155 case cricket::MEDIA_TYPE_DATA:
6156 channel_manager()->DestroyRtpDataChannel(
6157 static_cast<cricket::RtpDataChannel*>(channel));
6158 break;
6159 default:
6160 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6161 break;
6162 }
6163
6164 // |channel| can no longer be used.
6165
Steve Anton75737c02017-11-06 10:37:17 -08006166 transport_controller_->DestroyDtlsTransport(
6167 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6168 if (need_to_delete_rtcp) {
6169 transport_controller_->DestroyDtlsTransport(
6170 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6171 }
6172}
6173
Harald Alvestrand89061872018-01-02 14:08:34 +01006174void PeerConnection::ClearStatsCache() {
6175 if (stats_collector_) {
6176 stats_collector_->ClearCachedStatsReport();
6177 }
6178}
6179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006180} // namespace webrtc