blob: 84376ce58aa6df34d195e2d3cf9cf7ede16a8c62 [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 }
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001144 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1145 if (stream_ids.size() > 1u) {
1146 LOG_AND_RETURN_ERROR(
1147 RTCErrorType::UNSUPPORTED_OPERATION,
1148 "AddTrack with more than one stream is not currently supported.");
1149 }
Steve Antonf9381f02017-12-14 10:23:57 -08001150 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 }
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001159 // 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
1162 // 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());
1166 }
1167 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001168 auto sender_or_error =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001169 (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);
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001186 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 =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001191 FindSenderInfo(local_audio_sender_infos_,
1192 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001193 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 =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001201 FindSenderInfo(local_video_sender_infos_,
1202 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001203 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
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001373 if (init.stream_ids.size() > 1u) {
1374 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1375 "More than one stream is not yet supported.");
1376 }
1377
1378 std::vector<std::string> stream_ids = {
1379 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
1380
1381 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;
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001489 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) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001595 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001596 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001597 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001598 stats_collector_->GetStatsReport(callback);
1599}
1600
Henrik Boström1df1bf82018-03-20 13:24:20 +01001601void PeerConnection::GetStats(
1602 rtc::scoped_refptr<RtpSenderInterface> selector,
1603 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1604 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1605 RTC_DCHECK(callback);
1606 RTC_DCHECK(stats_collector_);
1607 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1608 if (selector) {
1609 for (const auto& proxy_transceiver : transceivers_) {
1610 for (const auto& proxy_sender :
1611 proxy_transceiver->internal()->senders()) {
1612 if (proxy_sender == selector) {
1613 internal_sender = proxy_sender->internal();
1614 break;
1615 }
1616 }
1617 if (internal_sender)
1618 break;
1619 }
1620 }
1621 // If there is no |internal_sender| then |selector| is either null or does not
1622 // belong to the PeerConnection (in Plan B, senders can be removed from the
1623 // PeerConnection). This means that "all the stats objects representing the
1624 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1625 // produces an empty stats report.
1626 stats_collector_->GetStatsReport(internal_sender, callback);
1627}
1628
1629void PeerConnection::GetStats(
1630 rtc::scoped_refptr<RtpReceiverInterface> selector,
1631 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1632 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1633 RTC_DCHECK(callback);
1634 RTC_DCHECK(stats_collector_);
1635 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1636 if (selector) {
1637 for (const auto& proxy_transceiver : transceivers_) {
1638 for (const auto& proxy_receiver :
1639 proxy_transceiver->internal()->receivers()) {
1640 if (proxy_receiver == selector) {
1641 internal_receiver = proxy_receiver->internal();
1642 break;
1643 }
1644 }
1645 if (internal_receiver)
1646 break;
1647 }
1648 }
1649 // If there is no |internal_receiver| then |selector| is either null or does
1650 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1651 // the PeerConnection). This means that "all the stats objects representing
1652 // the selector" is an empty set. Invoking GetStatsReport() with a null
1653 // selector produces an empty stats report.
1654 stats_collector_->GetStatsReport(internal_receiver, callback);
1655}
1656
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1658 return signaling_state_;
1659}
1660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661PeerConnectionInterface::IceConnectionState
1662PeerConnection::ice_connection_state() {
1663 return ice_connection_state_;
1664}
1665
1666PeerConnectionInterface::IceGatheringState
1667PeerConnection::ice_gathering_state() {
1668 return ice_gathering_state_;
1669}
1670
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001671rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672PeerConnection::CreateDataChannel(
1673 const std::string& label,
1674 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001675 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001676
deadbeefab9b2d12015-10-14 11:33:11 -07001677 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001678
kwibergd1fe2812016-04-27 06:47:29 -07001679 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001680 if (config) {
1681 internal_config.reset(new InternalDataChannelInit(*config));
1682 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001683 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001684 InternalCreateDataChannel(label, internal_config.get()));
1685 if (!channel.get()) {
1686 return nullptr;
1687 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001689 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1690 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001691 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001692 observer_->OnRenegotiationNeeded();
1693 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001694
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 return DataChannelProxy::Create(signaling_thread(), channel.get());
1696}
1697
1698void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1699 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001700 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001701
zhihuang1c378ed2017-08-17 14:10:50 -07001702 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1703 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1704 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1705 // compares the mandatory fields parsed with the mandatory fields added in the
1706 // |constraints| and some downstream applications might create offers with
1707 // mandatory fields which would not be parsed in the helper method. For
1708 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1709 // |constraints| as a mandatory field but it is not parsed.
1710 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001711
zhihuang1c378ed2017-08-17 14:10:50 -07001712 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001713}
1714
1715void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1716 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001717 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001718
nisse7ce109a2017-01-31 00:57:56 -08001719 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001720 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001721 return;
1722 }
deadbeefab9b2d12015-10-14 11:33:11 -07001723
Steve Anton8d3444d2017-10-20 15:30:51 -07001724 if (IsClosed()) {
1725 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001726 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001727 PostCreateSessionDescriptionFailure(
1728 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001729 return;
1730 }
1731
zhihuang1c378ed2017-08-17 14:10:50 -07001732 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001733 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001734 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001735 PostCreateSessionDescriptionFailure(
1736 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001737 return;
1738 }
1739
Steve Anton22da89f2018-01-25 13:58:07 -08001740 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1741 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1742 if (IsUnifiedPlan()) {
1743 RTCError error = HandleLegacyOfferOptions(options);
1744 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001745 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001746 return;
1747 }
1748 }
1749
zhihuang1c378ed2017-08-17 14:10:50 -07001750 cricket::MediaSessionOptions session_options;
1751 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001752 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001753}
1754
Steve Anton22da89f2018-01-25 13:58:07 -08001755RTCError PeerConnection::HandleLegacyOfferOptions(
1756 const RTCOfferAnswerOptions& options) {
1757 RTC_DCHECK(IsUnifiedPlan());
1758
1759 if (options.offer_to_receive_audio == 0) {
1760 RemoveRecvDirectionFromReceivingTransceiversOfType(
1761 cricket::MEDIA_TYPE_AUDIO);
1762 } else if (options.offer_to_receive_audio == 1) {
1763 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1764 } else if (options.offer_to_receive_audio > 1) {
1765 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1766 "offer_to_receive_audio > 1 is not supported.");
1767 }
1768
1769 if (options.offer_to_receive_video == 0) {
1770 RemoveRecvDirectionFromReceivingTransceiversOfType(
1771 cricket::MEDIA_TYPE_VIDEO);
1772 } else if (options.offer_to_receive_video == 1) {
1773 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1774 } else if (options.offer_to_receive_video > 1) {
1775 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1776 "offer_to_receive_video > 1 is not supported.");
1777 }
1778
1779 return RTCError::OK();
1780}
1781
1782void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1783 cricket::MediaType media_type) {
1784 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1785 transceiver->internal()->set_direction(
1786 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1787 }
1788}
1789
1790void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1791 cricket::MediaType media_type) {
1792 if (GetReceivingTransceiversOfType(media_type).empty()) {
1793 RtpTransceiverInit init;
1794 init.direction = RtpTransceiverDirection::kRecvOnly;
1795 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1796 }
1797}
1798
1799std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1800PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1801 std::vector<
1802 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1803 receiving_transceivers;
1804 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001805 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001806 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1807 receiving_transceivers.push_back(transceiver);
1808 }
1809 }
1810 return receiving_transceivers;
1811}
1812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813void PeerConnection::CreateAnswer(
1814 CreateSessionDescriptionObserver* observer,
1815 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001816 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001817
nisse7ce109a2017-01-31 00:57:56 -08001818 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return;
1821 }
deadbeefab9b2d12015-10-14 11:33:11 -07001822
zhihuang1c378ed2017-08-17 14:10:50 -07001823 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1824 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1825 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001826 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001828 PostCreateSessionDescriptionFailure(
1829 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001830 return;
1831 }
1832
Steve Anton8d3444d2017-10-20 15:30:51 -07001833 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001834}
1835
1836void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1837 const RTCOfferAnswerOptions& options) {
1838 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001839 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001840 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001841 return;
1842 }
1843
Steve Antondffead82018-02-06 10:31:29 -08001844 if (!(signaling_state_ == kHaveRemoteOffer ||
1845 signaling_state_ == kHaveLocalPrAnswer)) {
1846 std::string error =
1847 "PeerConnection cannot create an answer in a state other than "
1848 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001849 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001850 PostCreateSessionDescriptionFailure(
1851 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001852 return;
1853 }
1854
Steve Antondffead82018-02-06 10:31:29 -08001855 // The remote description should be set if we're in the right state.
1856 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001857
Steve Anton22da89f2018-01-25 13:58:07 -08001858 if (IsUnifiedPlan()) {
1859 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1860 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1861 "supported with Unified Plan semantics. Use the "
1862 "RtpTransceiver API instead.";
1863 }
1864 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1865 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1866 "supported with Unified Plan semantics. Use the "
1867 "RtpTransceiver API instead.";
1868 }
1869 }
1870
htaa2a49d92016-03-04 02:51:39 -08001871 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001872 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001873
Steve Antond25da372017-11-06 14:50:29 -08001874 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875}
1876
1877void PeerConnection::SetLocalDescription(
1878 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001879 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001880 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001881
Steve Anton80dd7b52018-02-16 17:08:42 -08001882 // The SetLocalDescription contract is that we take ownership of the session
1883 // description regardless of the outcome, so wrap it in a unique_ptr right
1884 // away. Ideally, SetLocalDescription's signature will be changed to take the
1885 // description as a unique_ptr argument to formalize this agreement.
1886 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1887
nisse7ce109a2017-01-31 00:57:56 -08001888 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890 return;
1891 }
Steve Anton8a006912017-12-04 15:25:56 -08001892
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001894 PostSetSessionDescriptionFailure(
1895 observer,
1896 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 return;
1898 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001899
Steve Anton80dd7b52018-02-16 17:08:42 -08001900 // If a session error has occurred the PeerConnection is in a possibly
1901 // inconsistent state so fail right away.
1902 if (session_error() != SessionError::kNone) {
1903 std::string error_message = GetSessionErrorMsg();
1904 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001905 PostSetSessionDescriptionFailure(
1906 observer,
1907 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001908 return;
1909 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001910
Steve Anton80dd7b52018-02-16 17:08:42 -08001911 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1912 if (!error.ok()) {
1913 std::string error_message = GetSetDescriptionErrorMessage(
1914 cricket::CS_LOCAL, desc->GetType(), error);
1915 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001916 PostSetSessionDescriptionFailure(
1917 observer,
1918 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001919 return;
1920 }
1921
1922 // Grab the description type before moving ownership to ApplyLocalDescription,
1923 // which may destroy it before returning.
1924 const SdpType type = desc->GetType();
1925
1926 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001927 // |desc| may be destroyed at this point.
1928
1929 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001930 // If ApplyLocalDescription fails, the PeerConnection could be in an
1931 // inconsistent state, so act conservatively here and set the session error
1932 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1933 SetSessionError(SessionError::kContent, error.message());
1934 std::string error_message =
1935 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1936 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001937 PostSetSessionDescriptionFailure(
1938 observer,
1939 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001940 return;
1941 }
Steve Anton8a006912017-12-04 15:25:56 -08001942 RTC_DCHECK(local_description());
1943
1944 PostSetSessionDescriptionSuccess(observer);
1945
1946 // According to JSEP, after setLocalDescription, changing the candidate pool
1947 // size is not allowed, and changing the set of ICE servers will not result
1948 // in new candidates being gathered.
1949 port_allocator_->FreezeCandidatePool();
1950
1951 // MaybeStartGathering needs to be called after posting
1952 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1953 // before signaling that SetLocalDescription completed.
1954 transport_controller_->MaybeStartGathering();
1955
Steve Antona3a92c22017-12-07 10:27:41 -08001956 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001957 // TODO(deadbeef): We already had to hop to the network thread for
1958 // MaybeStartGathering...
1959 network_thread()->Invoke<void>(
1960 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1961 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001962 // Make UMA notes about what was agreed to.
1963 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001964 }
1965}
1966
1967RTCError PeerConnection::ApplyLocalDescription(
1968 std::unique_ptr<SessionDescriptionInterface> desc) {
1969 RTC_DCHECK_RUN_ON(signaling_thread());
1970 RTC_DCHECK(desc);
1971
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 // Update stats here so that we have the most recent stats for tracks and
1973 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001974 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001975
1976 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001977 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001978 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001979 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001980 if (*initial_offerer_) {
1981 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1982 } else {
1983 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1984 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 }
Steve Anton8a006912017-12-04 15:25:56 -08001986
Steve Antondcc3c022017-12-22 16:02:54 -08001987 // Take a reference to the old local description since it's used below to
1988 // compare against the new local description. When setting the new local
1989 // description, grab ownership of the replaced session description in case it
1990 // is the same as |old_local_description|, to keep it alive for the duration
1991 // of the method.
1992 const SessionDescriptionInterface* old_local_description =
1993 local_description();
1994 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001995 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001996 replaced_local_description = pending_local_description_
1997 ? std::move(pending_local_description_)
1998 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001999 current_local_description_ = std::move(desc);
2000 pending_local_description_ = nullptr;
2001 current_remote_description_ = std::move(pending_remote_description_);
2002 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002003 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002004 pending_local_description_ = std::move(desc);
2005 }
2006 // The session description to apply now must be accessed by
2007 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002008 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002009
Steve Antondcc3c022017-12-22 16:02:54 -08002010 if (IsUnifiedPlan()) {
2011 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002012 cricket::CS_LOCAL, *local_description(), old_local_description,
2013 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002014 if (!error.ok()) {
2015 return error;
2016 }
Steve Antondcc3c022017-12-22 16:02:54 -08002017 for (auto transceiver : transceivers_) {
2018 const ContentInfo* content =
2019 FindMediaSectionForTransceiver(transceiver, local_description());
2020 if (!content) {
2021 continue;
2022 }
2023 const MediaContentDescription* media_desc = content->media_description();
2024 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2025 transceiver->internal()->set_current_direction(media_desc->direction());
2026 }
2027 if (content->rejected && !transceiver->stopped()) {
2028 transceiver->Stop();
2029 }
2030 }
2031 } else {
2032 // Transport and Media channels will be created only when offer is set.
2033 if (type == SdpType::kOffer) {
2034 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2035 // description is applied. Restore back to old description.
2036 RTCError error = CreateChannels(*local_description()->description());
2037 if (!error.ok()) {
2038 return error;
2039 }
2040 }
Steve Anton8a006912017-12-04 15:25:56 -08002041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 // Remove unused channels if MediaContentDescription is rejected.
2043 RemoveUnusedChannels(local_description()->description());
2044 }
Steve Anton8a006912017-12-04 15:25:56 -08002045
Steve Anton80dd7b52018-02-16 17:08:42 -08002046 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08002047 if (!error.ok()) {
2048 return error;
2049 }
Steve Antondcc3c022017-12-22 16:02:54 -08002050
Steve Anton8a006912017-12-04 15:25:56 -08002051 if (remote_description()) {
2052 // Now that we have a local description, we can push down remote candidates.
2053 UseCandidatesInSessionDescription(remote_description());
2054 }
2055
2056 pending_ice_restarts_.clear();
2057 if (session_error() != SessionError::kNone) {
2058 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2059 }
2060
deadbeefab9b2d12015-10-14 11:33:11 -07002061 // If setting the description decided our SSL role, allocate any necessary
2062 // SCTP sids.
2063 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002064 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002065 AllocateSctpSids(role);
2066 }
2067
Steve Antond3679212018-01-17 17:41:02 -08002068 if (IsUnifiedPlan()) {
2069 for (auto transceiver : transceivers_) {
2070 const ContentInfo* content =
2071 FindMediaSectionForTransceiver(transceiver, local_description());
2072 if (!content) {
2073 continue;
2074 }
2075 if (content->rejected && !transceiver->stopped()) {
2076 transceiver->Stop();
2077 }
Steve Anton74255ff2018-01-24 18:32:57 -08002078 const auto& streams = content->media_description()->streams();
2079 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002080 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002081 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002082 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002083 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002084 }
2085 }
2086 } else {
2087 // Plan B semantics.
2088
Steve Antondcc3c022017-12-22 16:02:54 -08002089 // Update state and SSRC of local MediaStreams and DataChannels based on the
2090 // local session description.
2091 const cricket::ContentInfo* audio_content =
2092 GetFirstAudioContent(local_description()->description());
2093 if (audio_content) {
2094 if (audio_content->rejected) {
2095 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2096 } else {
2097 const cricket::AudioContentDescription* audio_desc =
2098 audio_content->media_description()->as_audio();
2099 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2100 }
deadbeeffaac4972015-11-12 15:33:07 -08002101 }
deadbeefab9b2d12015-10-14 11:33:11 -07002102
Steve Antondcc3c022017-12-22 16:02:54 -08002103 const cricket::ContentInfo* video_content =
2104 GetFirstVideoContent(local_description()->description());
2105 if (video_content) {
2106 if (video_content->rejected) {
2107 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2108 } else {
2109 const cricket::VideoContentDescription* video_desc =
2110 video_content->media_description()->as_video();
2111 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2112 }
deadbeeffaac4972015-11-12 15:33:07 -08002113 }
deadbeefab9b2d12015-10-14 11:33:11 -07002114 }
2115
2116 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002117 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002118 if (data_content) {
2119 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002120 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002121 if (rtc::starts_with(data_desc->protocol().data(),
2122 cricket::kMediaProtocolRtpPrefix)) {
2123 UpdateLocalRtpDataChannels(data_desc->streams());
2124 }
2125 }
2126
Steve Anton8a006912017-12-04 15:25:56 -08002127 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128}
2129
2130void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002131 SetSessionDescriptionObserver* observer,
2132 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002133 SetRemoteDescription(
2134 std::unique_ptr<SessionDescriptionInterface>(desc),
2135 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2136 new SetRemoteDescriptionObserverAdapter(this, observer)));
2137}
2138
2139void PeerConnection::SetRemoteDescription(
2140 std::unique_ptr<SessionDescriptionInterface> desc,
2141 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002142 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002143
nisse7ce109a2017-01-31 00:57:56 -08002144 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002145 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146 return;
2147 }
Steve Anton8a006912017-12-04 15:25:56 -08002148
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002150 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002151 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152 return;
2153 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002154
Steve Anton80dd7b52018-02-16 17:08:42 -08002155 // If a session error has occurred the PeerConnection is in a possibly
2156 // inconsistent state so fail right away.
2157 if (session_error() != SessionError::kNone) {
2158 std::string error_message = GetSessionErrorMsg();
2159 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2160 observer->OnSetRemoteDescriptionComplete(
2161 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2162 return;
2163 }
Steve Anton71439a62018-02-15 11:53:06 -08002164
Steve Anton80dd7b52018-02-16 17:08:42 -08002165 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002166 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002167 std::string error_message = GetSetDescriptionErrorMessage(
2168 cricket::CS_REMOTE, desc->GetType(), error);
2169 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002170 observer->OnSetRemoteDescriptionComplete(
2171 RTCError(error.type(), std::move(error_message)));
2172 return;
2173 }
Steve Anton71439a62018-02-15 11:53:06 -08002174
Steve Anton80dd7b52018-02-16 17:08:42 -08002175 // Grab the description type before moving ownership to
2176 // ApplyRemoteDescription, which may destroy it before returning.
2177 const SdpType type = desc->GetType();
2178
2179 error = ApplyRemoteDescription(std::move(desc));
2180 // |desc| may be destroyed at this point.
2181
2182 if (!error.ok()) {
2183 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2184 // inconsistent state, so act conservatively here and set the session error
2185 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2186 SetSessionError(SessionError::kContent, error.message());
2187 std::string error_message =
2188 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2189 RTC_LOG(LS_ERROR) << error_message;
2190 observer->OnSetRemoteDescriptionComplete(
2191 RTCError(error.type(), std::move(error_message)));
2192 return;
2193 }
2194 RTC_DCHECK(remote_description());
2195
Steve Anton8e20f172018-03-06 10:55:04 -08002196 if (type == SdpType::kOffer) {
2197 // Report to UMA the format of the received offer.
2198 ReportSdpFormatReceived(*remote_description());
2199 }
2200
Steve Anton80dd7b52018-02-16 17:08:42 -08002201 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002202 // TODO(deadbeef): We already had to hop to the network thread for
2203 // MaybeStartGathering...
2204 network_thread()->Invoke<void>(
2205 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2206 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002207 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002208 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002209 }
2210
2211 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2212}
2213
2214RTCError PeerConnection::ApplyRemoteDescription(
2215 std::unique_ptr<SessionDescriptionInterface> desc) {
2216 RTC_DCHECK_RUN_ON(signaling_thread());
2217 RTC_DCHECK(desc);
2218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 // Update stats here so that we have the most recent stats for tracks and
2220 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002221 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002222
Steve Antondcc3c022017-12-22 16:02:54 -08002223 // Take a reference to the old remote description since it's used below to
2224 // compare against the new remote description. When setting the new remote
2225 // description, grab ownership of the replaced session description in case it
2226 // is the same as |old_remote_description|, to keep it alive for the duration
2227 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002228 const SessionDescriptionInterface* old_remote_description =
2229 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002230 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002231 SdpType type = desc->GetType();
2232 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002233 replaced_remote_description = pending_remote_description_
2234 ? std::move(pending_remote_description_)
2235 : std::move(current_remote_description_);
2236 current_remote_description_ = std::move(desc);
2237 pending_remote_description_ = nullptr;
2238 current_local_description_ = std::move(pending_local_description_);
2239 } else {
2240 replaced_remote_description = std::move(pending_remote_description_);
2241 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 }
Steve Anton8a006912017-12-04 15:25:56 -08002243 // The session description to apply now must be accessed by
2244 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002245 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246
Steve Anton8a006912017-12-04 15:25:56 -08002247 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002248 if (IsUnifiedPlan()) {
2249 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002250 cricket::CS_REMOTE, *remote_description(), local_description(),
2251 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002252 if (!error.ok()) {
2253 return error;
2254 }
Steve Antondcc3c022017-12-22 16:02:54 -08002255 } else {
2256 if (type == SdpType::kOffer) {
2257 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2258 // description is applied. Restore back to old description.
2259 RTCError error = CreateChannels(*remote_description()->description());
2260 if (!error.ok()) {
2261 return error;
2262 }
2263 }
Steve Anton8a006912017-12-04 15:25:56 -08002264
Steve Antondcc3c022017-12-22 16:02:54 -08002265 // Remove unused channels if MediaContentDescription is rejected.
2266 RemoveUnusedChannels(remote_description()->description());
2267 }
Steve Anton8a006912017-12-04 15:25:56 -08002268
2269 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2270 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002271 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002272 if (!error.ok()) {
2273 return error;
2274 }
2275
2276 if (local_description() &&
2277 !UseCandidatesInSessionDescription(remote_description())) {
2278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2279 }
2280
2281 if (old_remote_description) {
2282 for (const cricket::ContentInfo& content :
2283 old_remote_description->description()->contents()) {
2284 // Check if this new SessionDescription contains new ICE ufrag and
2285 // password that indicates the remote peer requests an ICE restart.
2286 // TODO(deadbeef): When we start storing both the current and pending
2287 // remote description, this should reset pending_ice_restarts and compare
2288 // against the current description.
2289 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2290 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002291 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002292 pending_ice_restarts_.insert(content.name);
2293 }
2294 } else {
2295 // We retain all received candidates only if ICE is not restarted.
2296 // When ICE is restarted, all previous candidates belong to an old
2297 // generation and should not be kept.
2298 // TODO(deadbeef): This goes against the W3C spec which says the remote
2299 // description should only contain candidates from the last set remote
2300 // description plus any candidates added since then. We should remove
2301 // this once we're sure it won't break anything.
2302 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2303 old_remote_description, content.name, mutable_remote_description());
2304 }
2305 }
2306 }
2307
2308 if (session_error() != SessionError::kNone) {
2309 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2310 }
2311
2312 // Set the the ICE connection state to connecting since the connection may
2313 // become writable with peer reflexive candidates before any remote candidate
2314 // is signaled.
2315 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2316 // is to have a new signal the indicates a change in checking state from the
2317 // transport and expose a new checking() member from transport that can be
2318 // read to determine the current checking state. The existing SignalConnecting
2319 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002320 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002321 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2322 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2323 }
2324
deadbeefab9b2d12015-10-14 11:33:11 -07002325 // If setting the description decided our SSL role, allocate any necessary
2326 // SCTP sids.
2327 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002328 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002329 AllocateSctpSids(role);
2330 }
2331
Steve Antondcc3c022017-12-22 16:02:54 -08002332 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002333 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2334 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002335 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002336 for (auto transceiver : transceivers_) {
2337 const ContentInfo* content =
2338 FindMediaSectionForTransceiver(transceiver, remote_description());
2339 if (!content) {
2340 continue;
2341 }
2342 const MediaContentDescription* media_desc = content->media_description();
2343 RtpTransceiverDirection local_direction =
2344 RtpTransceiverDirectionReversed(media_desc->direction());
2345 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2346 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2347 // transceiver's current direction is neither sendrecv nor recvonly,
2348 // process the addition of a remote track for the media description.
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00002349 //
2350 // Create a sync label in the case of an unsignalled msid.
2351 std::string sync_label = rtc::CreateRandomUuid();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002352 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002353 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002354 if (!stream_params.stream_ids().empty()) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00002355 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002356 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002357 }
Steve Antondcc3c022017-12-22 16:02:54 -08002358 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2359 (!transceiver->current_direction() ||
2360 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002361 *transceiver->current_direction()))) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00002362 rtc::scoped_refptr<MediaStreamInterface> stream =
2363 remote_streams_->find(sync_label);
2364 if (!stream) {
2365 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2366 MediaStream::Create(sync_label));
2367 remote_streams_->AddStream(stream);
2368 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002369 }
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00002370 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002371 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002372 }
2373 // If direction is sendonly or inactive, and transceiver's current
2374 // direction is neither sendonly nor inactive, process the removal of a
2375 // remote track for the media description.
2376 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002377 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002378 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002379 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002380 }
2381 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2382 transceiver->internal()->set_current_direction(local_direction);
2383 }
2384 if (content->rejected && !transceiver->stopped()) {
2385 transceiver->Stop();
2386 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002387 if (!content->rejected &&
2388 RtpTransceiverDirectionHasRecv(local_direction)) {
2389 // Set ssrc to 0 in the case of an unsignalled ssrc.
2390 uint32_t ssrc = 0;
2391 if (!media_desc->streams().empty()) {
2392 ssrc = media_desc->streams()[0].first_ssrc();
2393 }
2394 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002395 }
Steve Antondcc3c022017-12-22 16:02:54 -08002396 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002397 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002398 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002399 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002400 observer_->OnTrack(transceiver);
2401 observer_->OnAddTrack(transceiver->receiver(),
2402 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002403 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002404 for (auto stream : added_streams) {
2405 observer_->OnAddStream(stream);
2406 }
Steve Antondcc3c022017-12-22 16:02:54 -08002407 }
2408
Henrik Boströmfdb92012017-11-09 19:55:44 +01002409 const cricket::ContentInfo* audio_content =
2410 GetFirstAudioContent(remote_description()->description());
2411 const cricket::ContentInfo* video_content =
2412 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002413 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002414 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002415 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002416 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002417 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002418 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002419
2420 // Check if the descriptions include streams, just in case the peer supports
2421 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002422 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002423 (audio_desc && !audio_desc->streams().empty()) ||
2424 (video_desc && !video_desc->streams().empty())) {
2425 remote_peer_supports_msid_ = true;
2426 }
deadbeefab9b2d12015-10-14 11:33:11 -07002427
2428 // We wait to signal new streams until we finish processing the description,
2429 // since only at that point will new streams have all their tracks.
2430 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2431
Steve Antondcc3c022017-12-22 16:02:54 -08002432 if (!IsUnifiedPlan()) {
2433 // TODO(steveanton): When removing RTP senders/receivers in response to a
2434 // rejected media section, there is some cleanup logic that expects the
2435 // voice/ video channel to still be set. But in this method the voice/video
2436 // channel would have been destroyed by the SetRemoteDescription caller
2437 // above so the cleanup that relies on them fails to run. The RemoveSenders
2438 // calls should be moved to right before the DestroyChannel calls to fix
2439 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002440
Steve Antondcc3c022017-12-22 16:02:54 -08002441 // Find all audio rtp streams and create corresponding remote AudioTracks
2442 // and MediaStreams.
2443 if (audio_content) {
2444 if (audio_content->rejected) {
2445 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2446 } else {
2447 bool default_audio_track_needed =
2448 !remote_peer_supports_msid_ &&
2449 RtpTransceiverDirectionHasSend(audio_desc->direction());
2450 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2451 default_audio_track_needed, audio_desc->type(),
2452 new_streams);
2453 }
deadbeeffaac4972015-11-12 15:33:07 -08002454 }
deadbeefab9b2d12015-10-14 11:33:11 -07002455
Steve Antondcc3c022017-12-22 16:02:54 -08002456 // Find all video rtp streams and create corresponding remote VideoTracks
2457 // and MediaStreams.
2458 if (video_content) {
2459 if (video_content->rejected) {
2460 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2461 } else {
2462 bool default_video_track_needed =
2463 !remote_peer_supports_msid_ &&
2464 RtpTransceiverDirectionHasSend(video_desc->direction());
2465 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2466 default_video_track_needed, video_desc->type(),
2467 new_streams);
2468 }
deadbeeffaac4972015-11-12 15:33:07 -08002469 }
deadbeefab9b2d12015-10-14 11:33:11 -07002470
Steve Antondcc3c022017-12-22 16:02:54 -08002471 // Update the DataChannels with the information from the remote peer.
2472 if (data_desc) {
2473 if (rtc::starts_with(data_desc->protocol().data(),
2474 cricket::kMediaProtocolRtpPrefix)) {
2475 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2476 }
deadbeefab9b2d12015-10-14 11:33:11 -07002477 }
deadbeefab9b2d12015-10-14 11:33:11 -07002478
Steve Antondcc3c022017-12-22 16:02:54 -08002479 // Iterate new_streams and notify the observer about new MediaStreams.
2480 for (size_t i = 0; i < new_streams->count(); ++i) {
2481 MediaStreamInterface* new_stream = new_streams->at(i);
2482 stats_->AddStream(new_stream);
2483 observer_->OnAddStream(
2484 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2485 }
deadbeefab9b2d12015-10-14 11:33:11 -07002486
Steve Antondcc3c022017-12-22 16:02:54 -08002487 UpdateEndedRemoteMediaStreams();
2488 }
deadbeefab9b2d12015-10-14 11:33:11 -07002489
Steve Anton8a006912017-12-04 15:25:56 -08002490 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002491}
2492
Steve Antondcc3c022017-12-22 16:02:54 -08002493RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2494 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002495 const SessionDescriptionInterface& new_session,
2496 const SessionDescriptionInterface* old_local_description,
2497 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002498 RTC_DCHECK(IsUnifiedPlan());
2499
Steve Anton7464fca2018-01-19 11:10:37 -08002500 const cricket::ContentGroup* bundle_group = nullptr;
2501 if (new_session.GetType() == SdpType::kOffer) {
2502 auto bundle_group_or_error =
2503 GetEarlyBundleGroup(*new_session.description());
2504 if (!bundle_group_or_error.ok()) {
2505 return bundle_group_or_error.MoveError();
2506 }
2507 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002508 }
Steve Antondcc3c022017-12-22 16:02:54 -08002509
Steve Antondcc3c022017-12-22 16:02:54 -08002510 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002511 for (size_t i = 0; i < new_contents.size(); ++i) {
2512 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002513 cricket::MediaType media_type = new_content.media_description()->type();
2514 seen_mids_.insert(new_content.name);
2515 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2516 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002517 const cricket::ContentInfo* old_local_content = nullptr;
2518 if (old_local_description &&
2519 i < old_local_description->description()->contents().size()) {
2520 old_local_content =
2521 &old_local_description->description()->contents()[i];
2522 }
2523 const cricket::ContentInfo* old_remote_content = nullptr;
2524 if (old_remote_description &&
2525 i < old_remote_description->description()->contents().size()) {
2526 old_remote_content =
2527 &old_remote_description->description()->contents()[i];
2528 }
Steve Antondcc3c022017-12-22 16:02:54 -08002529 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002530 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2531 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002532 if (!transceiver_or_error.ok()) {
2533 return transceiver_or_error.MoveError();
2534 }
2535 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002536 RTCError error =
2537 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2538 if (!error.ok()) {
2539 return error;
2540 }
2541 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002542 if (GetDataMid() && new_content.name != *GetDataMid()) {
2543 // Ignore all but the first data section.
2544 continue;
2545 }
2546 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2547 if (!error.ok()) {
2548 return error;
2549 }
Steve Antondcc3c022017-12-22 16:02:54 -08002550 } else {
2551 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2552 "Unknown section type.");
2553 }
2554 }
2555
2556 return RTCError::OK();
2557}
2558
2559RTCError PeerConnection::UpdateTransceiverChannel(
2560 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2561 transceiver,
2562 const cricket::ContentInfo& content,
2563 const cricket::ContentGroup* bundle_group) {
2564 RTC_DCHECK(IsUnifiedPlan());
2565 RTC_DCHECK(transceiver);
2566 cricket::BaseChannel* channel = transceiver->internal()->channel();
2567 if (content.rejected) {
2568 if (channel) {
2569 transceiver->internal()->SetChannel(nullptr);
2570 DestroyBaseChannel(channel);
2571 }
2572 } else {
2573 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002574 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002575 channel = CreateVoiceChannel(
2576 content.name,
2577 GetTransportNameForMediaSection(content.name, bundle_group));
2578 } else {
Steve Anton69470252018-02-09 11:43:08 -08002579 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002580 channel = CreateVideoChannel(
2581 content.name,
2582 GetTransportNameForMediaSection(content.name, bundle_group));
2583 }
2584 if (!channel) {
2585 LOG_AND_RETURN_ERROR(
2586 RTCErrorType::INTERNAL_ERROR,
2587 "Failed to create channel for mid=" + content.name);
2588 }
2589 transceiver->internal()->SetChannel(channel);
2590 }
2591 }
2592 return RTCError::OK();
2593}
2594
Steve Antonfa2260d2017-12-28 16:38:23 -08002595RTCError PeerConnection::UpdateDataChannel(
2596 cricket::ContentSource source,
2597 const cricket::ContentInfo& content,
2598 const cricket::ContentGroup* bundle_group) {
2599 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002600 // If data channels are disabled, ignore this media section. CreateAnswer
2601 // will take care of rejecting it.
2602 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002603 }
2604 if (content.rejected) {
2605 DestroyDataChannel();
2606 } else {
2607 if (!rtp_data_channel_ && !sctp_transport_) {
2608 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2609 content.name, bundle_group))) {
2610 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2611 "Failed to create data channel.");
2612 }
2613 }
2614 if (source == cricket::CS_REMOTE) {
2615 const MediaContentDescription* data_desc = content.media_description();
2616 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2617 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2618 }
2619 }
2620 }
2621 return RTCError::OK();
2622}
2623
Steve Antondcc3c022017-12-22 16:02:54 -08002624RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2625PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002626 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002627 size_t mline_index,
2628 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002629 const ContentInfo* old_local_content,
2630 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002631 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002632 // If this is an offer then the m= section might be recycled. If the m=
2633 // section is being recycled (defined as: rejected in the current local or
2634 // remote description and not rejected in new description), dissociate the
2635 // currently associated RtpTransceiver by setting its mid property to null,
2636 // and discard the mapping between the transceiver and its m= section index.
2637 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2638 old_remote_content)) {
2639 // We want to dissociate the transceiver that has the rejected mid.
2640 const std::string& old_mid =
2641 (old_local_content && old_local_content->rejected)
2642 ? old_local_content->name
2643 : old_remote_content->name;
2644 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002645 if (old_transceiver) {
2646 old_transceiver->internal()->set_mid(rtc::nullopt);
2647 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2648 }
2649 }
2650 const MediaContentDescription* media_desc = content.media_description();
2651 auto transceiver = GetAssociatedTransceiver(content.name);
2652 if (source == cricket::CS_LOCAL) {
2653 // Find the RtpTransceiver that corresponds to this m= section, using the
2654 // mapping between transceivers and m= section indices established when
2655 // creating the offer.
2656 if (!transceiver) {
2657 transceiver = GetTransceiverByMLineIndex(mline_index);
2658 }
2659 if (!transceiver) {
2660 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2661 "Unknown transceiver");
2662 }
2663 } else {
2664 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2665 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2666 // of the same type...
2667 if (!transceiver &&
2668 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2669 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2670 }
2671 // If no RtpTransceiver was found in the previous step, create one with a
2672 // recvonly direction.
2673 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002674 auto sender =
2675 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002676 std::string receiver_id;
2677 if (!media_desc->streams().empty()) {
2678 receiver_id = media_desc->streams()[0].id;
2679 } else {
2680 receiver_id = rtc::CreateRandomUuid();
2681 }
2682 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002683 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002684 transceiver->internal()->set_direction(
2685 RtpTransceiverDirection::kRecvOnly);
2686 }
2687 }
2688 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002689 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002690 LOG_AND_RETURN_ERROR(
2691 RTCErrorType::INVALID_PARAMETER,
2692 "Transceiver type does not match media description type.");
2693 }
2694 // Associate the found or created RtpTransceiver with the m= section by
2695 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2696 // section, and establish a mapping between the transceiver and the index of
2697 // the m= section.
2698 transceiver->internal()->set_mid(content.name);
2699 transceiver->internal()->set_mline_index(mline_index);
2700 return std::move(transceiver);
2701}
2702
2703rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2704PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2705 RTC_DCHECK(IsUnifiedPlan());
2706 for (auto transceiver : transceivers_) {
2707 if (transceiver->mid() == mid) {
2708 return transceiver;
2709 }
2710 }
2711 return nullptr;
2712}
2713
2714rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2715PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2716 RTC_DCHECK(IsUnifiedPlan());
2717 for (auto transceiver : transceivers_) {
2718 if (transceiver->internal()->mline_index() == mline_index) {
2719 return transceiver;
2720 }
2721 }
2722 return nullptr;
2723}
2724
2725rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2726PeerConnection::FindAvailableTransceiverToReceive(
2727 cricket::MediaType media_type) const {
2728 RTC_DCHECK(IsUnifiedPlan());
2729 // From JSEP section 5.10 (Applying a Remote Description):
2730 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2731 // the same type that were added to the PeerConnection by addTrack and are not
2732 // associated with any m= section and are not stopped, find the first such
2733 // RtpTransceiver.
2734 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002735 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002736 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2737 !transceiver->stopped()) {
2738 return transceiver;
2739 }
2740 }
2741 return nullptr;
2742}
2743
Steve Antoned10bd92017-12-05 10:52:59 -08002744const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2745 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2746 transceiver,
2747 const SessionDescriptionInterface* sdesc) const {
2748 RTC_DCHECK(transceiver);
2749 RTC_DCHECK(sdesc);
2750 if (IsUnifiedPlan()) {
2751 if (!transceiver->internal()->mid()) {
2752 // This transceiver is not associated with a media section yet.
2753 return nullptr;
2754 }
2755 return sdesc->description()->GetContentByName(
2756 *transceiver->internal()->mid());
2757 } else {
2758 // Plan B only allows at most one audio and one video section, so use the
2759 // first media section of that type.
2760 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002761 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002762 }
2763}
2764
deadbeef46c73892016-11-16 19:42:04 -08002765PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2766 return configuration_;
2767}
2768
deadbeef293e9262017-01-11 12:28:30 -08002769bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2770 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002771 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002772
Steve Anton75737c02017-11-06 10:37:17 -08002773 if (local_description() && configuration.ice_candidate_pool_size !=
2774 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002775 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2776 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002777 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002778 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002779
deadbeef293e9262017-01-11 12:28:30 -08002780 // The simplest (and most future-compatible) way to tell if the config was
2781 // modified in an invalid way is to copy each property we do support
2782 // modifying, then use operator==. There are far more properties we don't
2783 // support modifying than those we do, and more could be added.
2784 RTCConfiguration modified_config = configuration_;
2785 modified_config.servers = configuration.servers;
2786 modified_config.type = configuration.type;
2787 modified_config.ice_candidate_pool_size =
2788 configuration.ice_candidate_pool_size;
2789 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002790 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002791 modified_config.ice_check_interval_strong_connectivity =
2792 configuration.ice_check_interval_strong_connectivity;
2793 modified_config.ice_check_interval_weak_connectivity =
2794 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002795 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2796 modified_config.ice_unwritable_min_checks =
2797 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002798 modified_config.stun_candidate_keepalive_interval =
2799 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002800 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002801 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002802 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002803 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002804 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2805 }
2806
Steve Anton038834f2017-07-14 15:59:59 -07002807 // Validate the modified configuration.
2808 RTCError validate_error = ValidateConfiguration(modified_config);
2809 if (!validate_error.ok()) {
2810 return SafeSetError(std::move(validate_error), error);
2811 }
2812
deadbeef293e9262017-01-11 12:28:30 -08002813 // Note that this isn't possible through chromium, since it's an unsigned
2814 // short in WebIDL.
2815 if (configuration.ice_candidate_pool_size < 0 ||
2816 configuration.ice_candidate_pool_size > UINT16_MAX) {
2817 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2818 }
2819
2820 // Parse ICE servers before hopping to network thread.
2821 cricket::ServerAddresses stun_servers;
2822 std::vector<cricket::RelayServerConfig> turn_servers;
2823 RTCErrorType parse_error =
2824 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2825 if (parse_error != RTCErrorType::NONE) {
2826 return SafeSetError(parse_error, error);
2827 }
2828
2829 // In theory this shouldn't fail.
2830 if (!network_thread()->Invoke<bool>(
2831 RTC_FROM_HERE,
2832 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2833 stun_servers, turn_servers, modified_config.type,
2834 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002835 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002836 modified_config.turn_customizer,
2837 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002838 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002839 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2840 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002841
deadbeefd1a38b52016-12-10 13:15:33 -08002842 // As described in JSEP, calling setConfiguration with new ICE servers or
2843 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2844 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002845 if (modified_config.servers != configuration_.servers ||
2846 modified_config.type != configuration_.type ||
2847 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002848 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002849 }
skvladd1f5fda2017-02-03 16:54:05 -08002850
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002851 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002852
deadbeef293e9262017-01-11 12:28:30 -08002853 configuration_ = modified_config;
2854 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002855}
2856
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857bool PeerConnection::AddIceCandidate(
2858 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002859 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002860 if (IsClosed()) {
2861 return false;
2862 }
Steve Antond25da372017-11-06 14:50:29 -08002863
2864 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002865 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002866 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002867 return false;
2868 }
2869
2870 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002871 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002872 return false;
2873 }
2874
2875 bool valid = false;
2876 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2877 if (!valid) {
2878 return false;
2879 }
2880
2881 // Add this candidate to the remote session description.
2882 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002883 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002884 return false;
2885 }
2886
2887 if (ready) {
2888 return UseCandidate(ice_candidate);
2889 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002890 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002891 return true;
2892 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893}
2894
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002895bool PeerConnection::RemoveIceCandidates(
2896 const std::vector<cricket::Candidate>& candidates) {
2897 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002898 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002899 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002900 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002901 return false;
2902 }
2903
2904 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002905 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002906 return false;
2907 }
2908
2909 size_t number_removed =
2910 mutable_remote_description()->RemoveCandidates(candidates);
2911 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002912 RTC_LOG(LS_ERROR)
2913 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002914 "Requested "
2915 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002916 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002917 }
2918
2919 // Remove the candidates from the transport controller.
2920 std::string error;
2921 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2922 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002923 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002924 }
2925 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002926}
2927
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002928void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002929 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002930 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002931
Steve Anton75737c02017-11-06 10:37:17 -08002932 if (transport_controller()) {
2933 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002934 }
2935
Steve Antondb67ba12018-03-19 17:41:42 -07002936 for (auto transceiver : transceivers_) {
2937 auto* channel = transceiver->internal()->channel();
2938 if (channel) {
2939 channel->SetMetricsObserver(uma_observer_);
2940 }
2941 }
2942
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002943 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002944 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002945 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002946 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002947 uma_observer_->IncrementEnumCounter(
2948 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2949 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002950 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002951 uma_observer_->IncrementEnumCounter(
2952 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2953 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002954 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002955 // Send information about the requested SDP semantics.
2956 switch (configuration_.sdp_semantics) {
2957 case SdpSemantics::kDefault:
2958 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2959 kSdpSemanticRequestDefault,
2960 kSdpSemanticRequestMax);
2961
2962 break;
2963 case SdpSemantics::kPlanB:
2964 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2965 kSdpSemanticRequestPlanB,
2966 kSdpSemanticRequestMax);
2967 break;
2968 case SdpSemantics::kUnifiedPlan:
2969 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2970 kSdpSemanticRequestUnifiedPlan,
2971 kSdpSemanticRequestMax);
2972 break;
2973 default:
2974 RTC_NOTREACHED();
2975 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002976 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002977}
2978
zstein4b979802017-06-02 14:37:37 -07002979RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002980 if (!worker_thread()->IsCurrent()) {
2981 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002982 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2983 }
2984
2985 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2986 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2987 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2988 if (has_min && *bitrate.min_bitrate_bps < 0) {
2989 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2990 "min_bitrate_bps <= 0");
2991 }
2992 if (has_current) {
2993 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2994 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2995 "current_bitrate_bps < min_bitrate_bps");
2996 } else if (*bitrate.current_bitrate_bps < 0) {
2997 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2998 "curent_bitrate_bps < 0");
2999 }
3000 }
3001 if (has_max) {
3002 if (has_current &&
3003 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3004 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3005 "max_bitrate_bps < current_bitrate_bps");
3006 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3007 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3008 "max_bitrate_bps < min_bitrate_bps");
3009 } else if (*bitrate.max_bitrate_bps < 0) {
3010 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3011 "max_bitrate_bps < 0");
3012 }
3013 }
3014
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003015 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003016 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3017 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3018 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3019
3020 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003021 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003022
3023 return RTCError::OK();
3024}
3025
Alex Narest78609d52017-10-20 10:37:47 +02003026void PeerConnection::SetBitrateAllocationStrategy(
3027 std::unique_ptr<rtc::BitrateAllocationStrategy>
3028 bitrate_allocation_strategy) {
3029 rtc::Thread* worker_thread = factory_->worker_thread();
3030 if (!worker_thread->IsCurrent()) {
3031 rtc::BitrateAllocationStrategy* strategy_raw =
3032 bitrate_allocation_strategy.release();
3033 auto functor = [this, strategy_raw]() {
3034 call_->SetBitrateAllocationStrategy(
3035 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3036 };
3037 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3038 return;
3039 }
3040 RTC_DCHECK(call_.get());
3041 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3042}
3043
henrika5f6bf242017-11-01 11:06:56 +01003044void PeerConnection::SetAudioPlayout(bool playout) {
3045 if (!worker_thread()->IsCurrent()) {
3046 worker_thread()->Invoke<void>(
3047 RTC_FROM_HERE,
3048 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3049 return;
3050 }
3051 auto audio_state =
3052 factory_->channel_manager()->media_engine()->GetAudioState();
3053 audio_state->SetPlayout(playout);
3054}
3055
3056void PeerConnection::SetAudioRecording(bool recording) {
3057 if (!worker_thread()->IsCurrent()) {
3058 worker_thread()->Invoke<void>(
3059 RTC_FROM_HERE,
3060 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3061 return;
3062 }
3063 auto audio_state =
3064 factory_->channel_manager()->media_engine()->GetAudioState();
3065 audio_state->SetRecording(recording);
3066}
3067
Steve Anton8c0f7a72017-10-03 10:03:10 -07003068std::unique_ptr<rtc::SSLCertificate>
3069PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003070 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3071 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003072 return nullptr;
3073 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003074 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003075}
3076
Zhi Huang70b820f2018-01-27 14:16:15 -08003077std::unique_ptr<rtc::SSLCertChain>
3078PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003079 auto audio_transceiver = GetFirstAudioTransceiver();
3080 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003081 return nullptr;
3082 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003083 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003084 audio_transceiver->internal()->channel()->transport_name());
3085}
3086
3087rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3088PeerConnection::GetFirstAudioTransceiver() const {
3089 for (auto transceiver : transceivers_) {
3090 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3091 return transceiver;
3092 }
3093 }
3094 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003095}
3096
ivoc14d5dbe2016-07-04 07:06:55 -07003097bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3098 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003099 // TODO(eladalon): It would be better to not allow negative values into PC.
3100 const size_t max_size = (max_size_bytes < 0)
3101 ? RtcEventLog::kUnlimitedOutput
3102 : rtc::saturated_cast<size_t>(max_size_bytes);
3103 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003104 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3105 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003106}
3107
Bjorn Tereliusde939432017-11-20 17:38:14 +01003108bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3109 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003110 // TODO(eladalon): In C++14, this can be done with a lambda.
3111 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003112 bool operator()() {
3113 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3114 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003115 PeerConnection* const pc;
3116 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003117 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003118 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003119 return worker_thread()->Invoke<bool>(
3120 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003121}
3122
3123void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003124 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003125 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3126}
3127
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003129 return pending_local_description_ ? pending_local_description_.get()
3130 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003131}
3132
3133const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003134 return pending_remote_description_ ? pending_remote_description_.get()
3135 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003136}
3137
deadbeeffe4a8a42016-12-20 17:56:17 -08003138const SessionDescriptionInterface* PeerConnection::current_local_description()
3139 const {
Steve Anton75737c02017-11-06 10:37:17 -08003140 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003141}
3142
3143const SessionDescriptionInterface* PeerConnection::current_remote_description()
3144 const {
Steve Anton75737c02017-11-06 10:37:17 -08003145 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003146}
3147
3148const SessionDescriptionInterface* PeerConnection::pending_local_description()
3149 const {
Steve Anton75737c02017-11-06 10:37:17 -08003150 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003151}
3152
3153const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3154 const {
Steve Anton75737c02017-11-06 10:37:17 -08003155 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003156}
3157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003158void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003159 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160 // Update stats here so that we have the most recent stats for tracks and
3161 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003162 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163
Steve Anton75737c02017-11-06 10:37:17 -08003164 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003165
Steve Anton8af21862017-12-15 11:20:13 -08003166 for (auto transceiver : transceivers_) {
3167 transceiver->Stop();
3168 }
3169 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003170
Qingsi Wang93a84392018-01-30 17:13:09 -08003171 // The event log is used in the transport controller, which must be outlived
3172 // by the former. CreateOffer by the peer connection is implemented
3173 // asynchronously and if the peer connection is closed without resetting the
3174 // WebRTC session description factory, the session description factory would
3175 // call the transport controller.
3176 webrtc_session_desc_factory_.reset();
3177 transport_controller_.reset();
3178
deadbeef42a42632017-03-10 15:18:00 -08003179 network_thread()->Invoke<void>(
3180 RTC_FROM_HERE,
3181 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3182 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003183
Steve Anton978b8762017-09-29 12:15:02 -07003184 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003185 call_.reset();
3186 // The event log must outlive call (and any other object that uses it).
3187 event_log_.reset();
3188 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189}
3190
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003191void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003192 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3194 SetSessionDescriptionMsg* param =
3195 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3196 param->observer->OnSuccess();
3197 delete param;
3198 break;
3199 }
3200 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3201 SetSessionDescriptionMsg* param =
3202 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003203 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003204 delete param;
3205 break;
3206 }
deadbeefab9b2d12015-10-14 11:33:11 -07003207 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3208 CreateSessionDescriptionMsg* param =
3209 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003210 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003211 delete param;
3212 break;
3213 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214 case MSG_GETSTATS: {
3215 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003216 StatsReports reports;
3217 stats_->GetStats(param->track, &reports);
3218 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219 delete param;
3220 break;
3221 }
deadbeefbd292462015-12-14 18:15:29 -08003222 case MSG_FREE_DATACHANNELS: {
3223 sctp_data_channels_to_free_.clear();
3224 break;
3225 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003227 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228 break;
3229 }
3230}
3231
Steve Antonafb0bb72018-02-20 11:35:37 -08003232cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3233 RTC_DCHECK(!IsUnifiedPlan());
3234 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3235 GetAudioTransceiver()->internal()->channel());
3236 if (voice_channel) {
3237 return voice_channel->media_channel();
3238 } else {
3239 return nullptr;
3240 }
3241}
3242
3243cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3244 RTC_DCHECK(!IsUnifiedPlan());
3245 auto* video_channel = static_cast<cricket::VideoChannel*>(
3246 GetVideoTransceiver()->internal()->channel());
3247 if (video_channel) {
3248 return video_channel->media_channel();
3249 } else {
3250 return nullptr;
3251 }
3252}
3253
Steve Anton4171afb2017-11-20 10:20:22 -08003254void PeerConnection::CreateAudioReceiver(
3255 MediaStreamInterface* stream,
3256 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003257 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3258 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003259 auto* audio_receiver = new AudioRtpReceiver(
3260 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003261 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003262 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3263 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3264 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003265 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003266 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003267}
3268
Steve Anton4171afb2017-11-20 10:20:22 -08003269void PeerConnection::CreateVideoReceiver(
3270 MediaStreamInterface* stream,
3271 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003272 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3273 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003274 auto* video_receiver = new VideoRtpReceiver(
3275 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003276 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003277 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3278 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3279 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003280 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003281 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282}
3283
deadbeef70ab1a12015-09-28 16:53:55 -07003284// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3285// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003286rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003287 const RtpSenderInfo& remote_sender_info) {
3288 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3289 if (!receiver) {
3290 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3291 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003292 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003293 }
Steve Anton4171afb2017-11-20 10:20:22 -08003294 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3295 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3296 } else {
3297 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3298 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003299 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003300}
3301
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003302void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3303 MediaStreamInterface* stream) {
3304 RTC_DCHECK(!IsClosed());
3305 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003306 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003307 // We already have a sender for this track, so just change the stream_id
3308 // so that it's correct in the next call to CreateOffer.
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003309 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003310 return;
3311 }
3312
3313 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003314 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003315 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003316 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003317 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003318 // If the sender has already been configured in SDP, we call SetSsrc,
3319 // which will connect the sender to the underlying transport. This can
3320 // occur if a local session description that contains the ID of the sender
3321 // is set before AddStream is called. It can also occur if the local
3322 // session description is not changed and RemoveStream is called, and
3323 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003324 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003325 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003326 if (sender_info) {
3327 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003328 }
3329}
3330
3331// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3332// indefinitely, when we have unified plan SDP.
3333void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3334 MediaStreamInterface* stream) {
3335 RTC_DCHECK(!IsClosed());
3336 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003337 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003338 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3339 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003340 return;
3341 }
Steve Anton4171afb2017-11-20 10:20:22 -08003342 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003343}
3344
3345void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3346 MediaStreamInterface* stream) {
3347 RTC_DCHECK(!IsClosed());
3348 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003349 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003350 // We already have a sender for this track, so just change the stream_id
3351 // so that it's correct in the next call to CreateOffer.
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003352 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003353 return;
3354 }
3355
3356 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003357 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003358 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003359 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003360 GetVideoTransceiver()->internal()->AddSender(new_sender);
3361 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003362 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003363 if (sender_info) {
3364 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003365 }
3366}
3367
3368void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3369 MediaStreamInterface* stream) {
3370 RTC_DCHECK(!IsClosed());
3371 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003372 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003373 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3374 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003375 return;
3376 }
Steve Anton4171afb2017-11-20 10:20:22 -08003377 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003378}
3379
Steve Antonba818672017-11-06 10:21:57 -08003380void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003381 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003382 if (ice_connection_state_ == new_state) {
3383 return;
3384 }
3385
deadbeefcbecd352015-09-23 11:50:27 -07003386 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003387 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003388 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003389 return;
3390 }
Steve Antonba818672017-11-06 10:21:57 -08003391
Mirko Bonadei675513b2017-11-09 11:09:25 +01003392 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3393 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003394 RTC_DCHECK(ice_connection_state_ !=
3395 PeerConnectionInterface::kIceConnectionClosed);
3396
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003397 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003398 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003399}
3400
3401void PeerConnection::OnIceGatheringChange(
3402 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003403 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003404 if (IsClosed()) {
3405 return;
3406 }
3407 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003408 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003409}
3410
jbauch81bf7b02017-03-25 08:31:12 -07003411void PeerConnection::OnIceCandidate(
3412 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003413 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003414 if (IsClosed()) {
3415 return;
3416 }
jbauch81bf7b02017-03-25 08:31:12 -07003417 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003418}
3419
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003420void PeerConnection::OnIceCandidatesRemoved(
3421 const std::vector<cricket::Candidate>& candidates) {
3422 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003423 if (IsClosed()) {
3424 return;
3425 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003426 observer_->OnIceCandidatesRemoved(candidates);
3427}
3428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003429void PeerConnection::ChangeSignalingState(
3430 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003431 RTC_DCHECK(signaling_thread()->IsCurrent());
3432 if (signaling_state_ == signaling_state) {
3433 return;
3434 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003435 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3436 << GetSignalingStateString(signaling_state_)
3437 << " New state: "
3438 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 signaling_state_ = signaling_state;
3440 if (signaling_state == kClosed) {
3441 ice_connection_state_ = kIceConnectionClosed;
3442 observer_->OnIceConnectionChange(ice_connection_state_);
3443 if (ice_gathering_state_ != kIceGatheringComplete) {
3444 ice_gathering_state_ = kIceGatheringComplete;
3445 observer_->OnIceGatheringChange(ice_gathering_state_);
3446 }
3447 }
3448 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003449}
3450
deadbeefeb459812015-12-15 19:24:43 -08003451void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3452 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003453 if (IsClosed()) {
3454 return;
3455 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003456 AddAudioTrack(track, stream);
3457 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003458}
3459
deadbeefeb459812015-12-15 19:24:43 -08003460void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3461 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003462 if (IsClosed()) {
3463 return;
3464 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003465 RemoveAudioTrack(track, stream);
3466 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003467}
3468
3469void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3470 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003471 if (IsClosed()) {
3472 return;
3473 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003474 AddVideoTrack(track, stream);
3475 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003476}
3477
3478void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3479 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003480 if (IsClosed()) {
3481 return;
3482 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003483 RemoveVideoTrack(track, stream);
3484 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003485}
3486
Henrik Boström31638672017-11-23 17:48:32 +01003487void PeerConnection::PostSetSessionDescriptionSuccess(
3488 SetSessionDescriptionObserver* observer) {
3489 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3490 signaling_thread()->Post(RTC_FROM_HERE, this,
3491 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3492}
3493
deadbeefab9b2d12015-10-14 11:33:11 -07003494void PeerConnection::PostSetSessionDescriptionFailure(
3495 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003496 RTCError&& error) {
3497 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003498 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003499 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003500 signaling_thread()->Post(RTC_FROM_HERE, this,
3501 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003502}
3503
3504void PeerConnection::PostCreateSessionDescriptionFailure(
3505 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003506 RTCError error) {
3507 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003508 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003509 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003510 signaling_thread()->Post(RTC_FROM_HERE, this,
3511 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003512}
3513
zhihuang1c378ed2017-08-17 14:10:50 -07003514void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003515 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003516 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003517 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003518
Steve Antondcc3c022017-12-22 16:02:54 -08003519 if (IsUnifiedPlan()) {
3520 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3521 } else {
3522 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3523 }
3524
Steve Antonfa2260d2017-12-28 16:38:23 -08003525 // Intentionally unset the data channel type for RTP data channel with the
3526 // second condition. Otherwise the RTP data channels would be successfully
3527 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3528 // when building with chromium. We want to leave RTP data channels broken, so
3529 // people won't try to use them.
3530 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3531 session_options->data_channel_type = data_channel_type();
3532 }
3533
Steve Antondcc3c022017-12-22 16:02:54 -08003534 // Apply ICE restart flag and renomination flag.
3535 for (auto& options : session_options->media_description_options) {
3536 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3537 options.transport_options.enable_ice_renomination =
3538 configuration_.enable_ice_renomination;
3539 }
3540
3541 session_options->rtcp_cname = rtcp_cname_;
3542 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003543 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003544}
3545
3546void PeerConnection::GetOptionsForPlanBOffer(
3547 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3548 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003549 // Figure out transceiver directional preferences.
3550 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3551 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3552
3553 // By default, generate sendrecv/recvonly m= sections.
3554 bool recv_audio = true;
3555 bool recv_video = true;
3556
3557 // By default, only offer a new m= section if we have media to send with it.
3558 bool offer_new_audio_description = send_audio;
3559 bool offer_new_video_description = send_video;
3560 bool offer_new_data_description = HasDataChannels();
3561
3562 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003563 if (offer_answer_options.offer_to_receive_audio !=
3564 RTCOfferAnswerOptions::kUndefined) {
3565 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003566 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003567 offer_new_audio_description ||
3568 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003569 }
Steve Antondcc3c022017-12-22 16:02:54 -08003570 if (offer_answer_options.offer_to_receive_video !=
3571 RTCOfferAnswerOptions::kUndefined) {
3572 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003573 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003574 offer_new_video_description ||
3575 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003576 }
3577
3578 rtc::Optional<size_t> audio_index;
3579 rtc::Optional<size_t> video_index;
3580 rtc::Optional<size_t> data_index;
3581 // If a current description exists, generate m= sections in the same order,
3582 // using the first audio/video/data section that appears and rejecting
3583 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003584 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003585 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003586 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003587 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3588 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3589 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003590 }
3591
zhihuang1c378ed2017-08-17 14:10:50 -07003592 // Add audio/video/data m= sections to the end if needed.
3593 if (!audio_index && offer_new_audio_description) {
3594 session_options->media_description_options.push_back(
3595 cricket::MediaDescriptionOptions(
3596 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003597 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3598 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003599 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003600 }
zhihuang1c378ed2017-08-17 14:10:50 -07003601 if (!video_index && offer_new_video_description) {
3602 session_options->media_description_options.push_back(
3603 cricket::MediaDescriptionOptions(
3604 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003605 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3606 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003607 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003608 }
zhihuang1c378ed2017-08-17 14:10:50 -07003609 if (!data_index && offer_new_data_description) {
3610 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003611 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003612 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003613 }
3614
3615 cricket::MediaDescriptionOptions* audio_media_description_options =
3616 !audio_index ? nullptr
3617 : &session_options->media_description_options[*audio_index];
3618 cricket::MediaDescriptionOptions* video_media_description_options =
3619 !video_index ? nullptr
3620 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003621
Steve Anton4171afb2017-11-20 10:20:22 -08003622 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003623 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003624}
3625
3626// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3627// and return a reference to it.
3628// Generated MIDs should be no more than 3 bytes long to take up less space in
3629// the RTP packet.
3630static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3631 RTC_DCHECK(used_mids);
3632 // We're boring: just generate MIDs 0, 1, 2, ...
3633 size_t i = 0;
3634 std::set<std::string>::iterator it;
3635 bool inserted;
3636 do {
3637 std::string mid = rtc::ToString(i++);
3638 auto insert_result = used_mids->insert(mid);
3639 it = insert_result.first;
3640 inserted = insert_result.second;
3641 } while (!inserted);
3642 return *it;
3643}
3644
3645static cricket::MediaDescriptionOptions
3646GetMediaDescriptionOptionsForTransceiver(
3647 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3648 transceiver,
3649 const std::string& mid) {
3650 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003651 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003652 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003653 // This behavior is specified in JSEP. The gist is that:
3654 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3655 // sendrecv.
3656 // 2. If the MSID is included, then it must be included in any subsequent
3657 // offer/answer exactly the same until the RtpTransceiver is stopped.
3658 if (!transceiver->stopped() &&
3659 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3660 transceiver->internal()->has_ever_been_used_to_send())) {
3661 cricket::SenderOptions sender_options;
3662 sender_options.track_id = transceiver->sender()->id();
3663 sender_options.stream_ids = transceiver->sender()->stream_ids();
3664 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3665 // set in the RTP parameters when the transceiver was added.
3666 sender_options.num_sim_layers = 1;
3667 media_description_options.sender_options.push_back(sender_options);
3668 }
Steve Antondcc3c022017-12-22 16:02:54 -08003669 return media_description_options;
3670}
3671
3672void PeerConnection::GetOptionsForUnifiedPlanOffer(
3673 const RTCOfferAnswerOptions& offer_answer_options,
3674 cricket::MediaSessionOptions* session_options) {
3675 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3676 // Offers) and 5.2.2 (Subsequent Offers).
3677 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3678 const ContentInfos& local_contents =
3679 (local_description() ? local_description()->description()->contents()
3680 : ContentInfos());
3681 const ContentInfos& remote_contents =
3682 (remote_description() ? remote_description()->description()->contents()
3683 : ContentInfos());
3684 // The mline indices that can be recycled. New transceivers should reuse these
3685 // slots first.
3686 std::queue<size_t> recycleable_mline_indices;
3687 // Track the MIDs used in previous offer/answer exchanges and the current
3688 // offer so that new, unique MIDs are generated.
3689 std::set<std::string> used_mids = seen_mids_;
3690 // First, go through each media section that exists in either the local or
3691 // remote description and generate a media section in this offer for the
3692 // associated transceiver. If a media section can be recycled, generate a
3693 // default, rejected media section here that can be later overwritten.
3694 for (size_t i = 0;
3695 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3696 // Either |local_content| or |remote_content| is non-null.
3697 const ContentInfo* local_content =
3698 (i < local_contents.size() ? &local_contents[i] : nullptr);
3699 const ContentInfo* remote_content =
3700 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3701 bool had_been_rejected = (local_content && local_content->rejected) ||
3702 (remote_content && remote_content->rejected);
3703 const std::string& mid =
3704 (local_content ? local_content->name : remote_content->name);
3705 cricket::MediaType media_type =
3706 (local_content ? local_content->media_description()->type()
3707 : remote_content->media_description()->type());
3708 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3709 media_type == cricket::MEDIA_TYPE_VIDEO) {
3710 auto transceiver = GetAssociatedTransceiver(mid);
3711 RTC_CHECK(transceiver);
3712 // A media section is considered eligible for recycling if it is marked as
3713 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003714 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003715 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003716 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3717 RtpTransceiverDirection::kInactive,
3718 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003719 recycleable_mline_indices.push(i);
3720 } else {
3721 session_options->media_description_options.push_back(
3722 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3723 // CreateOffer shouldn't really cause any state changes in
3724 // PeerConnection, but we need a way to match new transceivers to new
3725 // media sections in SetLocalDescription and JSEP specifies this is done
3726 // by recording the index of the media section generated for the
3727 // transceiver in the offer.
3728 transceiver->internal()->set_mline_index(i);
3729 }
3730 } else {
3731 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003732 RTC_CHECK(GetDataMid());
3733 if (had_been_rejected || mid != *GetDataMid()) {
3734 session_options->media_description_options.push_back(
3735 GetMediaDescriptionOptionsForRejectedData(mid));
3736 } else {
3737 session_options->media_description_options.push_back(
3738 GetMediaDescriptionOptionsForActiveData(mid));
3739 }
Steve Antondcc3c022017-12-22 16:02:54 -08003740 }
3741 }
3742 // Next, look for transceivers that are newly added (that is, are not stopped
3743 // and not associated). Reuse media sections marked as recyclable first,
3744 // otherwise append to the end of the offer. New media sections should be
3745 // added in the order they were added to the PeerConnection.
3746 for (auto transceiver : transceivers_) {
3747 if (transceiver->mid() || transceiver->stopped()) {
3748 continue;
3749 }
3750 size_t mline_index;
3751 if (!recycleable_mline_indices.empty()) {
3752 mline_index = recycleable_mline_indices.front();
3753 recycleable_mline_indices.pop();
3754 session_options->media_description_options[mline_index] =
3755 GetMediaDescriptionOptionsForTransceiver(transceiver,
3756 AllocateMid(&used_mids));
3757 } else {
3758 mline_index = session_options->media_description_options.size();
3759 session_options->media_description_options.push_back(
3760 GetMediaDescriptionOptionsForTransceiver(transceiver,
3761 AllocateMid(&used_mids)));
3762 }
3763 // See comment above for why CreateOffer changes the transceiver's state.
3764 transceiver->internal()->set_mline_index(mline_index);
3765 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003766 // Lastly, add a m-section if we have local data channels and an m section
3767 // does not already exist.
3768 if (!GetDataMid() && HasDataChannels()) {
3769 session_options->media_description_options.push_back(
3770 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3771 }
Steve Antondcc3c022017-12-22 16:02:54 -08003772}
3773
3774void PeerConnection::GetOptionsForAnswer(
3775 const RTCOfferAnswerOptions& offer_answer_options,
3776 cricket::MediaSessionOptions* session_options) {
3777 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3778
3779 if (IsUnifiedPlan()) {
3780 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3781 } else {
3782 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3783 }
3784
Steve Antonfa2260d2017-12-28 16:38:23 -08003785 // Intentionally unset the data channel type for RTP data channel. Otherwise
3786 // the RTP data channels would be successfully negotiated by default and the
3787 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3788 // We want to leave RTP data channels broken, so people won't try to use them.
3789 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3790 session_options->data_channel_type = data_channel_type();
3791 }
3792
Steve Antondcc3c022017-12-22 16:02:54 -08003793 // Apply ICE renomination flag.
3794 for (auto& options : session_options->media_description_options) {
3795 options.transport_options.enable_ice_renomination =
3796 configuration_.enable_ice_renomination;
3797 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003798
3799 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003800 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003801 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003802}
3803
Steve Antondcc3c022017-12-22 16:02:54 -08003804void PeerConnection::GetOptionsForPlanBAnswer(
3805 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003806 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003807 // Figure out transceiver directional preferences.
3808 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3809 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3810
3811 // By default, generate sendrecv/recvonly m= sections. The direction is also
3812 // restricted by the direction in the offer.
3813 bool recv_audio = true;
3814 bool recv_video = true;
3815
3816 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003817 if (offer_answer_options.offer_to_receive_audio !=
3818 RTCOfferAnswerOptions::kUndefined) {
3819 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003820 }
Steve Antondcc3c022017-12-22 16:02:54 -08003821 if (offer_answer_options.offer_to_receive_video !=
3822 RTCOfferAnswerOptions::kUndefined) {
3823 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003824 }
3825
3826 rtc::Optional<size_t> audio_index;
3827 rtc::Optional<size_t> video_index;
3828 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003829
3830 // Generate m= sections that match those in the offer.
3831 // Note that mediasession.cc will handle intersection our preferred
3832 // direction with the offered direction.
3833 GenerateMediaDescriptionOptions(
3834 remote_description(),
3835 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3836 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3837 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003838
3839 cricket::MediaDescriptionOptions* audio_media_description_options =
3840 !audio_index ? nullptr
3841 : &session_options->media_description_options[*audio_index];
3842 cricket::MediaDescriptionOptions* video_media_description_options =
3843 !video_index ? nullptr
3844 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003845
Steve Anton4171afb2017-11-20 10:20:22 -08003846 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003847 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003848}
zhihuangaf388472016-11-02 16:49:48 -07003849
Steve Antondcc3c022017-12-22 16:02:54 -08003850void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3851 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3852 cricket::MediaSessionOptions* session_options) {
3853 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3854 // Answers) and 5.3.2 (Subsequent Answers).
3855 RTC_DCHECK(remote_description());
3856 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3857 for (const ContentInfo& content :
3858 remote_description()->description()->contents()) {
3859 cricket::MediaType media_type = content.media_description()->type();
3860 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3861 media_type == cricket::MEDIA_TYPE_VIDEO) {
3862 auto transceiver = GetAssociatedTransceiver(content.name);
3863 RTC_CHECK(transceiver);
3864 session_options->media_description_options.push_back(
3865 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3866 } else {
3867 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003868 // Reject all data sections if data channels are disabled.
3869 // Reject a data section if it has already been rejected.
3870 // Reject all data sections except for the first one.
3871 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3872 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003873 session_options->media_description_options.push_back(
3874 GetMediaDescriptionOptionsForRejectedData(content.name));
3875 } else {
3876 session_options->media_description_options.push_back(
3877 GetMediaDescriptionOptionsForActiveData(content.name));
3878 }
Steve Antondcc3c022017-12-22 16:02:54 -08003879 }
3880 }
htaa2a49d92016-03-04 02:51:39 -08003881}
3882
zhihuang1c378ed2017-08-17 14:10:50 -07003883void PeerConnection::GenerateMediaDescriptionOptions(
3884 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003885 RtpTransceiverDirection audio_direction,
3886 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003887 rtc::Optional<size_t>* audio_index,
3888 rtc::Optional<size_t>* video_index,
3889 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003890 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003891 for (const cricket::ContentInfo& content :
3892 session_desc->description()->contents()) {
3893 if (IsAudioContent(&content)) {
3894 // If we already have an audio m= section, reject this extra one.
3895 if (*audio_index) {
3896 session_options->media_description_options.push_back(
3897 cricket::MediaDescriptionOptions(
3898 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003899 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003900 } else {
3901 session_options->media_description_options.push_back(
3902 cricket::MediaDescriptionOptions(
3903 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003904 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003905 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003906 }
3907 } else if (IsVideoContent(&content)) {
3908 // If we already have an video m= section, reject this extra one.
3909 if (*video_index) {
3910 session_options->media_description_options.push_back(
3911 cricket::MediaDescriptionOptions(
3912 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003913 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003914 } else {
3915 session_options->media_description_options.push_back(
3916 cricket::MediaDescriptionOptions(
3917 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003918 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003919 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003920 }
3921 } else {
3922 RTC_DCHECK(IsDataContent(&content));
3923 // If we already have an data m= section, reject this extra one.
3924 if (*data_index) {
3925 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003926 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003927 } else {
3928 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003929 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003930 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003931 }
3932 }
htaa2a49d92016-03-04 02:51:39 -08003933 }
deadbeefab9b2d12015-10-14 11:33:11 -07003934}
3935
Steve Antonfa2260d2017-12-28 16:38:23 -08003936cricket::MediaDescriptionOptions
3937PeerConnection::GetMediaDescriptionOptionsForActiveData(
3938 const std::string& mid) const {
3939 // Direction for data sections is meaningless, but legacy endpoints might
3940 // expect sendrecv.
3941 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3942 RtpTransceiverDirection::kSendRecv,
3943 /*stopped=*/false);
3944 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3945 return options;
3946}
3947
3948cricket::MediaDescriptionOptions
3949PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3950 const std::string& mid) const {
3951 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3952 RtpTransceiverDirection::kInactive,
3953 /*stopped=*/true);
3954 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3955 return options;
3956}
3957
3958rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3959 switch (data_channel_type_) {
3960 case cricket::DCT_RTP:
3961 if (!rtp_data_channel_) {
3962 return rtc::nullopt;
3963 }
3964 return rtp_data_channel_->content_name();
3965 case cricket::DCT_SCTP:
3966 return sctp_content_name_;
3967 default:
3968 return rtc::nullopt;
3969 }
3970}
3971
Steve Anton4171afb2017-11-20 10:20:22 -08003972void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3973 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3974 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003975 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003976}
3977
Steve Anton4171afb2017-11-20 10:20:22 -08003978void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003979 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003980 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003981 cricket::MediaType media_type,
3982 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003983 std::vector<RtpSenderInfo>* current_senders =
3984 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003985
Steve Anton4171afb2017-11-20 10:20:22 -08003986 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003987 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003988 for (auto sender_it = current_senders->begin();
3989 sender_it != current_senders->end();
3990 /* incremented manually */) {
3991 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003992 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003993 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003994 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003995 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003996 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003997 sender_exists) {
3998 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003999 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004000 OnRemoteSenderRemoved(info, media_type);
4001 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004002 }
4003 }
4004
Steve Anton4171afb2017-11-20 10:20:22 -08004005 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004006 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08004007 // |params.id| is the sender id and the stream id uses the first of
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004008 // |params.stream_ids|.
4009 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
Seth Hampson845e8782018-03-02 11:34:10 -08004010 const std::string& stream_id =
4011 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08004012 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004013 uint32_t ssrc = params.first_ssrc();
4014
4015 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004016 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004017 if (!stream) {
4018 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004019 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004020 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004021 remote_streams_->AddStream(stream);
4022 new_streams->AddStream(stream);
4023 }
4024
Steve Anton4171afb2017-11-20 10:20:22 -08004025 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004026 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004027 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004028 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004029 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004030 }
4031 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004032
Steve Anton4171afb2017-11-20 10:20:22 -08004033 // Add default sender if necessary.
4034 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004035 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004036 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004037 if (!default_stream) {
4038 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004039 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004040 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004041 remote_streams_->AddStream(default_stream);
4042 new_streams->AddStream(default_stream);
4043 }
Steve Anton4171afb2017-11-20 10:20:22 -08004044 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4045 ? kDefaultAudioSenderId
4046 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004047 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004048 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004049 if (!default_sender_info) {
4050 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004051 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004052 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004053 }
4054 }
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
Steve Anton4171afb2017-11-20 10:20:22 -08004057void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4058 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004059 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004060
4061 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004062 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004063 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004064 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004065 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004066 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004067 }
4068}
4069
Steve Anton4171afb2017-11-20 10:20:22 -08004070void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4071 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004072 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004073
Henrik Boström933d8b02017-10-10 10:05:16 -07004074 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004075 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004076 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4077 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004078 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004079 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004080 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004081 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004082 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004083 }
4084 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004085 // Stopping or destroying a VideoRtpReceiver will end the
4086 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004087 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004088 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004089 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004090 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004091 // There's no guarantee the track is still available, e.g. the track may
4092 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004093 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004094 }
4095 } else {
nisseede5da42017-01-12 05:15:36 -08004096 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004097 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004098 if (receiver) {
4099 observer_->OnRemoveTrack(receiver);
4100 }
deadbeefab9b2d12015-10-14 11:33:11 -07004101}
4102
4103void PeerConnection::UpdateEndedRemoteMediaStreams() {
4104 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4105 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4106 MediaStreamInterface* stream = remote_streams_->at(i);
4107 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4108 streams_to_remove.push_back(stream);
4109 }
4110 }
4111
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004112 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004113 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004114 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004115 }
4116}
4117
Steve Anton4171afb2017-11-20 10:20:22 -08004118void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004119 const std::vector<cricket::StreamParams>& streams,
4120 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004121 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004122
Seth Hampson845e8782018-03-02 11:34:10 -08004123 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004124 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004125 for (auto sender_it = current_senders->begin();
4126 sender_it != current_senders->end();
4127 /* incremented manually */) {
4128 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004129 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004130 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4131 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004132 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004133 OnLocalSenderRemoved(info, media_type);
4134 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004135 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004136 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004137 }
4138 }
4139
Steve Anton4171afb2017-11-20 10:20:22 -08004140 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004141 for (const cricket::StreamParams& params : streams) {
4142 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004143 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004144 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004145 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004146 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004147 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004148 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004149 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004150 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004151 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004152 }
4153 }
4154}
4155
Steve Anton4171afb2017-11-20 10:20:22 -08004156void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4157 cricket::MediaType media_type) {
4158 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004159 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004160 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4161 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004162 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004163 return;
4164 }
4165
deadbeeffac06552015-11-25 11:26:01 -08004166 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004167 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004168 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004169 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004170 }
deadbeeffac06552015-11-25 11:26:01 -08004171
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004172 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004173 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004174}
4175
Steve Anton4171afb2017-11-20 10:20:22 -08004176void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4177 cricket::MediaType media_type) {
4178 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004179 if (!sender) {
4180 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004181 // SessionDescriptions has been renegotiated.
4182 return;
4183 }
deadbeeffac06552015-11-25 11:26:01 -08004184
4185 // A sender has been removed from the SessionDescription but it's still
4186 // associated with the PeerConnection. This only occurs if the SDP doesn't
4187 // match with the calls to CreateSender, AddStream and RemoveStream.
4188 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004189 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004190 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004191 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004192 }
deadbeeffac06552015-11-25 11:26:01 -08004193
Steve Anton4171afb2017-11-20 10:20:22 -08004194 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004195}
4196
4197void PeerConnection::UpdateLocalRtpDataChannels(
4198 const cricket::StreamParamsVec& streams) {
4199 std::vector<std::string> existing_channels;
4200
4201 // Find new and active data channels.
4202 for (const cricket::StreamParams& params : streams) {
4203 // |it->sync_label| is actually the data channel label. The reason is that
4204 // we use the same naming of data channels as we do for
4205 // MediaStreams and Tracks.
4206 // For MediaStreams, the sync_label is the MediaStream label and the
4207 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004208 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004209 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004210 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004211 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004212 continue;
4213 }
4214 // Set the SSRC the data channel should use for sending.
4215 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4216 existing_channels.push_back(data_channel_it->first);
4217 }
4218
4219 UpdateClosingRtpDataChannels(existing_channels, true);
4220}
4221
4222void PeerConnection::UpdateRemoteRtpDataChannels(
4223 const cricket::StreamParamsVec& streams) {
4224 std::vector<std::string> existing_channels;
4225
4226 // Find new and active data channels.
4227 for (const cricket::StreamParams& params : streams) {
4228 // The data channel label is either the mslabel or the SSRC if the mslabel
4229 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004230 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004231 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004232 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004233 auto data_channel_it = rtp_data_channels_.find(label);
4234 if (data_channel_it == rtp_data_channels_.end()) {
4235 // This is a new data channel.
4236 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4237 } else {
4238 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4239 }
4240 existing_channels.push_back(label);
4241 }
4242
4243 UpdateClosingRtpDataChannels(existing_channels, false);
4244}
4245
4246void PeerConnection::UpdateClosingRtpDataChannels(
4247 const std::vector<std::string>& active_channels,
4248 bool is_local_update) {
4249 auto it = rtp_data_channels_.begin();
4250 while (it != rtp_data_channels_.end()) {
4251 DataChannel* data_channel = it->second;
4252 if (std::find(active_channels.begin(), active_channels.end(),
4253 data_channel->label()) != active_channels.end()) {
4254 ++it;
4255 continue;
4256 }
4257
4258 if (is_local_update) {
4259 data_channel->SetSendSsrc(0);
4260 } else {
4261 data_channel->RemotePeerRequestClose();
4262 }
4263
4264 if (data_channel->state() == DataChannel::kClosed) {
4265 rtp_data_channels_.erase(it);
4266 it = rtp_data_channels_.begin();
4267 } else {
4268 ++it;
4269 }
4270 }
4271}
4272
4273void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4274 uint32_t remote_ssrc) {
4275 rtc::scoped_refptr<DataChannel> channel(
4276 InternalCreateDataChannel(label, nullptr));
4277 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004278 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004279 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004280 return;
4281 }
4282 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004283 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4284 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004285 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004286}
4287
4288rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4289 const std::string& label,
4290 const InternalDataChannelInit* config) {
4291 if (IsClosed()) {
4292 return nullptr;
4293 }
Steve Anton75737c02017-11-06 10:37:17 -08004294 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004295 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004296 << "InternalCreateDataChannel: Data is not supported in this call.";
4297 return nullptr;
4298 }
4299 InternalDataChannelInit new_config =
4300 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004301 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004302 if (new_config.id < 0) {
4303 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004304 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004305 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004306 RTC_LOG(LS_ERROR)
4307 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004308 return nullptr;
4309 }
4310 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004312 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004313 return nullptr;
4314 }
4315 }
4316
Steve Anton75737c02017-11-06 10:37:17 -08004317 rtc::scoped_refptr<DataChannel> channel(
4318 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004319 if (!channel) {
4320 sid_allocator_.ReleaseSid(new_config.id);
4321 return nullptr;
4322 }
4323
4324 if (channel->data_channel_type() == cricket::DCT_RTP) {
4325 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004326 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4327 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004328 return nullptr;
4329 }
4330 rtp_data_channels_[channel->label()] = channel;
4331 } else {
4332 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4333 sctp_data_channels_.push_back(channel);
4334 channel->SignalClosed.connect(this,
4335 &PeerConnection::OnSctpDataChannelClosed);
4336 }
4337
Steve Anton2d8609c2018-01-23 16:38:46 -08004338 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004339 return channel;
4340}
4341
4342bool PeerConnection::HasDataChannels() const {
4343 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4344}
4345
4346void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4347 for (const auto& channel : sctp_data_channels_) {
4348 if (channel->id() < 0) {
4349 int sid;
4350 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004351 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004352 continue;
4353 }
4354 channel->SetSctpSid(sid);
4355 }
4356 }
4357}
4358
4359void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004360 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004361 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4362 ++it) {
4363 if (it->get() == channel) {
4364 if (channel->id() >= 0) {
4365 sid_allocator_.ReleaseSid(channel->id());
4366 }
deadbeefbd292462015-12-14 18:15:29 -08004367 // Since this method is triggered by a signal from the DataChannel,
4368 // we can't free it directly here; we need to free it asynchronously.
4369 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004370 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004371 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4372 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004373 return;
4374 }
4375 }
4376}
4377
deadbeefab9b2d12015-10-14 11:33:11 -07004378void PeerConnection::OnDataChannelDestroyed() {
4379 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4380 // DataChannel may callback to us and try to modify the list.
4381 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4382 temp_rtp_dcs.swap(rtp_data_channels_);
4383 for (const auto& kv : temp_rtp_dcs) {
4384 kv.second->OnTransportChannelDestroyed();
4385 }
4386
4387 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4388 temp_sctp_dcs.swap(sctp_data_channels_);
4389 for (const auto& channel : temp_sctp_dcs) {
4390 channel->OnTransportChannelDestroyed();
4391 }
4392}
4393
4394void PeerConnection::OnDataChannelOpenMessage(
4395 const std::string& label,
4396 const InternalDataChannelInit& config) {
4397 rtc::scoped_refptr<DataChannel> channel(
4398 InternalCreateDataChannel(label, &config));
4399 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004400 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004401 return;
4402 }
4403
deadbeefa601f5c2016-06-06 14:27:39 -07004404 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4405 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004406 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004407}
4408
Steve Anton4171afb2017-11-20 10:20:22 -08004409rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4410PeerConnection::GetAudioTransceiver() const {
4411 // This method only works with Plan B SDP, where there is a single
4412 // audio/video transceiver.
4413 RTC_DCHECK(!IsUnifiedPlan());
4414 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004415 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004416 return transceiver;
4417 }
4418 }
4419 RTC_NOTREACHED();
4420 return nullptr;
4421}
4422
4423rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4424PeerConnection::GetVideoTransceiver() const {
4425 // This method only works with Plan B SDP, where there is a single
4426 // audio/video transceiver.
4427 RTC_DCHECK(!IsUnifiedPlan());
4428 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004429 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004430 return transceiver;
4431 }
4432 }
4433 RTC_NOTREACHED();
4434 return nullptr;
4435}
4436
4437// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4438// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004439bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004440 switch (type) {
4441 case cricket::MEDIA_TYPE_AUDIO:
4442 return !GetAudioTransceiver()->internal()->senders().empty();
4443 case cricket::MEDIA_TYPE_VIDEO:
4444 return !GetVideoTransceiver()->internal()->senders().empty();
4445 case cricket::MEDIA_TYPE_DATA:
4446 return false;
4447 }
4448 RTC_NOTREACHED();
4449 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004450}
4451
Steve Anton4171afb2017-11-20 10:20:22 -08004452rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4453PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4454 for (auto transceiver : transceivers_) {
4455 for (auto sender : transceiver->internal()->senders()) {
4456 if (sender->track() == track) {
4457 return sender;
4458 }
4459 }
4460 }
4461 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004462}
4463
Steve Anton4171afb2017-11-20 10:20:22 -08004464rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4465PeerConnection::FindSenderById(const std::string& sender_id) const {
4466 for (auto transceiver : transceivers_) {
4467 for (auto sender : transceiver->internal()->senders()) {
4468 if (sender->id() == sender_id) {
4469 return sender;
4470 }
4471 }
4472 }
4473 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004474}
4475
Steve Anton4171afb2017-11-20 10:20:22 -08004476rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4477PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4478 for (auto transceiver : transceivers_) {
4479 for (auto receiver : transceiver->internal()->receivers()) {
4480 if (receiver->id() == receiver_id) {
4481 return receiver;
4482 }
4483 }
4484 }
4485 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004486}
4487
Steve Anton4171afb2017-11-20 10:20:22 -08004488std::vector<PeerConnection::RtpSenderInfo>*
4489PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4490 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4491 media_type == cricket::MEDIA_TYPE_VIDEO);
4492 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4493 ? &remote_audio_sender_infos_
4494 : &remote_video_sender_infos_;
4495}
4496
4497std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004498 cricket::MediaType media_type) {
4499 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4500 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004501 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4502 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004503}
4504
Steve Anton4171afb2017-11-20 10:20:22 -08004505const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4506 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004507 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004508 const std::string sender_id) const {
4509 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004510 if (sender_info.stream_id == stream_id &&
4511 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004512 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004513 }
4514 }
4515 return nullptr;
4516}
4517
4518DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4519 for (const auto& channel : sctp_data_channels_) {
4520 if (channel->id() == sid) {
4521 return channel;
4522 }
4523 }
4524 return nullptr;
4525}
4526
deadbeef91dd5672016-05-18 16:55:30 -07004527bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004528 const RTCConfiguration& configuration) {
4529 cricket::ServerAddresses stun_servers;
4530 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004531 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4532 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004533 return false;
4534 }
4535
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004536 port_allocator_->Initialize();
4537
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004538 // To handle both internal and externally created port allocator, we will
4539 // enable BUNDLE here.
4540 int portallocator_flags = port_allocator_->flags();
4541 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004542 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4543 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004544 // If the disable-IPv6 flag was specified, we'll not override it
4545 // by experiment.
4546 if (configuration.disable_ipv6) {
4547 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004548 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4549 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004550 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4551 }
4552
zhihuangb09b3f92017-03-07 14:40:51 -08004553 if (configuration.disable_ipv6_on_wifi) {
4554 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004555 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004556 }
4557
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004558 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4559 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004560 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004561 }
4562
honghaiz60347052016-05-31 18:29:12 -07004563 if (configuration.candidate_network_policy ==
4564 kCandidateNetworkPolicyLowCost) {
4565 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004566 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004567 }
4568
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004569 if (configuration.disable_link_local_networks) {
4570 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4571 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4572 }
4573
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004574 port_allocator_->set_flags(portallocator_flags);
4575 // No step delay is used while allocating ports.
4576 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4577 port_allocator_->set_candidate_filter(
4578 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004579 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004580
4581 // Call this last since it may create pooled allocator sessions using the
4582 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004583 port_allocator_->SetConfiguration(
4584 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4585 configuration.prune_turn_ports, configuration.turn_customizer,
4586 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004587 return true;
4588}
4589
deadbeef91dd5672016-05-18 16:55:30 -07004590bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004591 const cricket::ServerAddresses& stun_servers,
4592 const std::vector<cricket::RelayServerConfig>& turn_servers,
4593 IceTransportsType type,
4594 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004595 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004596 webrtc::TurnCustomizer* turn_customizer,
4597 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004598 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004599 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004600 // Call this last since it may create pooled allocator sessions using the
4601 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004602 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004603 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004604 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004605}
4606
Steve Antonba818672017-11-06 10:21:57 -08004607cricket::ChannelManager* PeerConnection::channel_manager() const {
4608 return factory_->channel_manager();
4609}
4610
4611MetricsObserverInterface* PeerConnection::metrics_observer() const {
4612 return uma_observer_;
4613}
4614
Elad Alon99c3fe52017-10-13 16:29:40 +02004615bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004616 std::unique_ptr<RtcEventLogOutput> output,
4617 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004618 if (!event_log_) {
4619 return false;
4620 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004621 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004622}
4623
4624void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004625 if (event_log_) {
4626 event_log_->StopLogging();
4627 }
ivoc14d5dbe2016-07-04 07:06:55 -07004628}
nisseeaabdf62017-05-05 02:23:02 -07004629
Steve Anton75737c02017-11-06 10:37:17 -08004630cricket::BaseChannel* PeerConnection::GetChannel(
4631 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004632 for (auto transceiver : transceivers_) {
4633 cricket::BaseChannel* channel = transceiver->internal()->channel();
4634 if (channel && channel->content_name() == content_name) {
4635 return channel;
4636 }
Steve Anton75737c02017-11-06 10:37:17 -08004637 }
4638 if (rtp_data_channel() &&
4639 rtp_data_channel()->content_name() == content_name) {
4640 return rtp_data_channel();
4641 }
4642 return nullptr;
4643}
4644
4645bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4646 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004647 RTC_LOG(LS_INFO)
4648 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004649 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004650 return false;
4651 }
4652 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004653 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004654 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004655 return false;
4656 }
4657
4658 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4659}
4660
4661bool PeerConnection::GetSslRole(const std::string& content_name,
4662 rtc::SSLRole* role) {
4663 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004664 RTC_LOG(LS_INFO)
4665 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004666 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004667 return false;
4668 }
4669
4670 return transport_controller_->GetSslRole(GetTransportName(content_name),
4671 role);
4672}
4673
Steve Antonf8470812017-12-04 10:46:21 -08004674void PeerConnection::SetSessionError(SessionError error,
4675 const std::string& error_desc) {
4676 RTC_DCHECK_RUN_ON(signaling_thread());
4677 if (error != session_error_) {
4678 session_error_ = error;
4679 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004680 }
4681}
4682
Steve Anton3828c062017-12-06 10:34:51 -08004683RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004684 cricket::ContentSource source) {
4685 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004686
4687 // If there's already a pending error then no state transition should happen.
4688 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004689 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004690
4691 // If this is an answer then we know whether to BUNDLE or not. If both the
4692 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004693 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004694 const cricket::ContentGroup* local_bundle =
4695 local_description()->description()->GetGroupByName(
4696 cricket::GROUP_TYPE_BUNDLE);
4697 const cricket::ContentGroup* remote_bundle =
4698 remote_description()->description()->GetGroupByName(
4699 cricket::GROUP_TYPE_BUNDLE);
4700 if (local_bundle && remote_bundle) {
4701 // The answerer decides the transport to bundle on.
4702 const cricket::ContentGroup* answer_bundle =
4703 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4704 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4706 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004707 }
4708 }
Steve Anton75737c02017-11-06 10:37:17 -08004709 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004710
4711 // Only push down the transport description after potentially enabling BUNDLE;
4712 // we don't want to push down a description on a transport about to be
4713 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004714 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004715 if (!error.ok()) {
4716 return error;
4717 }
4718
4719 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004720 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004721 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004722 }
4723
4724 // Update the signaling state according to the specified state machine (see
4725 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004726 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004727 ChangeSignalingState(source == cricket::CS_LOCAL
4728 ? PeerConnectionInterface::kHaveLocalOffer
4729 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004730 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004731 ChangeSignalingState(source == cricket::CS_LOCAL
4732 ? PeerConnectionInterface::kHaveLocalPrAnswer
4733 : PeerConnectionInterface::kHaveRemotePrAnswer);
4734 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004735 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004736 ChangeSignalingState(PeerConnectionInterface::kStable);
4737 }
4738
4739 // Update internal objects according to the session description's media
4740 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004741 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004742 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004743 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004744 }
4745
Steve Anton8a006912017-12-04 15:25:56 -08004746 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004747}
4748
Steve Anton8a006912017-12-04 15:25:56 -08004749RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004750 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004751 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004752 const SessionDescriptionInterface* sdesc =
4753 (source == cricket::CS_LOCAL ? local_description()
4754 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004755 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004756
4757 // Push down the new SDP media section for each audio/video transceiver.
4758 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004759 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004760 FindMediaSectionForTransceiver(transceiver, sdesc);
4761 cricket::BaseChannel* channel = transceiver->internal()->channel();
4762 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004763 continue;
4764 }
4765 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004766 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004767 if (!content_desc) {
4768 continue;
4769 }
4770 std::string error;
4771 bool success =
4772 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004773 ? channel->SetLocalContent(content_desc, type, &error)
4774 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004775 if (!success) {
4776 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4777 }
4778 }
4779
4780 // If using the RtpDataChannel, push down the new SDP section for it too.
4781 if (rtp_data_channel_) {
4782 const ContentInfo* data_content =
4783 cricket::GetFirstDataContent(sdesc->description());
4784 if (data_content && !data_content->rejected) {
4785 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004786 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004787 if (data_desc) {
4788 std::string error;
4789 bool success =
4790 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004791 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4792 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004793 &error);
4794 if (!success) {
4795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4796 std::move(error));
4797 }
Steve Anton75737c02017-11-06 10:37:17 -08004798 }
4799 }
4800 }
Steve Antoned10bd92017-12-05 10:52:59 -08004801
Steve Anton75737c02017-11-06 10:37:17 -08004802 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4803 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4804 if (sctp_transport_ && local_description() && remote_description() &&
4805 cricket::GetFirstDataContent(local_description()->description()) &&
4806 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004807 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004808 RTC_FROM_HERE,
4809 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004810 if (!success) {
4811 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4812 "Failed to push down SCTP parameters.");
4813 }
Steve Anton75737c02017-11-06 10:37:17 -08004814 }
Steve Antoned10bd92017-12-05 10:52:59 -08004815
Steve Anton8a006912017-12-04 15:25:56 -08004816 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004817}
4818
4819bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4820 RTC_DCHECK(network_thread()->IsCurrent());
4821 RTC_DCHECK(local_description());
4822 RTC_DCHECK(remote_description());
4823 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4824 // When we support "max-message-size", that would also be pushed down here.
4825 return sctp_transport_->Start(
4826 GetSctpPort(local_description()->description()),
4827 GetSctpPort(remote_description()->description()));
4828}
4829
Steve Anton8a006912017-12-04 15:25:56 -08004830RTCError PeerConnection::PushdownTransportDescription(
4831 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004832 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004833 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004834
Steve Anton8a006912017-12-04 15:25:56 -08004835 const SessionDescriptionInterface* sdesc =
4836 (source == cricket::CS_LOCAL ? local_description()
4837 : remote_description());
4838 RTC_DCHECK(sdesc);
4839 for (const cricket::TransportInfo& tinfo :
4840 sdesc->description()->transport_infos()) {
4841 std::string error;
4842 bool success;
4843 if (source == cricket::CS_LOCAL) {
4844 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004845 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004846 } else {
4847 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004848 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004849 }
4850 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004851 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4852 "Failed to push down transport description for " +
4853 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004854 }
4855 }
4856
Steve Anton8a006912017-12-04 15:25:56 -08004857 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004858}
4859
4860bool PeerConnection::GetTransportDescription(
4861 const SessionDescription* description,
4862 const std::string& content_name,
4863 cricket::TransportDescription* tdesc) {
4864 if (!description || !tdesc) {
4865 return false;
4866 }
4867 const TransportInfo* transport_info =
4868 description->GetTransportInfoByName(content_name);
4869 if (!transport_info) {
4870 return false;
4871 }
4872 *tdesc = transport_info->description;
4873 return true;
4874}
4875
4876bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4877 const std::string* first_content_name = bundle.FirstContentName();
4878 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004879 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004880 return false;
4881 }
4882 const std::string& transport_name = *first_content_name;
4883
4884 auto maybe_set_transport = [this, bundle,
4885 transport_name](cricket::BaseChannel* ch) {
4886 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004887 return;
Steve Anton75737c02017-11-06 10:37:17 -08004888 }
4889
4890 std::string old_transport_name = ch->transport_name();
4891 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004892 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4893 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004894 return;
Steve Anton75737c02017-11-06 10:37:17 -08004895 }
4896
4897 cricket::DtlsTransportInternal* rtp_dtls_transport =
4898 transport_controller_->CreateDtlsTransport(
4899 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4900 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4901 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4902 if (need_rtcp) {
4903 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4904 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4905 }
4906
4907 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004908 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4909 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004910 transport_controller_->DestroyDtlsTransport(
4911 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4912 // If the channel needs rtcp, it means that the channel used to have a
4913 // rtcp transport which needs to be deleted now.
4914 if (need_rtcp) {
4915 transport_controller_->DestroyDtlsTransport(
4916 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4917 }
Steve Anton75737c02017-11-06 10:37:17 -08004918 };
4919
Steve Antoned10bd92017-12-05 10:52:59 -08004920 for (auto transceiver : transceivers_) {
4921 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004922 }
Steve Antoned10bd92017-12-05 10:52:59 -08004923 maybe_set_transport(rtp_data_channel_);
4924
Steve Anton75737c02017-11-06 10:37:17 -08004925 // For SCTP, transport creation/deletion happens here instead of in the
4926 // object itself.
4927 if (sctp_transport_) {
4928 RTC_DCHECK(sctp_transport_name_);
4929 RTC_DCHECK(sctp_content_name_);
4930 if (transport_name != *sctp_transport_name_ &&
4931 bundle.HasContentName(*sctp_content_name_)) {
4932 network_thread()->Invoke<void>(
4933 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4934 transport_name));
4935 }
4936 }
4937
4938 return true;
4939}
4940
Steve Anton75737c02017-11-06 10:37:17 -08004941cricket::IceConfig PeerConnection::ParseIceConfig(
4942 const PeerConnectionInterface::RTCConfiguration& config) const {
4943 cricket::ContinualGatheringPolicy gathering_policy;
4944 // TODO(honghaiz): Add the third continual gathering policy in
4945 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4946 switch (config.continual_gathering_policy) {
4947 case PeerConnectionInterface::GATHER_ONCE:
4948 gathering_policy = cricket::GATHER_ONCE;
4949 break;
4950 case PeerConnectionInterface::GATHER_CONTINUALLY:
4951 gathering_policy = cricket::GATHER_CONTINUALLY;
4952 break;
4953 default:
4954 RTC_NOTREACHED();
4955 gathering_policy = cricket::GATHER_ONCE;
4956 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004957
Steve Anton75737c02017-11-06 10:37:17 -08004958 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004959 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4960 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004961 ice_config.prioritize_most_likely_candidate_pairs =
4962 config.prioritize_most_likely_ice_candidate_pairs;
4963 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004964 RTCConfigurationToIceConfigOptionalInt(
4965 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004966 ice_config.continual_gathering_policy = gathering_policy;
4967 ice_config.presume_writable_when_fully_relayed =
4968 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004969 ice_config.ice_check_interval_strong_connectivity =
4970 config.ice_check_interval_strong_connectivity;
4971 ice_config.ice_check_interval_weak_connectivity =
4972 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004973 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004974 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004975 ice_config.regather_all_networks_interval_range =
4976 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004977 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004978 return ice_config;
4979}
4980
Steve Anton75737c02017-11-06 10:37:17 -08004981bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4982 std::string* track_id) {
4983 if (!local_description()) {
4984 return false;
4985 }
4986 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4987 track_id);
4988}
4989
4990bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4991 std::string* track_id) {
4992 if (!remote_description()) {
4993 return false;
4994 }
4995 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4996 track_id);
4997}
4998
4999bool PeerConnection::SendData(const cricket::SendDataParams& params,
5000 const rtc::CopyOnWriteBuffer& payload,
5001 cricket::SendDataResult* result) {
5002 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005003 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005004 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005005 return false;
5006 }
5007 return rtp_data_channel_
5008 ? rtp_data_channel_->SendData(params, payload, result)
5009 : network_thread()->Invoke<bool>(
5010 RTC_FROM_HERE,
5011 Bind(&cricket::SctpTransportInternal::SendData,
5012 sctp_transport_.get(), params, payload, result));
5013}
5014
5015bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5016 if (!rtp_data_channel_ && !sctp_transport_) {
5017 // Don't log an error here, because DataChannels are expected to call
5018 // ConnectDataChannel in this state. It's the only way to initially tell
5019 // whether or not the underlying transport is ready.
5020 return false;
5021 }
5022 if (rtp_data_channel_) {
5023 rtp_data_channel_->SignalReadyToSendData.connect(
5024 webrtc_data_channel, &DataChannel::OnChannelReady);
5025 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5026 &DataChannel::OnDataReceived);
5027 } else {
5028 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5029 &DataChannel::OnChannelReady);
5030 SignalSctpDataReceived.connect(webrtc_data_channel,
5031 &DataChannel::OnDataReceived);
5032 SignalSctpStreamClosedRemotely.connect(
5033 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5034 }
5035 return true;
5036}
5037
5038void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5039 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005040 RTC_LOG(LS_ERROR)
5041 << "DisconnectDataChannel called when rtp_data_channel_ and "
5042 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005043 return;
5044 }
5045 if (rtp_data_channel_) {
5046 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5047 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5048 } else {
5049 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5050 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5051 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5052 }
5053}
5054
5055void PeerConnection::AddSctpDataStream(int sid) {
5056 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005057 RTC_LOG(LS_ERROR)
5058 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005059 return;
5060 }
5061 network_thread()->Invoke<void>(
5062 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5063 sctp_transport_.get(), sid));
5064}
5065
5066void PeerConnection::RemoveSctpDataStream(int sid) {
5067 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005068 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005069 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005070 return;
5071 }
5072 network_thread()->Invoke<void>(
5073 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5074 sctp_transport_.get(), sid));
5075}
5076
5077bool PeerConnection::ReadyToSendData() const {
5078 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5079 sctp_ready_to_send_data_;
5080}
5081
Qingsi Wang72a43a12018-02-20 16:03:18 -08005082cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5083 cricket::CandidateStatsList candidate_states_list;
5084 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5085 return candidate_states_list;
5086}
5087
Steve Anton5dfde182018-02-06 10:34:40 -08005088std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5089 const {
5090 std::map<std::string, std::string> transport_names_by_mid;
5091 for (auto transceiver : transceivers_) {
5092 cricket::BaseChannel* channel = transceiver->internal()->channel();
5093 if (channel) {
5094 transport_names_by_mid[channel->content_name()] =
5095 channel->transport_name();
5096 }
Steve Anton75737c02017-11-06 10:37:17 -08005097 }
Steve Anton5dfde182018-02-06 10:34:40 -08005098 if (rtp_data_channel_) {
5099 transport_names_by_mid[rtp_data_channel_->content_name()] =
5100 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
5102 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005103 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005104 }
Steve Anton5dfde182018-02-06 10:34:40 -08005105 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005106}
5107
Steve Anton5dfde182018-02-06 10:34:40 -08005108std::map<std::string, cricket::TransportStats>
5109PeerConnection::GetTransportStatsByNames(
5110 const std::set<std::string>& transport_names) {
5111 if (!network_thread()->IsCurrent()) {
5112 return network_thread()
5113 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5114 RTC_FROM_HERE,
5115 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005116 }
Steve Anton5dfde182018-02-06 10:34:40 -08005117 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5118 for (const std::string& transport_name : transport_names) {
5119 cricket::TransportStats transport_stats;
5120 bool success =
5121 transport_controller_->GetStats(transport_name, &transport_stats);
5122 if (success) {
5123 transport_stats_by_name[transport_name] = std::move(transport_stats);
5124 } else {
5125 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5126 << transport_name;
5127 }
5128 }
5129 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005130}
5131
5132bool PeerConnection::GetLocalCertificate(
5133 const std::string& transport_name,
5134 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5135 return transport_controller_->GetLocalCertificate(transport_name,
5136 certificate);
5137}
5138
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005139std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005140 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005141 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005142}
5143
5144cricket::DataChannelType PeerConnection::data_channel_type() const {
5145 return data_channel_type_;
5146}
5147
5148bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5149 return pending_ice_restarts_.find(content_name) !=
5150 pending_ice_restarts_.end();
5151}
5152
Steve Anton75737c02017-11-06 10:37:17 -08005153bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5154 return transport_controller_->NeedsIceRestart(content_name);
5155}
5156
5157void PeerConnection::OnCertificateReady(
5158 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5159 transport_controller_->SetLocalCertificate(certificate);
5160}
5161
5162void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005163 SetSessionError(SessionError::kTransport,
5164 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005165}
5166
5167void PeerConnection::OnTransportControllerConnectionState(
5168 cricket::IceConnectionState state) {
5169 switch (state) {
5170 case cricket::kIceConnectionConnecting:
5171 // If the current state is Connected or Completed, then there were
5172 // writable channels but now there are not, so the next state must
5173 // be Disconnected.
5174 // kIceConnectionConnecting is currently used as the default,
5175 // un-connected state by the TransportController, so its only use is
5176 // detecting disconnections.
5177 if (ice_connection_state_ ==
5178 PeerConnectionInterface::kIceConnectionConnected ||
5179 ice_connection_state_ ==
5180 PeerConnectionInterface::kIceConnectionCompleted) {
5181 SetIceConnectionState(
5182 PeerConnectionInterface::kIceConnectionDisconnected);
5183 }
5184 break;
5185 case cricket::kIceConnectionFailed:
5186 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5187 break;
5188 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005189 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005190 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005191 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5192 break;
5193 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005194 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005195 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005196 if (ice_connection_state_ !=
5197 PeerConnectionInterface::kIceConnectionConnected) {
5198 // If jumping directly from "checking" to "connected",
5199 // signal "connected" first.
5200 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5201 }
5202 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5203 if (metrics_observer()) {
5204 ReportTransportStats();
5205 }
5206 break;
5207 default:
5208 RTC_NOTREACHED();
5209 }
5210}
5211
5212void PeerConnection::OnTransportControllerCandidatesGathered(
5213 const std::string& transport_name,
5214 const cricket::Candidates& candidates) {
5215 RTC_DCHECK(signaling_thread()->IsCurrent());
5216 int sdp_mline_index;
5217 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005218 RTC_LOG(LS_ERROR)
5219 << "OnTransportControllerCandidatesGathered: content name "
5220 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005221 return;
5222 }
5223
5224 for (cricket::Candidates::const_iterator citer = candidates.begin();
5225 citer != candidates.end(); ++citer) {
5226 // Use transport_name as the candidate media id.
5227 std::unique_ptr<JsepIceCandidate> candidate(
5228 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5229 if (local_description()) {
5230 mutable_local_description()->AddCandidate(candidate.get());
5231 }
5232 OnIceCandidate(std::move(candidate));
5233 }
5234}
5235
5236void PeerConnection::OnTransportControllerCandidatesRemoved(
5237 const std::vector<cricket::Candidate>& candidates) {
5238 RTC_DCHECK(signaling_thread()->IsCurrent());
5239 // Sanity check.
5240 for (const cricket::Candidate& candidate : candidates) {
5241 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005242 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005243 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005244 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005245 return;
5246 }
5247 }
5248
5249 if (local_description()) {
5250 mutable_local_description()->RemoveCandidates(candidates);
5251 }
5252 OnIceCandidatesRemoved(candidates);
5253}
5254
5255void PeerConnection::OnTransportControllerDtlsHandshakeError(
5256 rtc::SSLHandshakeError error) {
5257 if (metrics_observer()) {
5258 metrics_observer()->IncrementEnumCounter(
5259 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5260 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5261 }
5262}
5263
Steve Antoned10bd92017-12-05 10:52:59 -08005264void PeerConnection::EnableSending() {
5265 for (auto transceiver : transceivers_) {
5266 cricket::BaseChannel* channel = transceiver->internal()->channel();
5267 if (channel && !channel->enabled()) {
5268 channel->Enable(true);
5269 }
Steve Anton75737c02017-11-06 10:37:17 -08005270 }
5271
Steve Anton4171afb2017-11-20 10:20:22 -08005272 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005273 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005274 }
Steve Anton75737c02017-11-06 10:37:17 -08005275}
5276
5277// Returns the media index for a local ice candidate given the content name.
5278bool PeerConnection::GetLocalCandidateMediaIndex(
5279 const std::string& content_name,
5280 int* sdp_mline_index) {
5281 if (!local_description() || !sdp_mline_index) {
5282 return false;
5283 }
5284
5285 bool content_found = false;
5286 const ContentInfos& contents = local_description()->description()->contents();
5287 for (size_t index = 0; index < contents.size(); ++index) {
5288 if (contents[index].name == content_name) {
5289 *sdp_mline_index = static_cast<int>(index);
5290 content_found = true;
5291 break;
5292 }
5293 }
5294 return content_found;
5295}
5296
5297bool PeerConnection::UseCandidatesInSessionDescription(
5298 const SessionDescriptionInterface* remote_desc) {
5299 if (!remote_desc) {
5300 return true;
5301 }
5302 bool ret = true;
5303
5304 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5305 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5306 for (size_t n = 0; n < candidates->count(); ++n) {
5307 const IceCandidateInterface* candidate = candidates->at(n);
5308 bool valid = false;
5309 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5310 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005311 RTC_LOG(LS_INFO)
5312 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005313 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005314 }
5315 continue;
5316 }
5317 ret = UseCandidate(candidate);
5318 if (!ret) {
5319 break;
5320 }
5321 }
5322 }
5323 return ret;
5324}
5325
5326bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5327 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5328 size_t remote_content_size =
5329 remote_description()->description()->contents().size();
5330 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005331 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005332 return false;
5333 }
5334
5335 cricket::ContentInfo content =
5336 remote_description()->description()->contents()[mediacontent_index];
5337 std::vector<cricket::Candidate> candidates;
5338 candidates.push_back(candidate->candidate());
5339 // Invoking BaseSession method to handle remote candidates.
5340 std::string error;
5341 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5342 &error)) {
5343 // Candidates successfully submitted for checking.
5344 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5345 ice_connection_state_ ==
5346 PeerConnectionInterface::kIceConnectionDisconnected) {
5347 // If state is New, then the session has just gotten its first remote ICE
5348 // candidates, so go to Checking.
5349 // If state is Disconnected, the session is re-using old candidates or
5350 // receiving additional ones, so go to Checking.
5351 // If state is Connected, stay Connected.
5352 // TODO(bemasc): If state is Connected, and the new candidates are for a
5353 // newly added transport, then the state actually _should_ move to
5354 // checking. Add a way to distinguish that case.
5355 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5356 }
5357 // TODO(bemasc): If state is Completed, go back to Connected.
5358 } else {
5359 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005360 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005361 }
5362 }
5363 return true;
5364}
5365
5366void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005367 // Destroy video channel first since it may have a pointer to the
5368 // voice channel.
5369 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005370 if (!video_info || video_info->rejected) {
5371 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005372 }
5373
Steve Anton6fec8802017-12-04 10:37:29 -08005374 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5375 if (!audio_info || audio_info->rejected) {
5376 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005377 }
5378
5379 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5380 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005381 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005382 }
5383}
5384
Steve Antoneda6ccd2017-12-04 10:21:55 -08005385std::string PeerConnection::GetTransportNameForMediaSection(
5386 const std::string& mid,
5387 const cricket::ContentGroup* bundle_group) const {
5388 if (!bundle_group) {
5389 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005390 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005391 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005392 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005393 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005394 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005395 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005396 if (!bundle_group->HasContentName(mid)) {
5397 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5398 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005399 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005400 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5401 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005402}
5403
Steve Antondcc3c022017-12-22 16:02:54 -08005404RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5405 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005406 const cricket::ContentGroup* bundle_group = nullptr;
5407 if (configuration_.bundle_policy ==
5408 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005409 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005410 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005411 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5412 "max-bundle configured but session description "
5413 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
5415 }
Steve Antondcc3c022017-12-22 16:02:54 -08005416 return std::move(bundle_group);
5417}
5418
5419RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5420 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5421 if (!bundle_group_or_error.ok()) {
5422 return bundle_group_or_error.MoveError();
5423 }
5424 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005425
Steve Antoneda6ccd2017-12-04 10:21:55 -08005426 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005427 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005428 if (voice && !voice->rejected &&
5429 !GetAudioTransceiver()->internal()->channel()) {
5430 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5431 voice->name,
5432 GetTransportNameForMediaSection(voice->name, bundle_group));
5433 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005434 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5435 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005436 }
5437 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5438 }
5439
Steve Antondcc3c022017-12-22 16:02:54 -08005440 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005441 if (video && !video->rejected &&
5442 !GetVideoTransceiver()->internal()->channel()) {
5443 cricket::VideoChannel* video_channel = CreateVideoChannel(
5444 video->name,
5445 GetTransportNameForMediaSection(video->name, bundle_group));
5446 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005447 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5448 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005449 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005450 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005451 }
5452
Steve Antondcc3c022017-12-22 16:02:54 -08005453 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005454 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5455 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005456 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5457 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005458 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5459 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005460 }
5461 }
5462
Steve Anton8a006912017-12-04 15:25:56 -08005463 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005464}
5465
Steve Anton4171afb2017-11-20 10:20:22 -08005466// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005467cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5468 const std::string& mid,
5469 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005470 cricket::DtlsTransportInternal* rtp_dtls_transport =
5471 transport_controller_->CreateDtlsTransport(
5472 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5473 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5474 if (configuration_.rtcp_mux_policy !=
5475 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5476 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5477 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5478 }
5479
5480 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5481 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005482 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5483 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005484 if (!voice_channel) {
5485 transport_controller_->DestroyDtlsTransport(
5486 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5487 if (rtcp_dtls_transport) {
5488 transport_controller_->DestroyDtlsTransport(
5489 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5490 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005491 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005492 }
Steve Anton75737c02017-11-06 10:37:17 -08005493 voice_channel->SignalRtcpMuxFullyActive.connect(
5494 this, &PeerConnection::DestroyRtcpTransport_n);
5495 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5496 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005497 voice_channel->SignalSentPacket.connect(this,
5498 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005499 if (uma_observer_) {
5500 voice_channel->SetMetricsObserver(uma_observer_);
5501 }
Steve Anton4171afb2017-11-20 10:20:22 -08005502
Steve Antoneda6ccd2017-12-04 10:21:55 -08005503 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005504}
5505
Steve Anton4171afb2017-11-20 10:20:22 -08005506// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005507cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5508 const std::string& mid,
5509 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005510 cricket::DtlsTransportInternal* rtp_dtls_transport =
5511 transport_controller_->CreateDtlsTransport(
5512 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5513 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5514 if (configuration_.rtcp_mux_policy !=
5515 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5516 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5517 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5518 }
5519
5520 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5521 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005522 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5523 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005524
5525 if (!video_channel) {
5526 transport_controller_->DestroyDtlsTransport(
5527 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5528 if (rtcp_dtls_transport) {
5529 transport_controller_->DestroyDtlsTransport(
5530 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5531 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005532 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005533 }
Steve Anton75737c02017-11-06 10:37:17 -08005534 video_channel->SignalRtcpMuxFullyActive.connect(
5535 this, &PeerConnection::DestroyRtcpTransport_n);
5536 video_channel->SignalDtlsSrtpSetupFailure.connect(
5537 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005538 video_channel->SignalSentPacket.connect(this,
5539 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005540 if (uma_observer_) {
5541 video_channel->SetMetricsObserver(uma_observer_);
5542 }
Steve Anton4171afb2017-11-20 10:20:22 -08005543
Steve Antoneda6ccd2017-12-04 10:21:55 -08005544 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005545}
5546
Steve Antoneda6ccd2017-12-04 10:21:55 -08005547bool PeerConnection::CreateDataChannel(const std::string& mid,
5548 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005549 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5550 if (sctp) {
5551 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005552 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005553 << "Trying to create SCTP transport, but didn't compile with "
5554 "SCTP support (HAVE_SCTP)";
5555 return false;
5556 }
5557 if (!network_thread()->Invoke<bool>(
5558 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005559 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005560 return false;
5561 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005562 for (const auto& channel : sctp_data_channels_) {
5563 channel->OnTransportChannelCreated();
5564 }
Steve Anton75737c02017-11-06 10:37:17 -08005565 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005566 cricket::DtlsTransportInternal* rtp_dtls_transport =
5567 transport_controller_->CreateDtlsTransport(
5568 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5569 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5570 if (configuration_.rtcp_mux_policy !=
5571 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5572 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5573 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5574 }
5575
5576 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5577 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005578 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005579
5580 if (!rtp_data_channel_) {
5581 transport_controller_->DestroyDtlsTransport(
5582 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5583 if (rtcp_dtls_transport) {
5584 transport_controller_->DestroyDtlsTransport(
5585 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5586 }
5587 return false;
5588 }
5589
5590 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5591 this, &PeerConnection::DestroyRtcpTransport_n);
5592 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5593 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5594 rtp_data_channel_->SignalSentPacket.connect(
5595 this, &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005596 if (uma_observer_) {
5597 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5598 }
Steve Anton75737c02017-11-06 10:37:17 -08005599 }
5600
Steve Anton75737c02017-11-06 10:37:17 -08005601 return true;
5602}
5603
5604Call::Stats PeerConnection::GetCallStats() {
5605 if (!worker_thread()->IsCurrent()) {
5606 return worker_thread()->Invoke<Call::Stats>(
5607 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5608 }
5609 if (call_) {
5610 return call_->GetStats();
5611 } else {
5612 return Call::Stats();
5613 }
5614}
5615
Steve Anton75737c02017-11-06 10:37:17 -08005616bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5617 const std::string& transport_name) {
5618 RTC_DCHECK(network_thread()->IsCurrent());
5619 RTC_DCHECK(sctp_factory_);
5620 cricket::DtlsTransportInternal* tc =
5621 transport_controller_->CreateDtlsTransport_n(
5622 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5623 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5624 RTC_DCHECK(sctp_transport_);
5625 sctp_invoker_.reset(new rtc::AsyncInvoker());
5626 sctp_transport_->SignalReadyToSendData.connect(
5627 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5628 sctp_transport_->SignalDataReceived.connect(
5629 this, &PeerConnection::OnSctpTransportDataReceived_n);
5630 sctp_transport_->SignalStreamClosedRemotely.connect(
5631 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005632 sctp_transport_name_ = transport_name;
5633 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005634 return true;
5635}
5636
5637void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5638 RTC_DCHECK(network_thread()->IsCurrent());
5639 RTC_DCHECK(sctp_transport_);
5640 RTC_DCHECK(sctp_transport_name_);
5641 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005642 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005643 cricket::DtlsTransportInternal* tc =
5644 transport_controller_->CreateDtlsTransport_n(
5645 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5646 sctp_transport_->SetTransportChannel(tc);
5647 transport_controller_->DestroyDtlsTransport_n(
5648 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5649}
5650
5651void PeerConnection::DestroySctpTransport_n() {
5652 RTC_DCHECK(network_thread()->IsCurrent());
5653 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005654 transport_controller_->DestroyDtlsTransport_n(
5655 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005656 sctp_content_name_.reset();
5657 sctp_transport_name_.reset();
5658 sctp_invoker_.reset(nullptr);
5659 sctp_ready_to_send_data_ = false;
5660}
5661
5662void PeerConnection::OnSctpTransportReadyToSendData_n() {
5663 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5664 RTC_DCHECK(network_thread()->IsCurrent());
5665 // Note: Cannot use rtc::Bind here because it will grab a reference to
5666 // PeerConnection and potentially cause PeerConnection to live longer than
5667 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5668 // be destroyed before PeerConnection is destroyed, and at that point all
5669 // pending tasks will be cleared.
5670 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5671 OnSctpTransportReadyToSendData_s(true);
5672 });
5673}
5674
5675void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5676 RTC_DCHECK(signaling_thread()->IsCurrent());
5677 sctp_ready_to_send_data_ = ready;
5678 SignalSctpReadyToSendData(ready);
5679}
5680
5681void PeerConnection::OnSctpTransportDataReceived_n(
5682 const cricket::ReceiveDataParams& params,
5683 const rtc::CopyOnWriteBuffer& payload) {
5684 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5685 RTC_DCHECK(network_thread()->IsCurrent());
5686 // Note: Cannot use rtc::Bind here because it will grab a reference to
5687 // PeerConnection and potentially cause PeerConnection to live longer than
5688 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5689 // be destroyed before PeerConnection is destroyed, and at that point all
5690 // pending tasks will be cleared.
5691 sctp_invoker_->AsyncInvoke<void>(
5692 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5693 OnSctpTransportDataReceived_s(params, payload);
5694 });
5695}
5696
5697void PeerConnection::OnSctpTransportDataReceived_s(
5698 const cricket::ReceiveDataParams& params,
5699 const rtc::CopyOnWriteBuffer& payload) {
5700 RTC_DCHECK(signaling_thread()->IsCurrent());
5701 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5702 // Received OPEN message; parse and signal that a new data channel should
5703 // be created.
5704 std::string label;
5705 InternalDataChannelInit config;
5706 config.id = params.ssrc;
5707 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005708 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5709 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005710 return;
5711 }
5712 config.open_handshake_role = InternalDataChannelInit::kAcker;
5713 OnDataChannelOpenMessage(label, config);
5714 } else {
5715 // Otherwise just forward the signal.
5716 SignalSctpDataReceived(params, payload);
5717 }
5718}
5719
5720void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5721 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5722 RTC_DCHECK(network_thread()->IsCurrent());
5723 sctp_invoker_->AsyncInvoke<void>(
5724 RTC_FROM_HERE, signaling_thread(),
5725 rtc::Bind(&sigslot::signal1<int>::operator(),
5726 &SignalSctpStreamClosedRemotely, sid));
5727}
5728
5729// Returns false if bundle is enabled and rtcp_mux is disabled.
5730bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5731 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5732 if (!bundle_enabled)
5733 return true;
5734
5735 const cricket::ContentGroup* bundle_group =
5736 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5737 RTC_DCHECK(bundle_group != NULL);
5738
5739 const cricket::ContentInfos& contents = desc->contents();
5740 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5741 citer != contents.end(); ++citer) {
5742 const cricket::ContentInfo* content = (&*citer);
5743 RTC_DCHECK(content != NULL);
5744 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005745 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005746 if (!HasRtcpMuxEnabled(content))
5747 return false;
5748 }
5749 }
5750 // RTCP-MUX is enabled in all the contents.
5751 return true;
5752}
5753
5754bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005755 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005756}
5757
Steve Anton8a006912017-12-04 15:25:56 -08005758RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005759 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005760 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005761 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005762 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005763 }
5764
5765 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005766 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005767 }
5768
Steve Anton3828c062017-12-06 10:34:51 -08005769 SdpType type = sdesc->GetType();
5770 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5771 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005772 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005773 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005774 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776
5777 // Verify crypto settings.
5778 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005779 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5780 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005781 RTCError crypto_error =
5782 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005783 if (!crypto_error.ok()) {
5784 return crypto_error;
5785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787
5788 // Verify ice-ufrag and ice-pwd.
5789 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005790 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5791 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005792 }
5793
5794 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5796 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005797 }
5798
5799 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5800 // m-lines that do not rtcp-mux enabled.
5801
5802 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005803 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005804 // With an answer we want to compare the new answer session description with
5805 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005806 const cricket::SessionDescription* offer_desc =
5807 (source == cricket::CS_LOCAL) ? remote_description()->description()
5808 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005809 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5810 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5811 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005812 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5813 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005814 }
5815 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005816 // The re-offers should respect the order of m= sections in current
5817 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005818 // With a re-offer, either the current local or current remote descriptions
5819 // could be the most up to date, so we would like to check against both of
5820 // them if they exist. It could be the case that one of them has a 0 port
5821 // for a media section, but the other does not. This is important to check
5822 // against in the case that we are recycling an m= section.
5823 const cricket::SessionDescription* current_desc = nullptr;
5824 const cricket::SessionDescription* secondary_current_desc = nullptr;
5825 if (local_description()) {
5826 current_desc = local_description()->description();
5827 if (remote_description()) {
5828 secondary_current_desc = remote_description()->description();
5829 }
5830 } else if (remote_description()) {
5831 current_desc = remote_description()->description();
5832 }
Steve Anton75737c02017-11-06 10:37:17 -08005833 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005834 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5835 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005836 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5837 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005838 }
5839 }
5840
Steve Anton8a006912017-12-04 15:25:56 -08005841 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005842}
5843
Steve Anton3828c062017-12-06 10:34:51 -08005844bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005845 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005846 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005847 return (state == PeerConnectionInterface::kStable) ||
5848 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005849 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005850 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005851 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5852 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5853 }
5854}
5855
Steve Anton3828c062017-12-06 10:34:51 -08005856bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005857 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005858 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005859 return (state == PeerConnectionInterface::kStable) ||
5860 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005861 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005862 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005863 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5864 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5865 }
5866}
5867
Steve Antonf8470812017-12-04 10:46:21 -08005868const char* PeerConnection::SessionErrorToString(SessionError error) const {
5869 switch (error) {
5870 case SessionError::kNone:
5871 return "ERROR_NONE";
5872 case SessionError::kContent:
5873 return "ERROR_CONTENT";
5874 case SessionError::kTransport:
5875 return "ERROR_TRANSPORT";
5876 }
5877 RTC_NOTREACHED();
5878 return "";
5879}
5880
Steve Anton75737c02017-11-06 10:37:17 -08005881std::string PeerConnection::GetSessionErrorMsg() {
5882 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005883 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5884 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005885 return desc.str();
5886}
5887
Steve Anton8e20f172018-03-06 10:55:04 -08005888void PeerConnection::ReportSdpFormatReceived(
5889 const SessionDescriptionInterface& remote_offer) {
5890 if (!uma_observer_) {
5891 return;
5892 }
5893 int num_audio_mlines = 0;
5894 int num_video_mlines = 0;
5895 int num_audio_tracks = 0;
5896 int num_video_tracks = 0;
5897 for (const ContentInfo& content : remote_offer.description()->contents()) {
5898 cricket::MediaType media_type = content.media_description()->type();
5899 int num_tracks = std::max(
5900 1, static_cast<int>(content.media_description()->streams().size()));
5901 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5902 num_audio_mlines += 1;
5903 num_audio_tracks += num_tracks;
5904 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5905 num_video_mlines += 1;
5906 num_video_tracks += num_tracks;
5907 }
5908 }
5909 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5910 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5911 format = kSdpFormatReceivedComplexUnifiedPlan;
5912 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5913 format = kSdpFormatReceivedComplexPlanB;
5914 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5915 format = kSdpFormatReceivedSimple;
5916 }
5917 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5918 kSdpFormatReceivedMax);
5919}
5920
Steve Anton0ffaaa22018-02-23 10:31:30 -08005921void PeerConnection::ReportNegotiatedSdpSemantics(
5922 const SessionDescriptionInterface& answer) {
5923 if (!uma_observer_) {
5924 return;
5925 }
5926 switch (answer.description()->msid_signaling()) {
5927 case 0:
5928 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5929 kSdpSemanticNegotiatedNone,
5930 kSdpSemanticNegotiatedMax);
5931 break;
5932 case cricket::kMsidSignalingMediaSection:
5933 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5934 kSdpSemanticNegotiatedUnifiedPlan,
5935 kSdpSemanticNegotiatedMax);
5936 break;
5937 case cricket::kMsidSignalingSsrcAttribute:
5938 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5939 kSdpSemanticNegotiatedPlanB,
5940 kSdpSemanticNegotiatedMax);
5941 break;
5942 case cricket::kMsidSignalingMediaSection |
5943 cricket::kMsidSignalingSsrcAttribute:
5944 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5945 kSdpSemanticNegotiatedMixed,
5946 kSdpSemanticNegotiatedMax);
5947 break;
5948 default:
5949 RTC_NOTREACHED();
5950 }
5951}
5952
Steve Anton75737c02017-11-06 10:37:17 -08005953// We need to check the local/remote description for the Transport instead of
5954// the session, because a new Transport added during renegotiation may have
5955// them unset while the session has them set from the previous negotiation.
5956// Not doing so may trigger the auto generation of transport description and
5957// mess up DTLS identity information, ICE credential, etc.
5958bool PeerConnection::ReadyToUseRemoteCandidate(
5959 const IceCandidateInterface* candidate,
5960 const SessionDescriptionInterface* remote_desc,
5961 bool* valid) {
5962 *valid = true;
5963
5964 const SessionDescriptionInterface* current_remote_desc =
5965 remote_desc ? remote_desc : remote_description();
5966
5967 if (!current_remote_desc) {
5968 return false;
5969 }
5970
5971 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5972 size_t remote_content_size =
5973 current_remote_desc->description()->contents().size();
5974 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005975 RTC_LOG(LS_ERROR)
5976 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5977 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005978
5979 *valid = false;
5980 return false;
5981 }
5982
5983 cricket::ContentInfo content =
5984 current_remote_desc->description()->contents()[mediacontent_index];
5985
5986 const std::string transport_name = GetTransportName(content.name);
5987 if (transport_name.empty()) {
5988 return false;
5989 }
5990 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5991}
5992
5993bool PeerConnection::SrtpRequired() const {
5994 return dtls_enabled_ ||
5995 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5996}
5997
5998void PeerConnection::OnTransportControllerGatheringState(
5999 cricket::IceGatheringState state) {
6000 RTC_DCHECK(signaling_thread()->IsCurrent());
6001 if (state == cricket::kIceGatheringGathering) {
6002 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6003 } else if (state == cricket::kIceGatheringComplete) {
6004 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6005 }
6006}
6007
6008void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006009 std::map<std::string, std::set<cricket::MediaType>>
6010 media_types_by_transport_name;
6011 for (auto transceiver : transceivers_) {
6012 if (transceiver->internal()->channel()) {
6013 const std::string& transport_name =
6014 transceiver->internal()->channel()->transport_name();
6015 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006016 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006017 }
Steve Anton75737c02017-11-06 10:37:17 -08006018 }
6019 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006020 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6021 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006022 }
6023 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 media_types_by_transport_name[*sctp_transport_name_].insert(
6025 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006026 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006027 for (const auto& entry : media_types_by_transport_name) {
6028 const std::string& transport_name = entry.first;
6029 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006030 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006031 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006032 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006033 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006034 }
6035 }
6036}
6037// Walk through the ConnectionInfos to gather best connection usage
6038// for IPv4 and IPv6.
6039void PeerConnection::ReportBestConnectionState(
6040 const cricket::TransportStats& stats) {
6041 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006042 for (const cricket::TransportChannelStats& channel_stats :
6043 stats.channel_stats) {
6044 for (const cricket::ConnectionInfo& connection_info :
6045 channel_stats.connection_infos) {
6046 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006047 continue;
6048 }
6049
6050 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006051 const cricket::Candidate& local = connection_info.local_candidate;
6052 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006053
6054 // Increment the counter for IceCandidatePairType.
6055 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6056 (local.type() == RELAY_PORT_TYPE &&
6057 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6058 type = kEnumCounterIceCandidatePairTypeTcp;
6059 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6060 type = kEnumCounterIceCandidatePairTypeUdp;
6061 } else {
6062 RTC_CHECK(0);
6063 }
6064 metrics_observer()->IncrementEnumCounter(
6065 type, GetIceCandidatePairCounter(local, remote),
6066 kIceCandidatePairMax);
6067
6068 // Increment the counter for IP type.
6069 if (local.address().family() == AF_INET) {
6070 metrics_observer()->IncrementEnumCounter(
6071 kEnumCounterAddressFamily, kBestConnections_IPv4,
6072 kPeerConnectionAddressFamilyCounter_Max);
6073
6074 } else if (local.address().family() == AF_INET6) {
6075 metrics_observer()->IncrementEnumCounter(
6076 kEnumCounterAddressFamily, kBestConnections_IPv6,
6077 kPeerConnectionAddressFamilyCounter_Max);
6078 } else {
6079 RTC_CHECK(0);
6080 }
6081
6082 return;
6083 }
6084 }
6085}
6086
6087void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006088 const cricket::TransportStats& stats,
6089 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006090 RTC_DCHECK(metrics_observer());
6091 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6092 return;
6093 }
6094
6095 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6096 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6097 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6098 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6099 return;
6100 }
6101
Steve Antonc7b964c2018-02-01 14:39:45 -08006102 for (cricket::MediaType media_type : media_types) {
6103 PeerConnectionEnumCounterType srtp_counter_type;
6104 PeerConnectionEnumCounterType ssl_counter_type;
6105 switch (media_type) {
6106 case cricket::MEDIA_TYPE_AUDIO:
6107 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6108 ssl_counter_type = kEnumCounterAudioSslCipher;
6109 break;
6110 case cricket::MEDIA_TYPE_VIDEO:
6111 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6112 ssl_counter_type = kEnumCounterVideoSslCipher;
6113 break;
6114 case cricket::MEDIA_TYPE_DATA:
6115 srtp_counter_type = kEnumCounterDataSrtpCipher;
6116 ssl_counter_type = kEnumCounterDataSslCipher;
6117 break;
6118 default:
6119 RTC_NOTREACHED();
6120 continue;
6121 }
6122 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6123 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6124 srtp_crypto_suite);
6125 }
6126 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6127 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6128 ssl_cipher_suite);
6129 }
Steve Anton75737c02017-11-06 10:37:17 -08006130 }
6131}
6132
6133void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6134 RTC_DCHECK(worker_thread()->IsCurrent());
6135 RTC_DCHECK(call_);
6136 call_->OnSentPacket(sent_packet);
6137}
6138
6139const std::string PeerConnection::GetTransportName(
6140 const std::string& content_name) {
6141 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006142 if (channel) {
6143 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006144 }
Steve Anton6fec8802017-12-04 10:37:29 -08006145 if (sctp_transport_) {
6146 RTC_DCHECK(sctp_content_name_);
6147 RTC_DCHECK(sctp_transport_name_);
6148 if (content_name == *sctp_content_name_) {
6149 return *sctp_transport_name_;
6150 }
6151 }
6152 // Return an empty string if failed to retrieve the transport name.
6153 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006154}
6155
6156void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6157 RTC_DCHECK(network_thread()->IsCurrent());
6158 transport_controller_->DestroyDtlsTransport_n(
6159 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6160}
6161
Steve Anton6fec8802017-12-04 10:37:29 -08006162void PeerConnection::DestroyTransceiverChannel(
6163 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6164 transceiver) {
6165 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006166
Steve Anton6fec8802017-12-04 10:37:29 -08006167 cricket::BaseChannel* channel = transceiver->internal()->channel();
6168 if (channel) {
6169 transceiver->internal()->SetChannel(nullptr);
6170 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006171 }
6172}
6173
6174void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006175 if (rtp_data_channel_) {
6176 OnDataChannelDestroyed();
6177 DestroyBaseChannel(rtp_data_channel_);
6178 rtp_data_channel_ = nullptr;
6179 }
6180
6181 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6182 // grab a reference to this PeerConnection. If this is called from the
6183 // PeerConnection destructor, the RefCountedObject vtable will have already
6184 // been destroyed (since it is a subclass of PeerConnection) and using
6185 // rtc::Bind will cause "Pure virtual function called" error to appear.
6186
6187 if (sctp_transport_) {
6188 OnDataChannelDestroyed();
6189 network_thread()->Invoke<void>(RTC_FROM_HERE,
6190 [this] { DestroySctpTransport_n(); });
6191 }
6192}
6193
6194void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6195 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006196 // Need to cache these before destroying the base channel so that we do not
6197 // access uninitialized memory.
Zhi Huang27f3bf52018-03-26 21:37:23 -07006198 const std::string transport_name = channel->transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006199 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6200
6201 switch (channel->media_type()) {
6202 case cricket::MEDIA_TYPE_AUDIO:
6203 channel_manager()->DestroyVoiceChannel(
6204 static_cast<cricket::VoiceChannel*>(channel));
6205 break;
6206 case cricket::MEDIA_TYPE_VIDEO:
6207 channel_manager()->DestroyVideoChannel(
6208 static_cast<cricket::VideoChannel*>(channel));
6209 break;
6210 case cricket::MEDIA_TYPE_DATA:
6211 channel_manager()->DestroyRtpDataChannel(
6212 static_cast<cricket::RtpDataChannel*>(channel));
6213 break;
6214 default:
6215 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6216 break;
6217 }
6218
6219 // |channel| can no longer be used.
6220
Steve Anton75737c02017-11-06 10:37:17 -08006221 transport_controller_->DestroyDtlsTransport(
6222 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6223 if (need_to_delete_rtcp) {
6224 transport_controller_->DestroyDtlsTransport(
6225 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6226 }
6227}
6228
Harald Alvestrand89061872018-01-02 14:08:34 +01006229void PeerConnection::ClearStatsCache() {
6230 if (stats_collector_) {
6231 stats_collector_->ClearCachedStatsReport();
6232 }
6233}
6234
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006235} // namespace webrtc