blob: eacfb8329b1fb3f95173ee228ee6bb9c41afbc5b [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 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001031 auto result =
1032 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1033 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001034}
1035
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001036rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001038 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1039 "Plan SdpSemantics. Please use GetSenders "
1040 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001041 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042}
1043
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001044rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001046 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1047 "Plan SdpSemantics. Please use GetReceivers "
1048 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001049 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050}
1051
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001052bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001053 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1054 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001055 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 if (IsClosed()) {
1057 return false;
1058 }
deadbeefab9b2d12015-10-14 11:33:11 -07001059 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 return false;
1061 }
deadbeefab9b2d12015-10-14 11:33:11 -07001062
1063 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001064 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1065 observer->SignalAudioTrackAdded.connect(this,
1066 &PeerConnection::OnAudioTrackAdded);
1067 observer->SignalAudioTrackRemoved.connect(
1068 this, &PeerConnection::OnAudioTrackRemoved);
1069 observer->SignalVideoTrackAdded.connect(this,
1070 &PeerConnection::OnVideoTrackAdded);
1071 observer->SignalVideoTrackRemoved.connect(
1072 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001073 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001074
deadbeefab9b2d12015-10-14 11:33:11 -07001075 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001076 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001077 }
1078 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001079 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001080 }
1081
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001082 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 observer_->OnRenegotiationNeeded();
1084 return true;
1085}
1086
1087void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001088 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1089 "Plan SdpSemantics. Please use RemoveTrack "
1090 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001091 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001092 if (!IsClosed()) {
1093 for (const auto& track : local_stream->GetAudioTracks()) {
1094 RemoveAudioTrack(track.get(), local_stream);
1095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
1097 RemoveVideoTrack(track.get(), local_stream);
1098 }
deadbeefab9b2d12015-10-14 11:33:11 -07001099 }
deadbeefab9b2d12015-10-14 11:33:11 -07001100 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001101 stream_observers_.erase(
1102 std::remove_if(
1103 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001104 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001105 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001106 }),
1107 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001108
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 if (IsClosed()) {
1110 return;
1111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 observer_->OnRenegotiationNeeded();
1113}
1114
deadbeefe1f9d832016-01-14 15:35:42 -08001115rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1116 MediaStreamTrackInterface* track,
1117 std::vector<MediaStreamInterface*> streams) {
1118 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001119 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001120 for (auto* stream : streams) {
1121 if (!stream) {
1122 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1123 return nullptr;
1124 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001125 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001126 }
Seth Hampson845e8782018-03-02 11:34:10 -08001127 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001128 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001129 return nullptr;
1130 }
Steve Antonf9381f02017-12-14 10:23:57 -08001131 return sender_or_error.MoveValue();
1132}
1133
Steve Anton2d6c76a2018-01-05 17:10:52 -08001134RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001135 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001136 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001137 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001138 if (!track) {
1139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1140 }
1141 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1142 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1144 "Track has invalid kind: " + track->kind());
1145 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001146 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1147 if (stream_ids.size() > 1u) {
1148 LOG_AND_RETURN_ERROR(
1149 RTCErrorType::UNSUPPORTED_OPERATION,
1150 "AddTrack with more than one stream is not currently supported.");
1151 }
Steve Antonf9381f02017-12-14 10:23:57 -08001152 if (IsClosed()) {
1153 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1154 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001155 }
Steve Anton4171afb2017-11-20 10:20:22 -08001156 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001157 LOG_AND_RETURN_ERROR(
1158 RTCErrorType::INVALID_PARAMETER,
1159 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001160 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001161 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1162 // one stream. AddTrackInternal will return an error if there is more than one
1163 // stream, but if the caller specifies none then we need to generate a random
1164 // stream id.
1165 std::vector<std::string> adjusted_stream_ids = stream_ids;
1166 if (stream_ids.empty()) {
1167 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1168 }
1169 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001170 auto sender_or_error =
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001171 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1172 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001173 if (sender_or_error.ok()) {
1174 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001175 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001176 }
1177 return sender_or_error;
1178}
deadbeefe1f9d832016-01-14 15:35:42 -08001179
Steve Antonf9381f02017-12-14 10:23:57 -08001180RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1181PeerConnection::AddTrackPlanB(
1182 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001183 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001184 cricket::MediaType media_type =
1185 (track->kind() == MediaStreamTrackInterface::kAudioKind
1186 ? cricket::MEDIA_TYPE_AUDIO
1187 : cricket::MEDIA_TYPE_VIDEO);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001188 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001189 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001190 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001191 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001192 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001193 FindSenderInfo(local_audio_sender_infos_,
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001194 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001195 if (sender_info) {
1196 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001197 }
Steve Antonf9381f02017-12-14 10:23:57 -08001198 } else {
1199 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001200 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001201 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001202 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001203 FindSenderInfo(local_video_sender_infos_,
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001204 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001205 if (sender_info) {
1206 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
deadbeefe1f9d832016-01-14 15:35:42 -08001208 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001209 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001210}
deadbeefe1f9d832016-01-14 15:35:42 -08001211
Steve Antonf9381f02017-12-14 10:23:57 -08001212RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1213PeerConnection::AddTrackUnifiedPlan(
1214 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001215 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001216 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1217 if (transceiver) {
1218 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001219 transceiver->internal()->set_direction(
1220 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001221 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001222 transceiver->internal()->set_direction(
1223 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001224 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001225 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001226 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001227 } else {
1228 cricket::MediaType media_type =
1229 (track->kind() == MediaStreamTrackInterface::kAudioKind
1230 ? cricket::MEDIA_TYPE_AUDIO
1231 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001232 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001233 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1234 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001235 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001236 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001237 }
Steve Antonf9381f02017-12-14 10:23:57 -08001238 return transceiver->sender();
1239}
1240
1241rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1242PeerConnection::FindFirstTransceiverForAddedTrack(
1243 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1244 RTC_DCHECK(track);
1245 for (auto transceiver : transceivers_) {
1246 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001247 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001248 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001249 !transceiver->internal()->has_ever_been_used_to_send() &&
1250 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001251 return transceiver;
1252 }
1253 }
1254 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001255}
1256
1257bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1258 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001259 return RemoveTrackInternal(sender).ok();
1260}
1261
1262RTCError PeerConnection::RemoveTrackInternal(
1263 rtc::scoped_refptr<RtpSenderInterface> sender) {
1264 if (!sender) {
1265 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1266 }
deadbeefe1f9d832016-01-14 15:35:42 -08001267 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001268 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1269 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001270 }
Steve Antonf9381f02017-12-14 10:23:57 -08001271 if (IsUnifiedPlan()) {
1272 auto transceiver = FindTransceiverBySender(sender);
1273 if (!transceiver || !sender->track()) {
1274 return RTCError::OK();
1275 }
1276 sender->SetTrack(nullptr);
1277 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001278 transceiver->internal()->set_direction(
1279 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001280 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001281 transceiver->internal()->set_direction(
1282 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001283 }
Steve Anton4171afb2017-11-20 10:20:22 -08001284 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001285 bool removed;
1286 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1287 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1288 } else {
1289 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1290 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1291 }
1292 if (!removed) {
1293 LOG_AND_RETURN_ERROR(
1294 RTCErrorType::INVALID_PARAMETER,
1295 "Couldn't find sender " + sender->id() + " to remove.");
1296 }
Steve Anton4171afb2017-11-20 10:20:22 -08001297 }
deadbeefe1f9d832016-01-14 15:35:42 -08001298 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001299 return RTCError::OK();
1300}
1301
1302rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1303PeerConnection::FindTransceiverBySender(
1304 rtc::scoped_refptr<RtpSenderInterface> sender) {
1305 for (auto transceiver : transceivers_) {
1306 if (transceiver->sender() == sender) {
1307 return transceiver;
1308 }
1309 }
1310 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001311}
1312
Steve Anton9158ef62017-11-27 13:01:52 -08001313RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1314PeerConnection::AddTransceiver(
1315 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1316 return AddTransceiver(track, RtpTransceiverInit());
1317}
1318
1319RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1320PeerConnection::AddTransceiver(
1321 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1322 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001323 RTC_CHECK(IsUnifiedPlan())
1324 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001325 if (!track) {
1326 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1327 }
1328 cricket::MediaType media_type;
1329 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1330 media_type = cricket::MEDIA_TYPE_AUDIO;
1331 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1332 media_type = cricket::MEDIA_TYPE_VIDEO;
1333 } else {
1334 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1335 "Track kind is not audio or video");
1336 }
1337 return AddTransceiver(media_type, track, init);
1338}
1339
1340RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1341PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1342 return AddTransceiver(media_type, RtpTransceiverInit());
1343}
1344
1345RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1346PeerConnection::AddTransceiver(cricket::MediaType media_type,
1347 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001348 RTC_CHECK(IsUnifiedPlan())
1349 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001350 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1351 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1352 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1353 "media type is not audio or video");
1354 }
1355 return AddTransceiver(media_type, nullptr, init);
1356}
1357
1358RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1359PeerConnection::AddTransceiver(
1360 cricket::MediaType media_type,
1361 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001362 const RtpTransceiverInit& init,
1363 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001364 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1365 media_type == cricket::MEDIA_TYPE_VIDEO));
1366 if (track) {
1367 RTC_DCHECK_EQ(media_type,
1368 (track->kind() == MediaStreamTrackInterface::kAudioKind
1369 ? cricket::MEDIA_TYPE_AUDIO
1370 : cricket::MEDIA_TYPE_VIDEO));
1371 }
1372
1373 // TODO(bugs.webrtc.org/7600): Verify init.
1374
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001375 if (init.stream_ids.size() > 1u) {
1376 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1377 "More than one stream is not yet supported.");
1378 }
1379
1380 std::vector<std::string> stream_ids = {
1381 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
1382
1383 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001384 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1385 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1386 transceiver->internal()->set_direction(init.direction);
1387
Steve Anton22da89f2018-01-25 13:58:07 -08001388 if (fire_callback) {
1389 observer_->OnRenegotiationNeeded();
1390 }
Steve Antonf9381f02017-12-14 10:23:57 -08001391
1392 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1393}
1394
Steve Anton02ee47c2018-01-10 16:26:06 -08001395rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1396PeerConnection::CreateSender(
1397 cricket::MediaType media_type,
1398 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001399 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001400 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001401 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1402 RTC_DCHECK(!track ||
1403 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1404 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1405 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001406 new AudioRtpSender(worker_thread(),
1407 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001408 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001409 } else {
1410 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1411 RTC_DCHECK(!track ||
1412 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1413 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1414 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001415 new VideoRtpSender(worker_thread(),
1416 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001417 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001418 }
Seth Hampson845e8782018-03-02 11:34:10 -08001419 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 return sender;
1421}
1422
1423rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1424PeerConnection::CreateReceiver(cricket::MediaType media_type,
1425 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001426 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1427 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001428 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001429 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001430 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001431 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001432 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001433 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001434 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1435 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001436 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001437 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001438 return receiver;
1439}
1440
1441rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1442PeerConnection::CreateAndAddTransceiver(
1443 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1444 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1445 receiver) {
1446 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1447 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001448 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001449 transceiver->internal()->SignalNegotiationNeeded.connect(
1450 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001451 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001452}
1453
Steve Anton52d86772018-02-20 15:48:12 -08001454void PeerConnection::OnNegotiationNeeded() {
1455 RTC_DCHECK_RUN_ON(signaling_thread());
1456 RTC_DCHECK(!IsClosed());
1457 observer_->OnRenegotiationNeeded();
1458}
1459
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001460rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001462 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001463 if (IsClosed()) {
1464 return nullptr;
1465 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001467 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001468 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 }
Steve Anton4171afb2017-11-20 10:20:22 -08001470 auto track_sender = FindSenderForTrack(track);
1471 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001472 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001473 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 }
1475
Steve Anton4171afb2017-11-20 10:20:22 -08001476 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477}
1478
deadbeeffac06552015-11-25 11:26:01 -08001479rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001480 const std::string& kind,
1481 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001482 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1483 "Plan SdpSemantics. Please use AddTransceiver "
1484 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001485 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001486 if (IsClosed()) {
1487 return nullptr;
1488 }
Steve Anton4171afb2017-11-20 10:20:22 -08001489
Seth Hampson845e8782018-03-02 11:34:10 -08001490 std::vector<std::string> stream_ids;
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001491 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001492 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001493 }
1494
Steve Anton4171afb2017-11-20 10:20:22 -08001495 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001496 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001497 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001498 auto* audio_sender =
1499 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001500 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001501 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001503 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001504 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001505 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001506 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001507 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001508 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001509 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001510 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001511 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001512 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001513 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001514 }
Steve Anton4171afb2017-11-20 10:20:22 -08001515
deadbeefe1f9d832016-01-14 15:35:42 -08001516 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001517}
1518
deadbeef70ab1a12015-09-28 16:53:55 -07001519std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1520 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001521 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001522 for (auto sender : GetSendersInternal()) {
1523 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001524 }
1525 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001526}
1527
Steve Anton4171afb2017-11-20 10:20:22 -08001528std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1529PeerConnection::GetSendersInternal() const {
1530 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1531 all_senders;
1532 for (auto transceiver : transceivers_) {
1533 auto senders = transceiver->internal()->senders();
1534 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1535 }
1536 return all_senders;
1537}
1538
deadbeef70ab1a12015-09-28 16:53:55 -07001539std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1540PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001541 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001542 for (const auto& receiver : GetReceiversInternal()) {
1543 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001544 }
1545 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001546}
1547
Steve Anton4171afb2017-11-20 10:20:22 -08001548std::vector<
1549 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1550PeerConnection::GetReceiversInternal() const {
1551 std::vector<
1552 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1553 all_receivers;
1554 for (auto transceiver : transceivers_) {
1555 auto receivers = transceiver->internal()->receivers();
1556 all_receivers.insert(all_receivers.end(), receivers.begin(),
1557 receivers.end());
1558 }
1559 return all_receivers;
1560}
1561
Steve Anton9158ef62017-11-27 13:01:52 -08001562std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1563PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001564 RTC_CHECK(IsUnifiedPlan())
1565 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001566 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1567 for (auto transceiver : transceivers_) {
1568 all_transceivers.push_back(transceiver);
1569 }
1570 return all_transceivers;
1571}
1572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001574 MediaStreamTrackInterface* track,
1575 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001576 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001577 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001578 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001579 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 return false;
1581 }
1582
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001583 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001584 // The StatsCollector is used to tell if a track is valid because it may
1585 // remember tracks that the PeerConnection previously removed.
1586 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001587 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1588 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001589 return false;
1590 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001591 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001592 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001593 return true;
1594}
1595
hbos74e1a4f2016-09-15 23:33:01 -07001596void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001597 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001598 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001599 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001600 stats_collector_->GetStatsReport(callback);
1601}
1602
Henrik Boström1df1bf82018-03-20 13:24:20 +01001603void PeerConnection::GetStats(
1604 rtc::scoped_refptr<RtpSenderInterface> selector,
1605 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1606 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1607 RTC_DCHECK(callback);
1608 RTC_DCHECK(stats_collector_);
1609 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1610 if (selector) {
1611 for (const auto& proxy_transceiver : transceivers_) {
1612 for (const auto& proxy_sender :
1613 proxy_transceiver->internal()->senders()) {
1614 if (proxy_sender == selector) {
1615 internal_sender = proxy_sender->internal();
1616 break;
1617 }
1618 }
1619 if (internal_sender)
1620 break;
1621 }
1622 }
1623 // If there is no |internal_sender| then |selector| is either null or does not
1624 // belong to the PeerConnection (in Plan B, senders can be removed from the
1625 // PeerConnection). This means that "all the stats objects representing the
1626 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1627 // produces an empty stats report.
1628 stats_collector_->GetStatsReport(internal_sender, callback);
1629}
1630
1631void PeerConnection::GetStats(
1632 rtc::scoped_refptr<RtpReceiverInterface> selector,
1633 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1634 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1635 RTC_DCHECK(callback);
1636 RTC_DCHECK(stats_collector_);
1637 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1638 if (selector) {
1639 for (const auto& proxy_transceiver : transceivers_) {
1640 for (const auto& proxy_receiver :
1641 proxy_transceiver->internal()->receivers()) {
1642 if (proxy_receiver == selector) {
1643 internal_receiver = proxy_receiver->internal();
1644 break;
1645 }
1646 }
1647 if (internal_receiver)
1648 break;
1649 }
1650 }
1651 // If there is no |internal_receiver| then |selector| is either null or does
1652 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1653 // the PeerConnection). This means that "all the stats objects representing
1654 // the selector" is an empty set. Invoking GetStatsReport() with a null
1655 // selector produces an empty stats report.
1656 stats_collector_->GetStatsReport(internal_receiver, callback);
1657}
1658
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001659PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1660 return signaling_state_;
1661}
1662
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001663PeerConnectionInterface::IceConnectionState
1664PeerConnection::ice_connection_state() {
1665 return ice_connection_state_;
1666}
1667
1668PeerConnectionInterface::IceGatheringState
1669PeerConnection::ice_gathering_state() {
1670 return ice_gathering_state_;
1671}
1672
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001673rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674PeerConnection::CreateDataChannel(
1675 const std::string& label,
1676 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001677 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001678
deadbeefab9b2d12015-10-14 11:33:11 -07001679 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001680
kwibergd1fe2812016-04-27 06:47:29 -07001681 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001682 if (config) {
1683 internal_config.reset(new InternalDataChannelInit(*config));
1684 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001685 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001686 InternalCreateDataChannel(label, internal_config.get()));
1687 if (!channel.get()) {
1688 return nullptr;
1689 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001691 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1692 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001693 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001694 observer_->OnRenegotiationNeeded();
1695 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001696
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001697 return DataChannelProxy::Create(signaling_thread(), channel.get());
1698}
1699
1700void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1701 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001702 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001703
zhihuang1c378ed2017-08-17 14:10:50 -07001704 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1705 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1706 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1707 // compares the mandatory fields parsed with the mandatory fields added in the
1708 // |constraints| and some downstream applications might create offers with
1709 // mandatory fields which would not be parsed in the helper method. For
1710 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1711 // |constraints| as a mandatory field but it is not parsed.
1712 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001713
zhihuang1c378ed2017-08-17 14:10:50 -07001714 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001715}
1716
1717void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1718 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001719 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001720
nisse7ce109a2017-01-31 00:57:56 -08001721 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001722 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001723 return;
1724 }
deadbeefab9b2d12015-10-14 11:33:11 -07001725
Steve Anton8d3444d2017-10-20 15:30:51 -07001726 if (IsClosed()) {
1727 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001728 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001729 PostCreateSessionDescriptionFailure(
1730 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001731 return;
1732 }
1733
zhihuang1c378ed2017-08-17 14:10:50 -07001734 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001735 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001736 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001737 PostCreateSessionDescriptionFailure(
1738 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001739 return;
1740 }
1741
Steve Anton22da89f2018-01-25 13:58:07 -08001742 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1743 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1744 if (IsUnifiedPlan()) {
1745 RTCError error = HandleLegacyOfferOptions(options);
1746 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001747 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001748 return;
1749 }
1750 }
1751
zhihuang1c378ed2017-08-17 14:10:50 -07001752 cricket::MediaSessionOptions session_options;
1753 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001754 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755}
1756
Steve Anton22da89f2018-01-25 13:58:07 -08001757RTCError PeerConnection::HandleLegacyOfferOptions(
1758 const RTCOfferAnswerOptions& options) {
1759 RTC_DCHECK(IsUnifiedPlan());
1760
1761 if (options.offer_to_receive_audio == 0) {
1762 RemoveRecvDirectionFromReceivingTransceiversOfType(
1763 cricket::MEDIA_TYPE_AUDIO);
1764 } else if (options.offer_to_receive_audio == 1) {
1765 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1766 } else if (options.offer_to_receive_audio > 1) {
1767 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1768 "offer_to_receive_audio > 1 is not supported.");
1769 }
1770
1771 if (options.offer_to_receive_video == 0) {
1772 RemoveRecvDirectionFromReceivingTransceiversOfType(
1773 cricket::MEDIA_TYPE_VIDEO);
1774 } else if (options.offer_to_receive_video == 1) {
1775 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1776 } else if (options.offer_to_receive_video > 1) {
1777 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1778 "offer_to_receive_video > 1 is not supported.");
1779 }
1780
1781 return RTCError::OK();
1782}
1783
1784void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1785 cricket::MediaType media_type) {
1786 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1787 transceiver->internal()->set_direction(
1788 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1789 }
1790}
1791
1792void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1793 cricket::MediaType media_type) {
1794 if (GetReceivingTransceiversOfType(media_type).empty()) {
1795 RtpTransceiverInit init;
1796 init.direction = RtpTransceiverDirection::kRecvOnly;
1797 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1798 }
1799}
1800
1801std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1802PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1803 std::vector<
1804 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1805 receiving_transceivers;
1806 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001807 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001808 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1809 receiving_transceivers.push_back(transceiver);
1810 }
1811 }
1812 return receiving_transceivers;
1813}
1814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001815void PeerConnection::CreateAnswer(
1816 CreateSessionDescriptionObserver* observer,
1817 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001818 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001819
nisse7ce109a2017-01-31 00:57:56 -08001820 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001821 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 return;
1823 }
deadbeefab9b2d12015-10-14 11:33:11 -07001824
zhihuang1c378ed2017-08-17 14:10:50 -07001825 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1826 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1827 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001828 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001829 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001830 PostCreateSessionDescriptionFailure(
1831 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001832 return;
1833 }
1834
Steve Anton8d3444d2017-10-20 15:30:51 -07001835 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001836}
1837
1838void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1839 const RTCOfferAnswerOptions& options) {
1840 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001841 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001842 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001843 return;
1844 }
1845
Steve Antondffead82018-02-06 10:31:29 -08001846 if (!(signaling_state_ == kHaveRemoteOffer ||
1847 signaling_state_ == kHaveLocalPrAnswer)) {
1848 std::string error =
1849 "PeerConnection cannot create an answer in a state other than "
1850 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001851 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001852 PostCreateSessionDescriptionFailure(
1853 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001854 return;
1855 }
1856
Steve Antondffead82018-02-06 10:31:29 -08001857 // The remote description should be set if we're in the right state.
1858 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001859
Steve Anton22da89f2018-01-25 13:58:07 -08001860 if (IsUnifiedPlan()) {
1861 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1862 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1863 "supported with Unified Plan semantics. Use the "
1864 "RtpTransceiver API instead.";
1865 }
1866 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1867 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1868 "supported with Unified Plan semantics. Use the "
1869 "RtpTransceiver API instead.";
1870 }
1871 }
1872
htaa2a49d92016-03-04 02:51:39 -08001873 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001874 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001875
Steve Antond25da372017-11-06 14:50:29 -08001876 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877}
1878
1879void PeerConnection::SetLocalDescription(
1880 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001881 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001882 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001883
Steve Anton80dd7b52018-02-16 17:08:42 -08001884 // The SetLocalDescription contract is that we take ownership of the session
1885 // description regardless of the outcome, so wrap it in a unique_ptr right
1886 // away. Ideally, SetLocalDescription's signature will be changed to take the
1887 // description as a unique_ptr argument to formalize this agreement.
1888 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1889
nisse7ce109a2017-01-31 00:57:56 -08001890 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001891 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 return;
1893 }
Steve Anton8a006912017-12-04 15:25:56 -08001894
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001896 PostSetSessionDescriptionFailure(
1897 observer,
1898 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899 return;
1900 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001901
Steve Anton80dd7b52018-02-16 17:08:42 -08001902 // If a session error has occurred the PeerConnection is in a possibly
1903 // inconsistent state so fail right away.
1904 if (session_error() != SessionError::kNone) {
1905 std::string error_message = GetSessionErrorMsg();
1906 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001907 PostSetSessionDescriptionFailure(
1908 observer,
1909 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001910 return;
1911 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001912
Steve Anton80dd7b52018-02-16 17:08:42 -08001913 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1914 if (!error.ok()) {
1915 std::string error_message = GetSetDescriptionErrorMessage(
1916 cricket::CS_LOCAL, desc->GetType(), error);
1917 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001918 PostSetSessionDescriptionFailure(
1919 observer,
1920 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001921 return;
1922 }
1923
1924 // Grab the description type before moving ownership to ApplyLocalDescription,
1925 // which may destroy it before returning.
1926 const SdpType type = desc->GetType();
1927
1928 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001929 // |desc| may be destroyed at this point.
1930
1931 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001932 // If ApplyLocalDescription fails, the PeerConnection could be in an
1933 // inconsistent state, so act conservatively here and set the session error
1934 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1935 SetSessionError(SessionError::kContent, error.message());
1936 std::string error_message =
1937 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1938 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001939 PostSetSessionDescriptionFailure(
1940 observer,
1941 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001942 return;
1943 }
Steve Anton8a006912017-12-04 15:25:56 -08001944 RTC_DCHECK(local_description());
1945
1946 PostSetSessionDescriptionSuccess(observer);
1947
1948 // According to JSEP, after setLocalDescription, changing the candidate pool
1949 // size is not allowed, and changing the set of ICE servers will not result
1950 // in new candidates being gathered.
1951 port_allocator_->FreezeCandidatePool();
1952
1953 // MaybeStartGathering needs to be called after posting
1954 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1955 // before signaling that SetLocalDescription completed.
1956 transport_controller_->MaybeStartGathering();
1957
Steve Antona3a92c22017-12-07 10:27:41 -08001958 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001959 // TODO(deadbeef): We already had to hop to the network thread for
1960 // MaybeStartGathering...
1961 network_thread()->Invoke<void>(
1962 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1963 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001964 // Make UMA notes about what was agreed to.
1965 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001966 }
1967}
1968
1969RTCError PeerConnection::ApplyLocalDescription(
1970 std::unique_ptr<SessionDescriptionInterface> desc) {
1971 RTC_DCHECK_RUN_ON(signaling_thread());
1972 RTC_DCHECK(desc);
1973
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974 // Update stats here so that we have the most recent stats for tracks and
1975 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001976 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001977
1978 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001979 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001980 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001981 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001982 if (*initial_offerer_) {
1983 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1984 } else {
1985 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1986 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 }
Steve Anton8a006912017-12-04 15:25:56 -08001988
Steve Antondcc3c022017-12-22 16:02:54 -08001989 // Take a reference to the old local description since it's used below to
1990 // compare against the new local description. When setting the new local
1991 // description, grab ownership of the replaced session description in case it
1992 // is the same as |old_local_description|, to keep it alive for the duration
1993 // of the method.
1994 const SessionDescriptionInterface* old_local_description =
1995 local_description();
1996 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001997 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001998 replaced_local_description = pending_local_description_
1999 ? std::move(pending_local_description_)
2000 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002001 current_local_description_ = std::move(desc);
2002 pending_local_description_ = nullptr;
2003 current_remote_description_ = std::move(pending_remote_description_);
2004 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002005 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002006 pending_local_description_ = std::move(desc);
2007 }
2008 // The session description to apply now must be accessed by
2009 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002010 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002011
Steve Antondcc3c022017-12-22 16:02:54 -08002012 if (IsUnifiedPlan()) {
2013 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002014 cricket::CS_LOCAL, *local_description(), old_local_description,
2015 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002016 if (!error.ok()) {
2017 return error;
2018 }
Steve Antondcc3c022017-12-22 16:02:54 -08002019 for (auto transceiver : transceivers_) {
2020 const ContentInfo* content =
2021 FindMediaSectionForTransceiver(transceiver, local_description());
2022 if (!content) {
2023 continue;
2024 }
2025 const MediaContentDescription* media_desc = content->media_description();
2026 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2027 transceiver->internal()->set_current_direction(media_desc->direction());
2028 }
2029 if (content->rejected && !transceiver->stopped()) {
2030 transceiver->Stop();
2031 }
2032 }
2033 } else {
2034 // Transport and Media channels will be created only when offer is set.
2035 if (type == SdpType::kOffer) {
2036 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2037 // description is applied. Restore back to old description.
2038 RTCError error = CreateChannels(*local_description()->description());
2039 if (!error.ok()) {
2040 return error;
2041 }
2042 }
Steve Anton8a006912017-12-04 15:25:56 -08002043
Steve Antondcc3c022017-12-22 16:02:54 -08002044 // Remove unused channels if MediaContentDescription is rejected.
2045 RemoveUnusedChannels(local_description()->description());
2046 }
Steve Anton8a006912017-12-04 15:25:56 -08002047
Steve Anton80dd7b52018-02-16 17:08:42 -08002048 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08002049 if (!error.ok()) {
2050 return error;
2051 }
Steve Antondcc3c022017-12-22 16:02:54 -08002052
Steve Anton8a006912017-12-04 15:25:56 -08002053 if (remote_description()) {
2054 // Now that we have a local description, we can push down remote candidates.
2055 UseCandidatesInSessionDescription(remote_description());
2056 }
2057
2058 pending_ice_restarts_.clear();
2059 if (session_error() != SessionError::kNone) {
2060 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2061 }
2062
deadbeefab9b2d12015-10-14 11:33:11 -07002063 // If setting the description decided our SSL role, allocate any necessary
2064 // SCTP sids.
2065 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002066 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002067 AllocateSctpSids(role);
2068 }
2069
Steve Antond3679212018-01-17 17:41:02 -08002070 if (IsUnifiedPlan()) {
2071 for (auto transceiver : transceivers_) {
2072 const ContentInfo* content =
2073 FindMediaSectionForTransceiver(transceiver, local_description());
2074 if (!content) {
2075 continue;
2076 }
2077 if (content->rejected && !transceiver->stopped()) {
2078 transceiver->Stop();
2079 }
Steve Anton74255ff2018-01-24 18:32:57 -08002080 const auto& streams = content->media_description()->streams();
2081 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002082 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002083 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002084 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002085 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002086 }
2087 }
2088 } else {
2089 // Plan B semantics.
2090
Steve Antondcc3c022017-12-22 16:02:54 -08002091 // Update state and SSRC of local MediaStreams and DataChannels based on the
2092 // local session description.
2093 const cricket::ContentInfo* audio_content =
2094 GetFirstAudioContent(local_description()->description());
2095 if (audio_content) {
2096 if (audio_content->rejected) {
2097 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2098 } else {
2099 const cricket::AudioContentDescription* audio_desc =
2100 audio_content->media_description()->as_audio();
2101 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2102 }
deadbeeffaac4972015-11-12 15:33:07 -08002103 }
deadbeefab9b2d12015-10-14 11:33:11 -07002104
Steve Antondcc3c022017-12-22 16:02:54 -08002105 const cricket::ContentInfo* video_content =
2106 GetFirstVideoContent(local_description()->description());
2107 if (video_content) {
2108 if (video_content->rejected) {
2109 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2110 } else {
2111 const cricket::VideoContentDescription* video_desc =
2112 video_content->media_description()->as_video();
2113 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2114 }
deadbeeffaac4972015-11-12 15:33:07 -08002115 }
deadbeefab9b2d12015-10-14 11:33:11 -07002116 }
2117
2118 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002119 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002120 if (data_content) {
2121 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002122 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002123 if (rtc::starts_with(data_desc->protocol().data(),
2124 cricket::kMediaProtocolRtpPrefix)) {
2125 UpdateLocalRtpDataChannels(data_desc->streams());
2126 }
2127 }
2128
Steve Anton8a006912017-12-04 15:25:56 -08002129 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130}
2131
2132void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002133 SetSessionDescriptionObserver* observer,
2134 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002135 SetRemoteDescription(
2136 std::unique_ptr<SessionDescriptionInterface>(desc),
2137 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2138 new SetRemoteDescriptionObserverAdapter(this, observer)));
2139}
2140
2141void PeerConnection::SetRemoteDescription(
2142 std::unique_ptr<SessionDescriptionInterface> desc,
2143 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002144 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002145
nisse7ce109a2017-01-31 00:57:56 -08002146 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002147 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 return;
2149 }
Steve Anton8a006912017-12-04 15:25:56 -08002150
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002152 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002153 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 return;
2155 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002156
Steve Anton80dd7b52018-02-16 17:08:42 -08002157 // If a session error has occurred the PeerConnection is in a possibly
2158 // inconsistent state so fail right away.
2159 if (session_error() != SessionError::kNone) {
2160 std::string error_message = GetSessionErrorMsg();
2161 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2162 observer->OnSetRemoteDescriptionComplete(
2163 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2164 return;
2165 }
Steve Anton71439a62018-02-15 11:53:06 -08002166
Steve Anton80dd7b52018-02-16 17:08:42 -08002167 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002168 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 std::string error_message = GetSetDescriptionErrorMessage(
2170 cricket::CS_REMOTE, desc->GetType(), error);
2171 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002172 observer->OnSetRemoteDescriptionComplete(
2173 RTCError(error.type(), std::move(error_message)));
2174 return;
2175 }
Steve Anton71439a62018-02-15 11:53:06 -08002176
Steve Anton80dd7b52018-02-16 17:08:42 -08002177 // Grab the description type before moving ownership to
2178 // ApplyRemoteDescription, which may destroy it before returning.
2179 const SdpType type = desc->GetType();
2180
2181 error = ApplyRemoteDescription(std::move(desc));
2182 // |desc| may be destroyed at this point.
2183
2184 if (!error.ok()) {
2185 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2186 // inconsistent state, so act conservatively here and set the session error
2187 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2188 SetSessionError(SessionError::kContent, error.message());
2189 std::string error_message =
2190 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2191 RTC_LOG(LS_ERROR) << error_message;
2192 observer->OnSetRemoteDescriptionComplete(
2193 RTCError(error.type(), std::move(error_message)));
2194 return;
2195 }
2196 RTC_DCHECK(remote_description());
2197
Steve Anton8e20f172018-03-06 10:55:04 -08002198 if (type == SdpType::kOffer) {
2199 // Report to UMA the format of the received offer.
2200 ReportSdpFormatReceived(*remote_description());
2201 }
2202
Steve Anton80dd7b52018-02-16 17:08:42 -08002203 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002204 // TODO(deadbeef): We already had to hop to the network thread for
2205 // MaybeStartGathering...
2206 network_thread()->Invoke<void>(
2207 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2208 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002209 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002210 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002211 }
2212
2213 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2214}
2215
2216RTCError PeerConnection::ApplyRemoteDescription(
2217 std::unique_ptr<SessionDescriptionInterface> desc) {
2218 RTC_DCHECK_RUN_ON(signaling_thread());
2219 RTC_DCHECK(desc);
2220
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 // Update stats here so that we have the most recent stats for tracks and
2222 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002223 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002224
Steve Antondcc3c022017-12-22 16:02:54 -08002225 // Take a reference to the old remote description since it's used below to
2226 // compare against the new remote description. When setting the new remote
2227 // description, grab ownership of the replaced session description in case it
2228 // is the same as |old_remote_description|, to keep it alive for the duration
2229 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002230 const SessionDescriptionInterface* old_remote_description =
2231 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002232 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002233 SdpType type = desc->GetType();
2234 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002235 replaced_remote_description = pending_remote_description_
2236 ? std::move(pending_remote_description_)
2237 : std::move(current_remote_description_);
2238 current_remote_description_ = std::move(desc);
2239 pending_remote_description_ = nullptr;
2240 current_local_description_ = std::move(pending_local_description_);
2241 } else {
2242 replaced_remote_description = std::move(pending_remote_description_);
2243 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 }
Steve Anton8a006912017-12-04 15:25:56 -08002245 // The session description to apply now must be accessed by
2246 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002247 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248
Steve Anton8a006912017-12-04 15:25:56 -08002249 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002250 if (IsUnifiedPlan()) {
2251 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002252 cricket::CS_REMOTE, *remote_description(), local_description(),
2253 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002254 if (!error.ok()) {
2255 return error;
2256 }
Steve Antondcc3c022017-12-22 16:02:54 -08002257 } else {
2258 if (type == SdpType::kOffer) {
2259 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2260 // description is applied. Restore back to old description.
2261 RTCError error = CreateChannels(*remote_description()->description());
2262 if (!error.ok()) {
2263 return error;
2264 }
2265 }
Steve Anton8a006912017-12-04 15:25:56 -08002266
Steve Antondcc3c022017-12-22 16:02:54 -08002267 // Remove unused channels if MediaContentDescription is rejected.
2268 RemoveUnusedChannels(remote_description()->description());
2269 }
Steve Anton8a006912017-12-04 15:25:56 -08002270
2271 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2272 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002273 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002274 if (!error.ok()) {
2275 return error;
2276 }
2277
2278 if (local_description() &&
2279 !UseCandidatesInSessionDescription(remote_description())) {
2280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2281 }
2282
2283 if (old_remote_description) {
2284 for (const cricket::ContentInfo& content :
2285 old_remote_description->description()->contents()) {
2286 // Check if this new SessionDescription contains new ICE ufrag and
2287 // password that indicates the remote peer requests an ICE restart.
2288 // TODO(deadbeef): When we start storing both the current and pending
2289 // remote description, this should reset pending_ice_restarts and compare
2290 // against the current description.
2291 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2292 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002293 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002294 pending_ice_restarts_.insert(content.name);
2295 }
2296 } else {
2297 // We retain all received candidates only if ICE is not restarted.
2298 // When ICE is restarted, all previous candidates belong to an old
2299 // generation and should not be kept.
2300 // TODO(deadbeef): This goes against the W3C spec which says the remote
2301 // description should only contain candidates from the last set remote
2302 // description plus any candidates added since then. We should remove
2303 // this once we're sure it won't break anything.
2304 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2305 old_remote_description, content.name, mutable_remote_description());
2306 }
2307 }
2308 }
2309
2310 if (session_error() != SessionError::kNone) {
2311 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2312 }
2313
2314 // Set the the ICE connection state to connecting since the connection may
2315 // become writable with peer reflexive candidates before any remote candidate
2316 // is signaled.
2317 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2318 // is to have a new signal the indicates a change in checking state from the
2319 // transport and expose a new checking() member from transport that can be
2320 // read to determine the current checking state. The existing SignalConnecting
2321 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002322 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002323 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2324 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2325 }
2326
deadbeefab9b2d12015-10-14 11:33:11 -07002327 // If setting the description decided our SSL role, allocate any necessary
2328 // SCTP sids.
2329 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002330 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002331 AllocateSctpSids(role);
2332 }
2333
Steve Antondcc3c022017-12-22 16:02:54 -08002334 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002335 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2336 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002337 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002338 for (auto transceiver : transceivers_) {
2339 const ContentInfo* content =
2340 FindMediaSectionForTransceiver(transceiver, remote_description());
2341 if (!content) {
2342 continue;
2343 }
2344 const MediaContentDescription* media_desc = content->media_description();
2345 RtpTransceiverDirection local_direction =
2346 RtpTransceiverDirectionReversed(media_desc->direction());
2347 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2348 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2349 // transceiver's current direction is neither sendrecv nor recvonly,
2350 // process the addition of a remote track for the media description.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002351 //
2352 // Create a sync label in the case of an unsignalled msid.
2353 std::string sync_label = rtc::CreateRandomUuid();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002354 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002355 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002356 if (!stream_params.stream_ids().empty()) {
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002357 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002358 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002359 }
Steve Antondcc3c022017-12-22 16:02:54 -08002360 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2361 (!transceiver->current_direction() ||
2362 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002363 *transceiver->current_direction()))) {
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002364 rtc::scoped_refptr<MediaStreamInterface> stream =
2365 remote_streams_->find(sync_label);
2366 if (!stream) {
2367 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2368 MediaStream::Create(sync_label));
2369 remote_streams_->AddStream(stream);
2370 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002371 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002372 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002373 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002374 }
2375 // If direction is sendonly or inactive, and transceiver's current
2376 // direction is neither sendonly nor inactive, process the removal of a
2377 // remote track for the media description.
2378 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002379 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002380 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002381 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002382 }
2383 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2384 transceiver->internal()->set_current_direction(local_direction);
2385 }
2386 if (content->rejected && !transceiver->stopped()) {
2387 transceiver->Stop();
2388 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002389 if (!content->rejected &&
2390 RtpTransceiverDirectionHasRecv(local_direction)) {
2391 // Set ssrc to 0 in the case of an unsignalled ssrc.
2392 uint32_t ssrc = 0;
2393 if (!media_desc->streams().empty()) {
2394 ssrc = media_desc->streams()[0].first_ssrc();
2395 }
2396 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002397 }
Steve Antondcc3c022017-12-22 16:02:54 -08002398 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002399 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002400 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002401 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002402 observer_->OnTrack(transceiver);
2403 observer_->OnAddTrack(transceiver->receiver(),
2404 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002405 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002406 for (auto stream : added_streams) {
2407 observer_->OnAddStream(stream);
2408 }
Steve Antondcc3c022017-12-22 16:02:54 -08002409 }
2410
Henrik Boströmfdb92012017-11-09 19:55:44 +01002411 const cricket::ContentInfo* audio_content =
2412 GetFirstAudioContent(remote_description()->description());
2413 const cricket::ContentInfo* video_content =
2414 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002415 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002416 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002417 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002418 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002419 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002420 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002421
2422 // Check if the descriptions include streams, just in case the peer supports
2423 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002424 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002425 (audio_desc && !audio_desc->streams().empty()) ||
2426 (video_desc && !video_desc->streams().empty())) {
2427 remote_peer_supports_msid_ = true;
2428 }
deadbeefab9b2d12015-10-14 11:33:11 -07002429
2430 // We wait to signal new streams until we finish processing the description,
2431 // since only at that point will new streams have all their tracks.
2432 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2433
Steve Antondcc3c022017-12-22 16:02:54 -08002434 if (!IsUnifiedPlan()) {
2435 // TODO(steveanton): When removing RTP senders/receivers in response to a
2436 // rejected media section, there is some cleanup logic that expects the
2437 // voice/ video channel to still be set. But in this method the voice/video
2438 // channel would have been destroyed by the SetRemoteDescription caller
2439 // above so the cleanup that relies on them fails to run. The RemoveSenders
2440 // calls should be moved to right before the DestroyChannel calls to fix
2441 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002442
Steve Antondcc3c022017-12-22 16:02:54 -08002443 // Find all audio rtp streams and create corresponding remote AudioTracks
2444 // and MediaStreams.
2445 if (audio_content) {
2446 if (audio_content->rejected) {
2447 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2448 } else {
2449 bool default_audio_track_needed =
2450 !remote_peer_supports_msid_ &&
2451 RtpTransceiverDirectionHasSend(audio_desc->direction());
2452 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2453 default_audio_track_needed, audio_desc->type(),
2454 new_streams);
2455 }
deadbeeffaac4972015-11-12 15:33:07 -08002456 }
deadbeefab9b2d12015-10-14 11:33:11 -07002457
Steve Antondcc3c022017-12-22 16:02:54 -08002458 // Find all video rtp streams and create corresponding remote VideoTracks
2459 // and MediaStreams.
2460 if (video_content) {
2461 if (video_content->rejected) {
2462 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2463 } else {
2464 bool default_video_track_needed =
2465 !remote_peer_supports_msid_ &&
2466 RtpTransceiverDirectionHasSend(video_desc->direction());
2467 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2468 default_video_track_needed, video_desc->type(),
2469 new_streams);
2470 }
deadbeeffaac4972015-11-12 15:33:07 -08002471 }
deadbeefab9b2d12015-10-14 11:33:11 -07002472
Steve Antondcc3c022017-12-22 16:02:54 -08002473 // Update the DataChannels with the information from the remote peer.
2474 if (data_desc) {
2475 if (rtc::starts_with(data_desc->protocol().data(),
2476 cricket::kMediaProtocolRtpPrefix)) {
2477 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2478 }
deadbeefab9b2d12015-10-14 11:33:11 -07002479 }
deadbeefab9b2d12015-10-14 11:33:11 -07002480
Steve Antondcc3c022017-12-22 16:02:54 -08002481 // Iterate new_streams and notify the observer about new MediaStreams.
2482 for (size_t i = 0; i < new_streams->count(); ++i) {
2483 MediaStreamInterface* new_stream = new_streams->at(i);
2484 stats_->AddStream(new_stream);
2485 observer_->OnAddStream(
2486 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2487 }
deadbeefab9b2d12015-10-14 11:33:11 -07002488
Steve Antondcc3c022017-12-22 16:02:54 -08002489 UpdateEndedRemoteMediaStreams();
2490 }
deadbeefab9b2d12015-10-14 11:33:11 -07002491
Steve Anton8a006912017-12-04 15:25:56 -08002492 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002493}
2494
Steve Antondcc3c022017-12-22 16:02:54 -08002495RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2496 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002497 const SessionDescriptionInterface& new_session,
2498 const SessionDescriptionInterface* old_local_description,
2499 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002500 RTC_DCHECK(IsUnifiedPlan());
2501
Steve Anton7464fca2018-01-19 11:10:37 -08002502 const cricket::ContentGroup* bundle_group = nullptr;
2503 if (new_session.GetType() == SdpType::kOffer) {
2504 auto bundle_group_or_error =
2505 GetEarlyBundleGroup(*new_session.description());
2506 if (!bundle_group_or_error.ok()) {
2507 return bundle_group_or_error.MoveError();
2508 }
2509 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002510 }
Steve Antondcc3c022017-12-22 16:02:54 -08002511
Steve Antondcc3c022017-12-22 16:02:54 -08002512 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002513 for (size_t i = 0; i < new_contents.size(); ++i) {
2514 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002515 cricket::MediaType media_type = new_content.media_description()->type();
2516 seen_mids_.insert(new_content.name);
2517 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2518 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002519 const cricket::ContentInfo* old_local_content = nullptr;
2520 if (old_local_description &&
2521 i < old_local_description->description()->contents().size()) {
2522 old_local_content =
2523 &old_local_description->description()->contents()[i];
2524 }
2525 const cricket::ContentInfo* old_remote_content = nullptr;
2526 if (old_remote_description &&
2527 i < old_remote_description->description()->contents().size()) {
2528 old_remote_content =
2529 &old_remote_description->description()->contents()[i];
2530 }
Steve Antondcc3c022017-12-22 16:02:54 -08002531 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002532 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2533 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002534 if (!transceiver_or_error.ok()) {
2535 return transceiver_or_error.MoveError();
2536 }
2537 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002538 RTCError error =
2539 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2540 if (!error.ok()) {
2541 return error;
2542 }
2543 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002544 if (GetDataMid() && new_content.name != *GetDataMid()) {
2545 // Ignore all but the first data section.
2546 continue;
2547 }
2548 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2549 if (!error.ok()) {
2550 return error;
2551 }
Steve Antondcc3c022017-12-22 16:02:54 -08002552 } else {
2553 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2554 "Unknown section type.");
2555 }
2556 }
2557
2558 return RTCError::OK();
2559}
2560
2561RTCError PeerConnection::UpdateTransceiverChannel(
2562 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2563 transceiver,
2564 const cricket::ContentInfo& content,
2565 const cricket::ContentGroup* bundle_group) {
2566 RTC_DCHECK(IsUnifiedPlan());
2567 RTC_DCHECK(transceiver);
2568 cricket::BaseChannel* channel = transceiver->internal()->channel();
2569 if (content.rejected) {
2570 if (channel) {
2571 transceiver->internal()->SetChannel(nullptr);
2572 DestroyBaseChannel(channel);
2573 }
2574 } else {
2575 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002576 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002577 channel = CreateVoiceChannel(
2578 content.name,
2579 GetTransportNameForMediaSection(content.name, bundle_group));
2580 } else {
Steve Anton69470252018-02-09 11:43:08 -08002581 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002582 channel = CreateVideoChannel(
2583 content.name,
2584 GetTransportNameForMediaSection(content.name, bundle_group));
2585 }
2586 if (!channel) {
2587 LOG_AND_RETURN_ERROR(
2588 RTCErrorType::INTERNAL_ERROR,
2589 "Failed to create channel for mid=" + content.name);
2590 }
2591 transceiver->internal()->SetChannel(channel);
2592 }
2593 }
2594 return RTCError::OK();
2595}
2596
Steve Antonfa2260d2017-12-28 16:38:23 -08002597RTCError PeerConnection::UpdateDataChannel(
2598 cricket::ContentSource source,
2599 const cricket::ContentInfo& content,
2600 const cricket::ContentGroup* bundle_group) {
2601 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002602 // If data channels are disabled, ignore this media section. CreateAnswer
2603 // will take care of rejecting it.
2604 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002605 }
2606 if (content.rejected) {
2607 DestroyDataChannel();
2608 } else {
2609 if (!rtp_data_channel_ && !sctp_transport_) {
2610 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2611 content.name, bundle_group))) {
2612 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2613 "Failed to create data channel.");
2614 }
2615 }
2616 if (source == cricket::CS_REMOTE) {
2617 const MediaContentDescription* data_desc = content.media_description();
2618 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2619 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2620 }
2621 }
2622 }
2623 return RTCError::OK();
2624}
2625
Steve Antondcc3c022017-12-22 16:02:54 -08002626RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2627PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002628 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002629 size_t mline_index,
2630 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002631 const ContentInfo* old_local_content,
2632 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002633 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002634 // If this is an offer then the m= section might be recycled. If the m=
2635 // section is being recycled (defined as: rejected in the current local or
2636 // remote description and not rejected in new description), dissociate the
2637 // currently associated RtpTransceiver by setting its mid property to null,
2638 // and discard the mapping between the transceiver and its m= section index.
2639 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2640 old_remote_content)) {
2641 // We want to dissociate the transceiver that has the rejected mid.
2642 const std::string& old_mid =
2643 (old_local_content && old_local_content->rejected)
2644 ? old_local_content->name
2645 : old_remote_content->name;
2646 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002647 if (old_transceiver) {
2648 old_transceiver->internal()->set_mid(rtc::nullopt);
2649 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2650 }
2651 }
2652 const MediaContentDescription* media_desc = content.media_description();
2653 auto transceiver = GetAssociatedTransceiver(content.name);
2654 if (source == cricket::CS_LOCAL) {
2655 // Find the RtpTransceiver that corresponds to this m= section, using the
2656 // mapping between transceivers and m= section indices established when
2657 // creating the offer.
2658 if (!transceiver) {
2659 transceiver = GetTransceiverByMLineIndex(mline_index);
2660 }
2661 if (!transceiver) {
2662 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2663 "Unknown transceiver");
2664 }
2665 } else {
2666 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2667 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2668 // of the same type...
2669 if (!transceiver &&
2670 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2671 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2672 }
2673 // If no RtpTransceiver was found in the previous step, create one with a
2674 // recvonly direction.
2675 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002676 auto sender =
2677 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002678 std::string receiver_id;
2679 if (!media_desc->streams().empty()) {
2680 receiver_id = media_desc->streams()[0].id;
2681 } else {
2682 receiver_id = rtc::CreateRandomUuid();
2683 }
2684 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002685 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002686 transceiver->internal()->set_direction(
2687 RtpTransceiverDirection::kRecvOnly);
2688 }
2689 }
2690 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002691 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002692 LOG_AND_RETURN_ERROR(
2693 RTCErrorType::INVALID_PARAMETER,
2694 "Transceiver type does not match media description type.");
2695 }
2696 // Associate the found or created RtpTransceiver with the m= section by
2697 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2698 // section, and establish a mapping between the transceiver and the index of
2699 // the m= section.
2700 transceiver->internal()->set_mid(content.name);
2701 transceiver->internal()->set_mline_index(mline_index);
2702 return std::move(transceiver);
2703}
2704
2705rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2706PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2707 RTC_DCHECK(IsUnifiedPlan());
2708 for (auto transceiver : transceivers_) {
2709 if (transceiver->mid() == mid) {
2710 return transceiver;
2711 }
2712 }
2713 return nullptr;
2714}
2715
2716rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2717PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2718 RTC_DCHECK(IsUnifiedPlan());
2719 for (auto transceiver : transceivers_) {
2720 if (transceiver->internal()->mline_index() == mline_index) {
2721 return transceiver;
2722 }
2723 }
2724 return nullptr;
2725}
2726
2727rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2728PeerConnection::FindAvailableTransceiverToReceive(
2729 cricket::MediaType media_type) const {
2730 RTC_DCHECK(IsUnifiedPlan());
2731 // From JSEP section 5.10 (Applying a Remote Description):
2732 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2733 // the same type that were added to the PeerConnection by addTrack and are not
2734 // associated with any m= section and are not stopped, find the first such
2735 // RtpTransceiver.
2736 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002737 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002738 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2739 !transceiver->stopped()) {
2740 return transceiver;
2741 }
2742 }
2743 return nullptr;
2744}
2745
Steve Antoned10bd92017-12-05 10:52:59 -08002746const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2747 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2748 transceiver,
2749 const SessionDescriptionInterface* sdesc) const {
2750 RTC_DCHECK(transceiver);
2751 RTC_DCHECK(sdesc);
2752 if (IsUnifiedPlan()) {
2753 if (!transceiver->internal()->mid()) {
2754 // This transceiver is not associated with a media section yet.
2755 return nullptr;
2756 }
2757 return sdesc->description()->GetContentByName(
2758 *transceiver->internal()->mid());
2759 } else {
2760 // Plan B only allows at most one audio and one video section, so use the
2761 // first media section of that type.
2762 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002763 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002764 }
2765}
2766
deadbeef46c73892016-11-16 19:42:04 -08002767PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2768 return configuration_;
2769}
2770
deadbeef293e9262017-01-11 12:28:30 -08002771bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2772 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002773 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002774
Steve Anton75737c02017-11-06 10:37:17 -08002775 if (local_description() && configuration.ice_candidate_pool_size !=
2776 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002777 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2778 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002779 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002780 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002781
deadbeef293e9262017-01-11 12:28:30 -08002782 // The simplest (and most future-compatible) way to tell if the config was
2783 // modified in an invalid way is to copy each property we do support
2784 // modifying, then use operator==. There are far more properties we don't
2785 // support modifying than those we do, and more could be added.
2786 RTCConfiguration modified_config = configuration_;
2787 modified_config.servers = configuration.servers;
2788 modified_config.type = configuration.type;
2789 modified_config.ice_candidate_pool_size =
2790 configuration.ice_candidate_pool_size;
2791 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002792 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002793 modified_config.ice_check_interval_strong_connectivity =
2794 configuration.ice_check_interval_strong_connectivity;
2795 modified_config.ice_check_interval_weak_connectivity =
2796 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002797 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2798 modified_config.ice_unwritable_min_checks =
2799 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002800 modified_config.stun_candidate_keepalive_interval =
2801 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002802 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002803 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002804 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002805 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002806 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2807 }
2808
Steve Anton038834f2017-07-14 15:59:59 -07002809 // Validate the modified configuration.
2810 RTCError validate_error = ValidateConfiguration(modified_config);
2811 if (!validate_error.ok()) {
2812 return SafeSetError(std::move(validate_error), error);
2813 }
2814
deadbeef293e9262017-01-11 12:28:30 -08002815 // Note that this isn't possible through chromium, since it's an unsigned
2816 // short in WebIDL.
2817 if (configuration.ice_candidate_pool_size < 0 ||
2818 configuration.ice_candidate_pool_size > UINT16_MAX) {
2819 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2820 }
2821
2822 // Parse ICE servers before hopping to network thread.
2823 cricket::ServerAddresses stun_servers;
2824 std::vector<cricket::RelayServerConfig> turn_servers;
2825 RTCErrorType parse_error =
2826 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2827 if (parse_error != RTCErrorType::NONE) {
2828 return SafeSetError(parse_error, error);
2829 }
2830
2831 // In theory this shouldn't fail.
2832 if (!network_thread()->Invoke<bool>(
2833 RTC_FROM_HERE,
2834 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2835 stun_servers, turn_servers, modified_config.type,
2836 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002837 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002838 modified_config.turn_customizer,
2839 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002840 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002841 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2842 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002843
deadbeefd1a38b52016-12-10 13:15:33 -08002844 // As described in JSEP, calling setConfiguration with new ICE servers or
2845 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2846 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002847 if (modified_config.servers != configuration_.servers ||
2848 modified_config.type != configuration_.type ||
2849 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002850 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002851 }
skvladd1f5fda2017-02-03 16:54:05 -08002852
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002853 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002854
deadbeef293e9262017-01-11 12:28:30 -08002855 configuration_ = modified_config;
2856 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002857}
2858
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859bool PeerConnection::AddIceCandidate(
2860 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002861 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002862 if (IsClosed()) {
2863 return false;
2864 }
Steve Antond25da372017-11-06 14:50:29 -08002865
2866 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002867 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002868 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002869 return false;
2870 }
2871
2872 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002873 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002874 return false;
2875 }
2876
2877 bool valid = false;
2878 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2879 if (!valid) {
2880 return false;
2881 }
2882
2883 // Add this candidate to the remote session description.
2884 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002885 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002886 return false;
2887 }
2888
2889 if (ready) {
2890 return UseCandidate(ice_candidate);
2891 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002892 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002893 return true;
2894 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895}
2896
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002897bool PeerConnection::RemoveIceCandidates(
2898 const std::vector<cricket::Candidate>& candidates) {
2899 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002900 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002901 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002902 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002903 return false;
2904 }
2905
2906 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002907 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002908 return false;
2909 }
2910
2911 size_t number_removed =
2912 mutable_remote_description()->RemoveCandidates(candidates);
2913 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002914 RTC_LOG(LS_ERROR)
2915 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002916 "Requested "
2917 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002918 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002919 }
2920
2921 // Remove the candidates from the transport controller.
2922 std::string error;
2923 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2924 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002925 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002926 }
2927 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002928}
2929
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002930void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002931 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002932 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002933
Steve Anton75737c02017-11-06 10:37:17 -08002934 if (transport_controller()) {
2935 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002936 }
2937
Steve Antondb67ba12018-03-19 17:41:42 -07002938 for (auto transceiver : transceivers_) {
2939 auto* channel = transceiver->internal()->channel();
2940 if (channel) {
2941 channel->SetMetricsObserver(uma_observer_);
2942 }
2943 }
2944
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002945 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002946 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002947 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002948 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002949 uma_observer_->IncrementEnumCounter(
2950 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2951 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002952 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002953 uma_observer_->IncrementEnumCounter(
2954 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2955 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002956 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002957 // Send information about the requested SDP semantics.
2958 switch (configuration_.sdp_semantics) {
2959 case SdpSemantics::kDefault:
2960 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2961 kSdpSemanticRequestDefault,
2962 kSdpSemanticRequestMax);
2963
2964 break;
2965 case SdpSemantics::kPlanB:
2966 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2967 kSdpSemanticRequestPlanB,
2968 kSdpSemanticRequestMax);
2969 break;
2970 case SdpSemantics::kUnifiedPlan:
2971 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2972 kSdpSemanticRequestUnifiedPlan,
2973 kSdpSemanticRequestMax);
2974 break;
2975 default:
2976 RTC_NOTREACHED();
2977 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002978 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002979}
2980
zstein4b979802017-06-02 14:37:37 -07002981RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002982 if (!worker_thread()->IsCurrent()) {
2983 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002984 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2985 }
2986
2987 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2988 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2989 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2990 if (has_min && *bitrate.min_bitrate_bps < 0) {
2991 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2992 "min_bitrate_bps <= 0");
2993 }
2994 if (has_current) {
2995 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2996 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2997 "current_bitrate_bps < min_bitrate_bps");
2998 } else if (*bitrate.current_bitrate_bps < 0) {
2999 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3000 "curent_bitrate_bps < 0");
3001 }
3002 }
3003 if (has_max) {
3004 if (has_current &&
3005 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3006 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3007 "max_bitrate_bps < current_bitrate_bps");
3008 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3009 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3010 "max_bitrate_bps < min_bitrate_bps");
3011 } else if (*bitrate.max_bitrate_bps < 0) {
3012 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3013 "max_bitrate_bps < 0");
3014 }
3015 }
3016
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003017 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003018 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3019 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3020 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3021
3022 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003023 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003024
3025 return RTCError::OK();
3026}
3027
Alex Narest78609d52017-10-20 10:37:47 +02003028void PeerConnection::SetBitrateAllocationStrategy(
3029 std::unique_ptr<rtc::BitrateAllocationStrategy>
3030 bitrate_allocation_strategy) {
3031 rtc::Thread* worker_thread = factory_->worker_thread();
3032 if (!worker_thread->IsCurrent()) {
3033 rtc::BitrateAllocationStrategy* strategy_raw =
3034 bitrate_allocation_strategy.release();
3035 auto functor = [this, strategy_raw]() {
3036 call_->SetBitrateAllocationStrategy(
3037 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3038 };
3039 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3040 return;
3041 }
3042 RTC_DCHECK(call_.get());
3043 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3044}
3045
henrika5f6bf242017-11-01 11:06:56 +01003046void PeerConnection::SetAudioPlayout(bool playout) {
3047 if (!worker_thread()->IsCurrent()) {
3048 worker_thread()->Invoke<void>(
3049 RTC_FROM_HERE,
3050 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3051 return;
3052 }
3053 auto audio_state =
3054 factory_->channel_manager()->media_engine()->GetAudioState();
3055 audio_state->SetPlayout(playout);
3056}
3057
3058void PeerConnection::SetAudioRecording(bool recording) {
3059 if (!worker_thread()->IsCurrent()) {
3060 worker_thread()->Invoke<void>(
3061 RTC_FROM_HERE,
3062 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3063 return;
3064 }
3065 auto audio_state =
3066 factory_->channel_manager()->media_engine()->GetAudioState();
3067 audio_state->SetRecording(recording);
3068}
3069
Steve Anton8c0f7a72017-10-03 10:03:10 -07003070std::unique_ptr<rtc::SSLCertificate>
3071PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003072 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3073 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003074 return nullptr;
3075 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003076 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003077}
3078
Zhi Huang70b820f2018-01-27 14:16:15 -08003079std::unique_ptr<rtc::SSLCertChain>
3080PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003081 auto audio_transceiver = GetFirstAudioTransceiver();
3082 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003083 return nullptr;
3084 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003085 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003086 audio_transceiver->internal()->channel()->transport_name());
3087}
3088
3089rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3090PeerConnection::GetFirstAudioTransceiver() const {
3091 for (auto transceiver : transceivers_) {
3092 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3093 return transceiver;
3094 }
3095 }
3096 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003097}
3098
ivoc14d5dbe2016-07-04 07:06:55 -07003099bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3100 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003101 // TODO(eladalon): It would be better to not allow negative values into PC.
3102 const size_t max_size = (max_size_bytes < 0)
3103 ? RtcEventLog::kUnlimitedOutput
3104 : rtc::saturated_cast<size_t>(max_size_bytes);
3105 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003106 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3107 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003108}
3109
Bjorn Tereliusde939432017-11-20 17:38:14 +01003110bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3111 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003112 // TODO(eladalon): In C++14, this can be done with a lambda.
3113 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003114 bool operator()() {
3115 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3116 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003117 PeerConnection* const pc;
3118 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003119 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003120 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003121 return worker_thread()->Invoke<bool>(
3122 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003123}
3124
3125void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003126 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003127 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3128}
3129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003130const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003131 return pending_local_description_ ? pending_local_description_.get()
3132 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133}
3134
3135const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003136 return pending_remote_description_ ? pending_remote_description_.get()
3137 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138}
3139
deadbeeffe4a8a42016-12-20 17:56:17 -08003140const SessionDescriptionInterface* PeerConnection::current_local_description()
3141 const {
Steve Anton75737c02017-11-06 10:37:17 -08003142 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003143}
3144
3145const SessionDescriptionInterface* PeerConnection::current_remote_description()
3146 const {
Steve Anton75737c02017-11-06 10:37:17 -08003147 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003148}
3149
3150const SessionDescriptionInterface* PeerConnection::pending_local_description()
3151 const {
Steve Anton75737c02017-11-06 10:37:17 -08003152 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003153}
3154
3155const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3156 const {
Steve Anton75737c02017-11-06 10:37:17 -08003157 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003158}
3159
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003161 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 // Update stats here so that we have the most recent stats for tracks and
3163 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003164 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003165
Steve Anton75737c02017-11-06 10:37:17 -08003166 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003167
Steve Anton8af21862017-12-15 11:20:13 -08003168 for (auto transceiver : transceivers_) {
3169 transceiver->Stop();
3170 }
3171 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003172
Qingsi Wang93a84392018-01-30 17:13:09 -08003173 // The event log is used in the transport controller, which must be outlived
3174 // by the former. CreateOffer by the peer connection is implemented
3175 // asynchronously and if the peer connection is closed without resetting the
3176 // WebRTC session description factory, the session description factory would
3177 // call the transport controller.
3178 webrtc_session_desc_factory_.reset();
3179 transport_controller_.reset();
3180
deadbeef42a42632017-03-10 15:18:00 -08003181 network_thread()->Invoke<void>(
3182 RTC_FROM_HERE,
3183 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3184 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003185
Steve Anton978b8762017-09-29 12:15:02 -07003186 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003187 call_.reset();
3188 // The event log must outlive call (and any other object that uses it).
3189 event_log_.reset();
3190 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003191}
3192
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003193void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3196 SetSessionDescriptionMsg* param =
3197 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3198 param->observer->OnSuccess();
3199 delete param;
3200 break;
3201 }
3202 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3203 SetSessionDescriptionMsg* param =
3204 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003205 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206 delete param;
3207 break;
3208 }
deadbeefab9b2d12015-10-14 11:33:11 -07003209 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3210 CreateSessionDescriptionMsg* param =
3211 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003212 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003213 delete param;
3214 break;
3215 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 case MSG_GETSTATS: {
3217 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003218 StatsReports reports;
3219 stats_->GetStats(param->track, &reports);
3220 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003221 delete param;
3222 break;
3223 }
deadbeefbd292462015-12-14 18:15:29 -08003224 case MSG_FREE_DATACHANNELS: {
3225 sctp_data_channels_to_free_.clear();
3226 break;
3227 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003229 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230 break;
3231 }
3232}
3233
Steve Antonafb0bb72018-02-20 11:35:37 -08003234cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3235 RTC_DCHECK(!IsUnifiedPlan());
3236 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3237 GetAudioTransceiver()->internal()->channel());
3238 if (voice_channel) {
3239 return voice_channel->media_channel();
3240 } else {
3241 return nullptr;
3242 }
3243}
3244
3245cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3246 RTC_DCHECK(!IsUnifiedPlan());
3247 auto* video_channel = static_cast<cricket::VideoChannel*>(
3248 GetVideoTransceiver()->internal()->channel());
3249 if (video_channel) {
3250 return video_channel->media_channel();
3251 } else {
3252 return nullptr;
3253 }
3254}
3255
Steve Anton4171afb2017-11-20 10:20:22 -08003256void PeerConnection::CreateAudioReceiver(
3257 MediaStreamInterface* stream,
3258 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003259 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3260 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003261 auto* audio_receiver = new AudioRtpReceiver(
3262 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003263 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003264 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3265 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3266 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003267 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003268 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269}
3270
Steve Anton4171afb2017-11-20 10:20:22 -08003271void PeerConnection::CreateVideoReceiver(
3272 MediaStreamInterface* stream,
3273 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003274 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3275 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003276 auto* video_receiver = new VideoRtpReceiver(
3277 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003278 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003279 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3280 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3281 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003282 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003283 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284}
3285
deadbeef70ab1a12015-09-28 16:53:55 -07003286// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3287// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003288rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003289 const RtpSenderInfo& remote_sender_info) {
3290 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3291 if (!receiver) {
3292 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3293 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003294 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003295 }
Steve Anton4171afb2017-11-20 10:20:22 -08003296 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3297 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3298 } else {
3299 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3300 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003301 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302}
3303
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003304void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3305 MediaStreamInterface* stream) {
3306 RTC_DCHECK(!IsClosed());
3307 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003308 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003309 // We already have a sender for this track, so just change the stream_id
3310 // so that it's correct in the next call to CreateOffer.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00003311 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003312 return;
3313 }
3314
3315 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003316 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003317 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003318 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003319 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003320 // If the sender has already been configured in SDP, we call SetSsrc,
3321 // which will connect the sender to the underlying transport. This can
3322 // occur if a local session description that contains the ID of the sender
3323 // is set before AddStream is called. It can also occur if the local
3324 // session description is not changed and RemoveStream is called, and
3325 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003326 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003327 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003328 if (sender_info) {
3329 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003330 }
3331}
3332
3333// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3334// indefinitely, when we have unified plan SDP.
3335void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3336 MediaStreamInterface* stream) {
3337 RTC_DCHECK(!IsClosed());
3338 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003339 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003340 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3341 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003342 return;
3343 }
Steve Anton4171afb2017-11-20 10:20:22 -08003344 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003345}
3346
3347void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3348 MediaStreamInterface* stream) {
3349 RTC_DCHECK(!IsClosed());
3350 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003351 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003352 // We already have a sender for this track, so just change the stream_id
3353 // so that it's correct in the next call to CreateOffer.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00003354 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003355 return;
3356 }
3357
3358 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003359 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003360 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003361 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003362 GetVideoTransceiver()->internal()->AddSender(new_sender);
3363 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003364 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003365 if (sender_info) {
3366 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003367 }
3368}
3369
3370void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3371 MediaStreamInterface* stream) {
3372 RTC_DCHECK(!IsClosed());
3373 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003374 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003375 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3376 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003377 return;
3378 }
Steve Anton4171afb2017-11-20 10:20:22 -08003379 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003380}
3381
Steve Antonba818672017-11-06 10:21:57 -08003382void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003383 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003384 if (ice_connection_state_ == new_state) {
3385 return;
3386 }
3387
deadbeefcbecd352015-09-23 11:50:27 -07003388 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003389 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003390 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003391 return;
3392 }
Steve Antonba818672017-11-06 10:21:57 -08003393
Mirko Bonadei675513b2017-11-09 11:09:25 +01003394 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3395 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003396 RTC_DCHECK(ice_connection_state_ !=
3397 PeerConnectionInterface::kIceConnectionClosed);
3398
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003399 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003400 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003401}
3402
3403void PeerConnection::OnIceGatheringChange(
3404 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003405 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 if (IsClosed()) {
3407 return;
3408 }
3409 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003410 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411}
3412
jbauch81bf7b02017-03-25 08:31:12 -07003413void PeerConnection::OnIceCandidate(
3414 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003415 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003416 if (IsClosed()) {
3417 return;
3418 }
jbauch81bf7b02017-03-25 08:31:12 -07003419 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003420}
3421
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003422void PeerConnection::OnIceCandidatesRemoved(
3423 const std::vector<cricket::Candidate>& candidates) {
3424 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003425 if (IsClosed()) {
3426 return;
3427 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003428 observer_->OnIceCandidatesRemoved(candidates);
3429}
3430
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003431void PeerConnection::ChangeSignalingState(
3432 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003433 RTC_DCHECK(signaling_thread()->IsCurrent());
3434 if (signaling_state_ == signaling_state) {
3435 return;
3436 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003437 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3438 << GetSignalingStateString(signaling_state_)
3439 << " New state: "
3440 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003441 signaling_state_ = signaling_state;
3442 if (signaling_state == kClosed) {
3443 ice_connection_state_ = kIceConnectionClosed;
3444 observer_->OnIceConnectionChange(ice_connection_state_);
3445 if (ice_gathering_state_ != kIceGatheringComplete) {
3446 ice_gathering_state_ = kIceGatheringComplete;
3447 observer_->OnIceGatheringChange(ice_gathering_state_);
3448 }
3449 }
3450 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003451}
3452
deadbeefeb459812015-12-15 19:24:43 -08003453void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3454 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003455 if (IsClosed()) {
3456 return;
3457 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003458 AddAudioTrack(track, stream);
3459 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003460}
3461
deadbeefeb459812015-12-15 19:24:43 -08003462void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3463 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003464 if (IsClosed()) {
3465 return;
3466 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003467 RemoveAudioTrack(track, stream);
3468 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003469}
3470
3471void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3472 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003473 if (IsClosed()) {
3474 return;
3475 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003476 AddVideoTrack(track, stream);
3477 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003478}
3479
3480void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3481 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003482 if (IsClosed()) {
3483 return;
3484 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003485 RemoveVideoTrack(track, stream);
3486 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003487}
3488
Henrik Boström31638672017-11-23 17:48:32 +01003489void PeerConnection::PostSetSessionDescriptionSuccess(
3490 SetSessionDescriptionObserver* observer) {
3491 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3492 signaling_thread()->Post(RTC_FROM_HERE, this,
3493 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3494}
3495
deadbeefab9b2d12015-10-14 11:33:11 -07003496void PeerConnection::PostSetSessionDescriptionFailure(
3497 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003498 RTCError&& error) {
3499 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003500 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003501 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003502 signaling_thread()->Post(RTC_FROM_HERE, this,
3503 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003504}
3505
3506void PeerConnection::PostCreateSessionDescriptionFailure(
3507 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003508 RTCError error) {
3509 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003510 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003511 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003512 signaling_thread()->Post(RTC_FROM_HERE, this,
3513 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003514}
3515
zhihuang1c378ed2017-08-17 14:10:50 -07003516void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003517 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003518 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003519 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003520
Steve Antondcc3c022017-12-22 16:02:54 -08003521 if (IsUnifiedPlan()) {
3522 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3523 } else {
3524 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3525 }
3526
Steve Antonfa2260d2017-12-28 16:38:23 -08003527 // Intentionally unset the data channel type for RTP data channel with the
3528 // second condition. Otherwise the RTP data channels would be successfully
3529 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3530 // when building with chromium. We want to leave RTP data channels broken, so
3531 // people won't try to use them.
3532 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3533 session_options->data_channel_type = data_channel_type();
3534 }
3535
Steve Antondcc3c022017-12-22 16:02:54 -08003536 // Apply ICE restart flag and renomination flag.
3537 for (auto& options : session_options->media_description_options) {
3538 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3539 options.transport_options.enable_ice_renomination =
3540 configuration_.enable_ice_renomination;
3541 }
3542
3543 session_options->rtcp_cname = rtcp_cname_;
3544 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003545 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003546}
3547
3548void PeerConnection::GetOptionsForPlanBOffer(
3549 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3550 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003551 // Figure out transceiver directional preferences.
3552 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3553 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3554
3555 // By default, generate sendrecv/recvonly m= sections.
3556 bool recv_audio = true;
3557 bool recv_video = true;
3558
3559 // By default, only offer a new m= section if we have media to send with it.
3560 bool offer_new_audio_description = send_audio;
3561 bool offer_new_video_description = send_video;
3562 bool offer_new_data_description = HasDataChannels();
3563
3564 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003565 if (offer_answer_options.offer_to_receive_audio !=
3566 RTCOfferAnswerOptions::kUndefined) {
3567 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003568 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003569 offer_new_audio_description ||
3570 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003571 }
Steve Antondcc3c022017-12-22 16:02:54 -08003572 if (offer_answer_options.offer_to_receive_video !=
3573 RTCOfferAnswerOptions::kUndefined) {
3574 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003575 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003576 offer_new_video_description ||
3577 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003578 }
3579
3580 rtc::Optional<size_t> audio_index;
3581 rtc::Optional<size_t> video_index;
3582 rtc::Optional<size_t> data_index;
3583 // If a current description exists, generate m= sections in the same order,
3584 // using the first audio/video/data section that appears and rejecting
3585 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003586 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003587 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003588 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003589 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3590 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3591 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003592 }
3593
zhihuang1c378ed2017-08-17 14:10:50 -07003594 // Add audio/video/data m= sections to the end if needed.
3595 if (!audio_index && offer_new_audio_description) {
3596 session_options->media_description_options.push_back(
3597 cricket::MediaDescriptionOptions(
3598 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003599 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3600 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003601 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003602 }
zhihuang1c378ed2017-08-17 14:10:50 -07003603 if (!video_index && offer_new_video_description) {
3604 session_options->media_description_options.push_back(
3605 cricket::MediaDescriptionOptions(
3606 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003607 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3608 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003609 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003610 }
zhihuang1c378ed2017-08-17 14:10:50 -07003611 if (!data_index && offer_new_data_description) {
3612 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003613 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003614 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003615 }
3616
3617 cricket::MediaDescriptionOptions* audio_media_description_options =
3618 !audio_index ? nullptr
3619 : &session_options->media_description_options[*audio_index];
3620 cricket::MediaDescriptionOptions* video_media_description_options =
3621 !video_index ? nullptr
3622 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003623
Steve Anton4171afb2017-11-20 10:20:22 -08003624 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003625 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003626}
3627
3628// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3629// and return a reference to it.
3630// Generated MIDs should be no more than 3 bytes long to take up less space in
3631// the RTP packet.
3632static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3633 RTC_DCHECK(used_mids);
3634 // We're boring: just generate MIDs 0, 1, 2, ...
3635 size_t i = 0;
3636 std::set<std::string>::iterator it;
3637 bool inserted;
3638 do {
3639 std::string mid = rtc::ToString(i++);
3640 auto insert_result = used_mids->insert(mid);
3641 it = insert_result.first;
3642 inserted = insert_result.second;
3643 } while (!inserted);
3644 return *it;
3645}
3646
3647static cricket::MediaDescriptionOptions
3648GetMediaDescriptionOptionsForTransceiver(
3649 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3650 transceiver,
3651 const std::string& mid) {
3652 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003653 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003654 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003655 // This behavior is specified in JSEP. The gist is that:
3656 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3657 // sendrecv.
3658 // 2. If the MSID is included, then it must be included in any subsequent
3659 // offer/answer exactly the same until the RtpTransceiver is stopped.
3660 if (!transceiver->stopped() &&
3661 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3662 transceiver->internal()->has_ever_been_used_to_send())) {
3663 cricket::SenderOptions sender_options;
3664 sender_options.track_id = transceiver->sender()->id();
3665 sender_options.stream_ids = transceiver->sender()->stream_ids();
3666 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3667 // set in the RTP parameters when the transceiver was added.
3668 sender_options.num_sim_layers = 1;
3669 media_description_options.sender_options.push_back(sender_options);
3670 }
Steve Antondcc3c022017-12-22 16:02:54 -08003671 return media_description_options;
3672}
3673
3674void PeerConnection::GetOptionsForUnifiedPlanOffer(
3675 const RTCOfferAnswerOptions& offer_answer_options,
3676 cricket::MediaSessionOptions* session_options) {
3677 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3678 // Offers) and 5.2.2 (Subsequent Offers).
3679 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3680 const ContentInfos& local_contents =
3681 (local_description() ? local_description()->description()->contents()
3682 : ContentInfos());
3683 const ContentInfos& remote_contents =
3684 (remote_description() ? remote_description()->description()->contents()
3685 : ContentInfos());
3686 // The mline indices that can be recycled. New transceivers should reuse these
3687 // slots first.
3688 std::queue<size_t> recycleable_mline_indices;
3689 // Track the MIDs used in previous offer/answer exchanges and the current
3690 // offer so that new, unique MIDs are generated.
3691 std::set<std::string> used_mids = seen_mids_;
3692 // First, go through each media section that exists in either the local or
3693 // remote description and generate a media section in this offer for the
3694 // associated transceiver. If a media section can be recycled, generate a
3695 // default, rejected media section here that can be later overwritten.
3696 for (size_t i = 0;
3697 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3698 // Either |local_content| or |remote_content| is non-null.
3699 const ContentInfo* local_content =
3700 (i < local_contents.size() ? &local_contents[i] : nullptr);
3701 const ContentInfo* remote_content =
3702 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3703 bool had_been_rejected = (local_content && local_content->rejected) ||
3704 (remote_content && remote_content->rejected);
3705 const std::string& mid =
3706 (local_content ? local_content->name : remote_content->name);
3707 cricket::MediaType media_type =
3708 (local_content ? local_content->media_description()->type()
3709 : remote_content->media_description()->type());
3710 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3711 media_type == cricket::MEDIA_TYPE_VIDEO) {
3712 auto transceiver = GetAssociatedTransceiver(mid);
3713 RTC_CHECK(transceiver);
3714 // A media section is considered eligible for recycling if it is marked as
3715 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003716 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003717 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003718 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3719 RtpTransceiverDirection::kInactive,
3720 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003721 recycleable_mline_indices.push(i);
3722 } else {
3723 session_options->media_description_options.push_back(
3724 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3725 // CreateOffer shouldn't really cause any state changes in
3726 // PeerConnection, but we need a way to match new transceivers to new
3727 // media sections in SetLocalDescription and JSEP specifies this is done
3728 // by recording the index of the media section generated for the
3729 // transceiver in the offer.
3730 transceiver->internal()->set_mline_index(i);
3731 }
3732 } else {
3733 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003734 RTC_CHECK(GetDataMid());
3735 if (had_been_rejected || mid != *GetDataMid()) {
3736 session_options->media_description_options.push_back(
3737 GetMediaDescriptionOptionsForRejectedData(mid));
3738 } else {
3739 session_options->media_description_options.push_back(
3740 GetMediaDescriptionOptionsForActiveData(mid));
3741 }
Steve Antondcc3c022017-12-22 16:02:54 -08003742 }
3743 }
3744 // Next, look for transceivers that are newly added (that is, are not stopped
3745 // and not associated). Reuse media sections marked as recyclable first,
3746 // otherwise append to the end of the offer. New media sections should be
3747 // added in the order they were added to the PeerConnection.
3748 for (auto transceiver : transceivers_) {
3749 if (transceiver->mid() || transceiver->stopped()) {
3750 continue;
3751 }
3752 size_t mline_index;
3753 if (!recycleable_mline_indices.empty()) {
3754 mline_index = recycleable_mline_indices.front();
3755 recycleable_mline_indices.pop();
3756 session_options->media_description_options[mline_index] =
3757 GetMediaDescriptionOptionsForTransceiver(transceiver,
3758 AllocateMid(&used_mids));
3759 } else {
3760 mline_index = session_options->media_description_options.size();
3761 session_options->media_description_options.push_back(
3762 GetMediaDescriptionOptionsForTransceiver(transceiver,
3763 AllocateMid(&used_mids)));
3764 }
3765 // See comment above for why CreateOffer changes the transceiver's state.
3766 transceiver->internal()->set_mline_index(mline_index);
3767 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003768 // Lastly, add a m-section if we have local data channels and an m section
3769 // does not already exist.
3770 if (!GetDataMid() && HasDataChannels()) {
3771 session_options->media_description_options.push_back(
3772 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3773 }
Steve Antondcc3c022017-12-22 16:02:54 -08003774}
3775
3776void PeerConnection::GetOptionsForAnswer(
3777 const RTCOfferAnswerOptions& offer_answer_options,
3778 cricket::MediaSessionOptions* session_options) {
3779 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3780
3781 if (IsUnifiedPlan()) {
3782 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3783 } else {
3784 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3785 }
3786
Steve Antonfa2260d2017-12-28 16:38:23 -08003787 // Intentionally unset the data channel type for RTP data channel. Otherwise
3788 // the RTP data channels would be successfully negotiated by default and the
3789 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3790 // We want to leave RTP data channels broken, so people won't try to use them.
3791 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3792 session_options->data_channel_type = data_channel_type();
3793 }
3794
Steve Antondcc3c022017-12-22 16:02:54 -08003795 // Apply ICE renomination flag.
3796 for (auto& options : session_options->media_description_options) {
3797 options.transport_options.enable_ice_renomination =
3798 configuration_.enable_ice_renomination;
3799 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003800
3801 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003802 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003803 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003804}
3805
Steve Antondcc3c022017-12-22 16:02:54 -08003806void PeerConnection::GetOptionsForPlanBAnswer(
3807 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003808 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003809 // Figure out transceiver directional preferences.
3810 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3811 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3812
3813 // By default, generate sendrecv/recvonly m= sections. The direction is also
3814 // restricted by the direction in the offer.
3815 bool recv_audio = true;
3816 bool recv_video = true;
3817
3818 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003819 if (offer_answer_options.offer_to_receive_audio !=
3820 RTCOfferAnswerOptions::kUndefined) {
3821 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003822 }
Steve Antondcc3c022017-12-22 16:02:54 -08003823 if (offer_answer_options.offer_to_receive_video !=
3824 RTCOfferAnswerOptions::kUndefined) {
3825 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003826 }
3827
3828 rtc::Optional<size_t> audio_index;
3829 rtc::Optional<size_t> video_index;
3830 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003831
3832 // Generate m= sections that match those in the offer.
3833 // Note that mediasession.cc will handle intersection our preferred
3834 // direction with the offered direction.
3835 GenerateMediaDescriptionOptions(
3836 remote_description(),
3837 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3838 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3839 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003840
3841 cricket::MediaDescriptionOptions* audio_media_description_options =
3842 !audio_index ? nullptr
3843 : &session_options->media_description_options[*audio_index];
3844 cricket::MediaDescriptionOptions* video_media_description_options =
3845 !video_index ? nullptr
3846 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003847
Steve Anton4171afb2017-11-20 10:20:22 -08003848 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003849 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003850}
zhihuangaf388472016-11-02 16:49:48 -07003851
Steve Antondcc3c022017-12-22 16:02:54 -08003852void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3853 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3854 cricket::MediaSessionOptions* session_options) {
3855 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3856 // Answers) and 5.3.2 (Subsequent Answers).
3857 RTC_DCHECK(remote_description());
3858 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3859 for (const ContentInfo& content :
3860 remote_description()->description()->contents()) {
3861 cricket::MediaType media_type = content.media_description()->type();
3862 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3863 media_type == cricket::MEDIA_TYPE_VIDEO) {
3864 auto transceiver = GetAssociatedTransceiver(content.name);
3865 RTC_CHECK(transceiver);
3866 session_options->media_description_options.push_back(
3867 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3868 } else {
3869 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003870 // Reject all data sections if data channels are disabled.
3871 // Reject a data section if it has already been rejected.
3872 // Reject all data sections except for the first one.
3873 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3874 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003875 session_options->media_description_options.push_back(
3876 GetMediaDescriptionOptionsForRejectedData(content.name));
3877 } else {
3878 session_options->media_description_options.push_back(
3879 GetMediaDescriptionOptionsForActiveData(content.name));
3880 }
Steve Antondcc3c022017-12-22 16:02:54 -08003881 }
3882 }
htaa2a49d92016-03-04 02:51:39 -08003883}
3884
zhihuang1c378ed2017-08-17 14:10:50 -07003885void PeerConnection::GenerateMediaDescriptionOptions(
3886 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003887 RtpTransceiverDirection audio_direction,
3888 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003889 rtc::Optional<size_t>* audio_index,
3890 rtc::Optional<size_t>* video_index,
3891 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003892 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003893 for (const cricket::ContentInfo& content :
3894 session_desc->description()->contents()) {
3895 if (IsAudioContent(&content)) {
3896 // If we already have an audio m= section, reject this extra one.
3897 if (*audio_index) {
3898 session_options->media_description_options.push_back(
3899 cricket::MediaDescriptionOptions(
3900 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003901 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003902 } else {
3903 session_options->media_description_options.push_back(
3904 cricket::MediaDescriptionOptions(
3905 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003906 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003907 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003908 }
3909 } else if (IsVideoContent(&content)) {
3910 // If we already have an video m= section, reject this extra one.
3911 if (*video_index) {
3912 session_options->media_description_options.push_back(
3913 cricket::MediaDescriptionOptions(
3914 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003915 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003916 } else {
3917 session_options->media_description_options.push_back(
3918 cricket::MediaDescriptionOptions(
3919 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003920 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003921 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003922 }
3923 } else {
3924 RTC_DCHECK(IsDataContent(&content));
3925 // If we already have an data m= section, reject this extra one.
3926 if (*data_index) {
3927 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003928 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003929 } else {
3930 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003931 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003932 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003933 }
3934 }
htaa2a49d92016-03-04 02:51:39 -08003935 }
deadbeefab9b2d12015-10-14 11:33:11 -07003936}
3937
Steve Antonfa2260d2017-12-28 16:38:23 -08003938cricket::MediaDescriptionOptions
3939PeerConnection::GetMediaDescriptionOptionsForActiveData(
3940 const std::string& mid) const {
3941 // Direction for data sections is meaningless, but legacy endpoints might
3942 // expect sendrecv.
3943 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3944 RtpTransceiverDirection::kSendRecv,
3945 /*stopped=*/false);
3946 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3947 return options;
3948}
3949
3950cricket::MediaDescriptionOptions
3951PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3952 const std::string& mid) const {
3953 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3954 RtpTransceiverDirection::kInactive,
3955 /*stopped=*/true);
3956 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3957 return options;
3958}
3959
3960rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3961 switch (data_channel_type_) {
3962 case cricket::DCT_RTP:
3963 if (!rtp_data_channel_) {
3964 return rtc::nullopt;
3965 }
3966 return rtp_data_channel_->content_name();
3967 case cricket::DCT_SCTP:
3968 return sctp_content_name_;
3969 default:
3970 return rtc::nullopt;
3971 }
3972}
3973
Steve Anton4171afb2017-11-20 10:20:22 -08003974void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3975 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3976 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003977 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003978}
3979
Steve Anton4171afb2017-11-20 10:20:22 -08003980void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003981 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003982 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003983 cricket::MediaType media_type,
3984 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003985 std::vector<RtpSenderInfo>* current_senders =
3986 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003987
Steve Anton4171afb2017-11-20 10:20:22 -08003988 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003989 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003990 for (auto sender_it = current_senders->begin();
3991 sender_it != current_senders->end();
3992 /* incremented manually */) {
3993 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003994 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003995 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00003996 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003997 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003998 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003999 sender_exists) {
4000 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004001 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004002 OnRemoteSenderRemoved(info, media_type);
4003 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004004 }
4005 }
4006
Steve Anton4171afb2017-11-20 10:20:22 -08004007 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004008 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08004009 // |params.id| is the sender id and the stream id uses the first of
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004010 // |params.stream_ids|.
4011 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
Seth Hampson845e8782018-03-02 11:34:10 -08004012 const std::string& stream_id =
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004013 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08004014 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004015 uint32_t ssrc = params.first_ssrc();
4016
4017 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004018 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004019 if (!stream) {
4020 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004021 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004022 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004023 remote_streams_->AddStream(stream);
4024 new_streams->AddStream(stream);
4025 }
4026
Steve Anton4171afb2017-11-20 10:20:22 -08004027 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004028 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004029 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004030 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004031 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004032 }
4033 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004034
Steve Anton4171afb2017-11-20 10:20:22 -08004035 // Add default sender if necessary.
4036 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004037 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004038 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004039 if (!default_stream) {
4040 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004041 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004042 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004043 remote_streams_->AddStream(default_stream);
4044 new_streams->AddStream(default_stream);
4045 }
Steve Anton4171afb2017-11-20 10:20:22 -08004046 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4047 ? kDefaultAudioSenderId
4048 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004049 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004050 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004051 if (!default_sender_info) {
4052 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004053 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004054 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004055 }
4056 }
deadbeefab9b2d12015-10-14 11:33:11 -07004057}
4058
Steve Anton4171afb2017-11-20 10:20:22 -08004059void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4060 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004061 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004062
4063 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004064 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004065 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004066 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004067 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004068 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004069 }
4070}
4071
Steve Anton4171afb2017-11-20 10:20:22 -08004072void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4073 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004074 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004075
Henrik Boström933d8b02017-10-10 10:05:16 -07004076 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004077 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004078 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4079 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004080 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004081 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004082 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004083 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004084 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004085 }
4086 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004087 // Stopping or destroying a VideoRtpReceiver will end the
4088 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004089 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004090 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004091 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004092 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004093 // There's no guarantee the track is still available, e.g. the track may
4094 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004095 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004096 }
4097 } else {
nisseede5da42017-01-12 05:15:36 -08004098 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004099 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004100 if (receiver) {
4101 observer_->OnRemoveTrack(receiver);
4102 }
deadbeefab9b2d12015-10-14 11:33:11 -07004103}
4104
4105void PeerConnection::UpdateEndedRemoteMediaStreams() {
4106 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4107 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4108 MediaStreamInterface* stream = remote_streams_->at(i);
4109 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4110 streams_to_remove.push_back(stream);
4111 }
4112 }
4113
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004114 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004115 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004116 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004117 }
4118}
4119
Steve Anton4171afb2017-11-20 10:20:22 -08004120void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004121 const std::vector<cricket::StreamParams>& streams,
4122 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004123 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004124
Seth Hampson845e8782018-03-02 11:34:10 -08004125 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004126 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004127 for (auto sender_it = current_senders->begin();
4128 sender_it != current_senders->end();
4129 /* incremented manually */) {
4130 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004131 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004132 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4133 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004134 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004135 OnLocalSenderRemoved(info, media_type);
4136 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004137 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004138 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004139 }
4140 }
4141
Steve Anton4171afb2017-11-20 10:20:22 -08004142 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004143 for (const cricket::StreamParams& params : streams) {
4144 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004145 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004146 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004147 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004148 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004149 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004150 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004151 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004152 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004153 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004154 }
4155 }
4156}
4157
Steve Anton4171afb2017-11-20 10:20:22 -08004158void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4159 cricket::MediaType media_type) {
4160 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004161 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004162 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4163 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004164 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004165 return;
4166 }
4167
deadbeeffac06552015-11-25 11:26:01 -08004168 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004169 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004170 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004171 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004172 }
deadbeeffac06552015-11-25 11:26:01 -08004173
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004174 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004175 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004176}
4177
Steve Anton4171afb2017-11-20 10:20:22 -08004178void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4179 cricket::MediaType media_type) {
4180 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004181 if (!sender) {
4182 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004183 // SessionDescriptions has been renegotiated.
4184 return;
4185 }
deadbeeffac06552015-11-25 11:26:01 -08004186
4187 // A sender has been removed from the SessionDescription but it's still
4188 // associated with the PeerConnection. This only occurs if the SDP doesn't
4189 // match with the calls to CreateSender, AddStream and RemoveStream.
4190 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004191 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004192 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004193 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004194 }
deadbeeffac06552015-11-25 11:26:01 -08004195
Steve Anton4171afb2017-11-20 10:20:22 -08004196 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004197}
4198
4199void PeerConnection::UpdateLocalRtpDataChannels(
4200 const cricket::StreamParamsVec& streams) {
4201 std::vector<std::string> existing_channels;
4202
4203 // Find new and active data channels.
4204 for (const cricket::StreamParams& params : streams) {
4205 // |it->sync_label| is actually the data channel label. The reason is that
4206 // we use the same naming of data channels as we do for
4207 // MediaStreams and Tracks.
4208 // For MediaStreams, the sync_label is the MediaStream label and the
4209 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004210 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004211 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004212 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004213 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004214 continue;
4215 }
4216 // Set the SSRC the data channel should use for sending.
4217 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4218 existing_channels.push_back(data_channel_it->first);
4219 }
4220
4221 UpdateClosingRtpDataChannels(existing_channels, true);
4222}
4223
4224void PeerConnection::UpdateRemoteRtpDataChannels(
4225 const cricket::StreamParamsVec& streams) {
4226 std::vector<std::string> existing_channels;
4227
4228 // Find new and active data channels.
4229 for (const cricket::StreamParams& params : streams) {
4230 // The data channel label is either the mslabel or the SSRC if the mslabel
4231 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004232 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004233 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004234 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004235 auto data_channel_it = rtp_data_channels_.find(label);
4236 if (data_channel_it == rtp_data_channels_.end()) {
4237 // This is a new data channel.
4238 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4239 } else {
4240 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4241 }
4242 existing_channels.push_back(label);
4243 }
4244
4245 UpdateClosingRtpDataChannels(existing_channels, false);
4246}
4247
4248void PeerConnection::UpdateClosingRtpDataChannels(
4249 const std::vector<std::string>& active_channels,
4250 bool is_local_update) {
4251 auto it = rtp_data_channels_.begin();
4252 while (it != rtp_data_channels_.end()) {
4253 DataChannel* data_channel = it->second;
4254 if (std::find(active_channels.begin(), active_channels.end(),
4255 data_channel->label()) != active_channels.end()) {
4256 ++it;
4257 continue;
4258 }
4259
4260 if (is_local_update) {
4261 data_channel->SetSendSsrc(0);
4262 } else {
4263 data_channel->RemotePeerRequestClose();
4264 }
4265
4266 if (data_channel->state() == DataChannel::kClosed) {
4267 rtp_data_channels_.erase(it);
4268 it = rtp_data_channels_.begin();
4269 } else {
4270 ++it;
4271 }
4272 }
4273}
4274
4275void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4276 uint32_t remote_ssrc) {
4277 rtc::scoped_refptr<DataChannel> channel(
4278 InternalCreateDataChannel(label, nullptr));
4279 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004280 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004281 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004282 return;
4283 }
4284 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004285 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4286 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004287 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004288}
4289
4290rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4291 const std::string& label,
4292 const InternalDataChannelInit* config) {
4293 if (IsClosed()) {
4294 return nullptr;
4295 }
Steve Anton75737c02017-11-06 10:37:17 -08004296 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004297 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004298 << "InternalCreateDataChannel: Data is not supported in this call.";
4299 return nullptr;
4300 }
4301 InternalDataChannelInit new_config =
4302 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004303 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004304 if (new_config.id < 0) {
4305 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004306 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004307 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_ERROR)
4309 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004310 return nullptr;
4311 }
4312 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004313 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004314 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004315 return nullptr;
4316 }
4317 }
4318
Steve Anton75737c02017-11-06 10:37:17 -08004319 rtc::scoped_refptr<DataChannel> channel(
4320 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004321 if (!channel) {
4322 sid_allocator_.ReleaseSid(new_config.id);
4323 return nullptr;
4324 }
4325
4326 if (channel->data_channel_type() == cricket::DCT_RTP) {
4327 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004328 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4329 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004330 return nullptr;
4331 }
4332 rtp_data_channels_[channel->label()] = channel;
4333 } else {
4334 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4335 sctp_data_channels_.push_back(channel);
4336 channel->SignalClosed.connect(this,
4337 &PeerConnection::OnSctpDataChannelClosed);
4338 }
4339
Steve Anton2d8609c2018-01-23 16:38:46 -08004340 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004341 return channel;
4342}
4343
4344bool PeerConnection::HasDataChannels() const {
4345 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4346}
4347
4348void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4349 for (const auto& channel : sctp_data_channels_) {
4350 if (channel->id() < 0) {
4351 int sid;
4352 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004353 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004354 continue;
4355 }
4356 channel->SetSctpSid(sid);
4357 }
4358 }
4359}
4360
4361void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004362 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004363 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4364 ++it) {
4365 if (it->get() == channel) {
4366 if (channel->id() >= 0) {
4367 sid_allocator_.ReleaseSid(channel->id());
4368 }
deadbeefbd292462015-12-14 18:15:29 -08004369 // Since this method is triggered by a signal from the DataChannel,
4370 // we can't free it directly here; we need to free it asynchronously.
4371 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004372 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004373 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4374 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004375 return;
4376 }
4377 }
4378}
4379
deadbeefab9b2d12015-10-14 11:33:11 -07004380void PeerConnection::OnDataChannelDestroyed() {
4381 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4382 // DataChannel may callback to us and try to modify the list.
4383 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4384 temp_rtp_dcs.swap(rtp_data_channels_);
4385 for (const auto& kv : temp_rtp_dcs) {
4386 kv.second->OnTransportChannelDestroyed();
4387 }
4388
4389 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4390 temp_sctp_dcs.swap(sctp_data_channels_);
4391 for (const auto& channel : temp_sctp_dcs) {
4392 channel->OnTransportChannelDestroyed();
4393 }
4394}
4395
4396void PeerConnection::OnDataChannelOpenMessage(
4397 const std::string& label,
4398 const InternalDataChannelInit& config) {
4399 rtc::scoped_refptr<DataChannel> channel(
4400 InternalCreateDataChannel(label, &config));
4401 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004402 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004403 return;
4404 }
4405
deadbeefa601f5c2016-06-06 14:27:39 -07004406 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4407 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004408 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004409}
4410
Steve Anton4171afb2017-11-20 10:20:22 -08004411rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4412PeerConnection::GetAudioTransceiver() const {
4413 // This method only works with Plan B SDP, where there is a single
4414 // audio/video transceiver.
4415 RTC_DCHECK(!IsUnifiedPlan());
4416 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004417 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004418 return transceiver;
4419 }
4420 }
4421 RTC_NOTREACHED();
4422 return nullptr;
4423}
4424
4425rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4426PeerConnection::GetVideoTransceiver() const {
4427 // This method only works with Plan B SDP, where there is a single
4428 // audio/video transceiver.
4429 RTC_DCHECK(!IsUnifiedPlan());
4430 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004431 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004432 return transceiver;
4433 }
4434 }
4435 RTC_NOTREACHED();
4436 return nullptr;
4437}
4438
4439// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4440// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004441bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004442 switch (type) {
4443 case cricket::MEDIA_TYPE_AUDIO:
4444 return !GetAudioTransceiver()->internal()->senders().empty();
4445 case cricket::MEDIA_TYPE_VIDEO:
4446 return !GetVideoTransceiver()->internal()->senders().empty();
4447 case cricket::MEDIA_TYPE_DATA:
4448 return false;
4449 }
4450 RTC_NOTREACHED();
4451 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004452}
4453
Steve Anton4171afb2017-11-20 10:20:22 -08004454rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4455PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4456 for (auto transceiver : transceivers_) {
4457 for (auto sender : transceiver->internal()->senders()) {
4458 if (sender->track() == track) {
4459 return sender;
4460 }
4461 }
4462 }
4463 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004464}
4465
Steve Anton4171afb2017-11-20 10:20:22 -08004466rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4467PeerConnection::FindSenderById(const std::string& sender_id) const {
4468 for (auto transceiver : transceivers_) {
4469 for (auto sender : transceiver->internal()->senders()) {
4470 if (sender->id() == sender_id) {
4471 return sender;
4472 }
4473 }
4474 }
4475 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004476}
4477
Steve Anton4171afb2017-11-20 10:20:22 -08004478rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4479PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4480 for (auto transceiver : transceivers_) {
4481 for (auto receiver : transceiver->internal()->receivers()) {
4482 if (receiver->id() == receiver_id) {
4483 return receiver;
4484 }
4485 }
4486 }
4487 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004488}
4489
Steve Anton4171afb2017-11-20 10:20:22 -08004490std::vector<PeerConnection::RtpSenderInfo>*
4491PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4492 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4493 media_type == cricket::MEDIA_TYPE_VIDEO);
4494 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4495 ? &remote_audio_sender_infos_
4496 : &remote_video_sender_infos_;
4497}
4498
4499std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004500 cricket::MediaType media_type) {
4501 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4502 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004503 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4504 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004505}
4506
Steve Anton4171afb2017-11-20 10:20:22 -08004507const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4508 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004509 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004510 const std::string sender_id) const {
4511 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004512 if (sender_info.stream_id == stream_id &&
4513 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004514 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004515 }
4516 }
4517 return nullptr;
4518}
4519
4520DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4521 for (const auto& channel : sctp_data_channels_) {
4522 if (channel->id() == sid) {
4523 return channel;
4524 }
4525 }
4526 return nullptr;
4527}
4528
deadbeef91dd5672016-05-18 16:55:30 -07004529bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004530 const RTCConfiguration& configuration) {
4531 cricket::ServerAddresses stun_servers;
4532 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004533 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4534 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004535 return false;
4536 }
4537
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004538 port_allocator_->Initialize();
4539
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004540 // To handle both internal and externally created port allocator, we will
4541 // enable BUNDLE here.
4542 int portallocator_flags = port_allocator_->flags();
4543 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004544 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4545 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004546 // If the disable-IPv6 flag was specified, we'll not override it
4547 // by experiment.
4548 if (configuration.disable_ipv6) {
4549 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004550 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4551 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004552 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4553 }
4554
zhihuangb09b3f92017-03-07 14:40:51 -08004555 if (configuration.disable_ipv6_on_wifi) {
4556 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004557 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004558 }
4559
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004560 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4561 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004562 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004563 }
4564
honghaiz60347052016-05-31 18:29:12 -07004565 if (configuration.candidate_network_policy ==
4566 kCandidateNetworkPolicyLowCost) {
4567 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004568 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004569 }
4570
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004571 if (configuration.disable_link_local_networks) {
4572 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4573 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4574 }
4575
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004576 port_allocator_->set_flags(portallocator_flags);
4577 // No step delay is used while allocating ports.
4578 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4579 port_allocator_->set_candidate_filter(
4580 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004581 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004582
4583 // Call this last since it may create pooled allocator sessions using the
4584 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004585 port_allocator_->SetConfiguration(
4586 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4587 configuration.prune_turn_ports, configuration.turn_customizer,
4588 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004589 return true;
4590}
4591
deadbeef91dd5672016-05-18 16:55:30 -07004592bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004593 const cricket::ServerAddresses& stun_servers,
4594 const std::vector<cricket::RelayServerConfig>& turn_servers,
4595 IceTransportsType type,
4596 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004597 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004598 webrtc::TurnCustomizer* turn_customizer,
4599 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004600 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004601 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004602 // Call this last since it may create pooled allocator sessions using the
4603 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004604 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004605 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004606 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004607}
4608
Steve Antonba818672017-11-06 10:21:57 -08004609cricket::ChannelManager* PeerConnection::channel_manager() const {
4610 return factory_->channel_manager();
4611}
4612
4613MetricsObserverInterface* PeerConnection::metrics_observer() const {
4614 return uma_observer_;
4615}
4616
Elad Alon99c3fe52017-10-13 16:29:40 +02004617bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004618 std::unique_ptr<RtcEventLogOutput> output,
4619 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004620 if (!event_log_) {
4621 return false;
4622 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004623 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004624}
4625
4626void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004627 if (event_log_) {
4628 event_log_->StopLogging();
4629 }
ivoc14d5dbe2016-07-04 07:06:55 -07004630}
nisseeaabdf62017-05-05 02:23:02 -07004631
Steve Anton75737c02017-11-06 10:37:17 -08004632cricket::BaseChannel* PeerConnection::GetChannel(
4633 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004634 for (auto transceiver : transceivers_) {
4635 cricket::BaseChannel* channel = transceiver->internal()->channel();
4636 if (channel && channel->content_name() == content_name) {
4637 return channel;
4638 }
Steve Anton75737c02017-11-06 10:37:17 -08004639 }
4640 if (rtp_data_channel() &&
4641 rtp_data_channel()->content_name() == content_name) {
4642 return rtp_data_channel();
4643 }
4644 return nullptr;
4645}
4646
4647bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4648 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004649 RTC_LOG(LS_INFO)
4650 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004651 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004652 return false;
4653 }
4654 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004655 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004656 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004657 return false;
4658 }
4659
4660 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4661}
4662
4663bool PeerConnection::GetSslRole(const std::string& content_name,
4664 rtc::SSLRole* role) {
4665 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004666 RTC_LOG(LS_INFO)
4667 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004668 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004669 return false;
4670 }
4671
4672 return transport_controller_->GetSslRole(GetTransportName(content_name),
4673 role);
4674}
4675
Steve Antonf8470812017-12-04 10:46:21 -08004676void PeerConnection::SetSessionError(SessionError error,
4677 const std::string& error_desc) {
4678 RTC_DCHECK_RUN_ON(signaling_thread());
4679 if (error != session_error_) {
4680 session_error_ = error;
4681 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004682 }
4683}
4684
Steve Anton3828c062017-12-06 10:34:51 -08004685RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004686 cricket::ContentSource source) {
4687 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004688
4689 // If there's already a pending error then no state transition should happen.
4690 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004691 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004692
4693 // If this is an answer then we know whether to BUNDLE or not. If both the
4694 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004695 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004696 const cricket::ContentGroup* local_bundle =
4697 local_description()->description()->GetGroupByName(
4698 cricket::GROUP_TYPE_BUNDLE);
4699 const cricket::ContentGroup* remote_bundle =
4700 remote_description()->description()->GetGroupByName(
4701 cricket::GROUP_TYPE_BUNDLE);
4702 if (local_bundle && remote_bundle) {
4703 // The answerer decides the transport to bundle on.
4704 const cricket::ContentGroup* answer_bundle =
4705 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4706 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4708 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004709 }
4710 }
Steve Anton75737c02017-11-06 10:37:17 -08004711 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004712
4713 // Only push down the transport description after potentially enabling BUNDLE;
4714 // we don't want to push down a description on a transport about to be
4715 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004716 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004717 if (!error.ok()) {
4718 return error;
4719 }
4720
4721 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004722 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004723 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004724 }
4725
4726 // Update the signaling state according to the specified state machine (see
4727 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004728 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004729 ChangeSignalingState(source == cricket::CS_LOCAL
4730 ? PeerConnectionInterface::kHaveLocalOffer
4731 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004732 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004733 ChangeSignalingState(source == cricket::CS_LOCAL
4734 ? PeerConnectionInterface::kHaveLocalPrAnswer
4735 : PeerConnectionInterface::kHaveRemotePrAnswer);
4736 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004737 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004738 ChangeSignalingState(PeerConnectionInterface::kStable);
4739 }
4740
4741 // Update internal objects according to the session description's media
4742 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004743 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004744 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004745 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004746 }
4747
Steve Anton8a006912017-12-04 15:25:56 -08004748 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004749}
4750
Steve Anton8a006912017-12-04 15:25:56 -08004751RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004752 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004753 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004754 const SessionDescriptionInterface* sdesc =
4755 (source == cricket::CS_LOCAL ? local_description()
4756 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004757 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004758
4759 // Push down the new SDP media section for each audio/video transceiver.
4760 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004761 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004762 FindMediaSectionForTransceiver(transceiver, sdesc);
4763 cricket::BaseChannel* channel = transceiver->internal()->channel();
4764 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004765 continue;
4766 }
4767 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004768 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004769 if (!content_desc) {
4770 continue;
4771 }
4772 std::string error;
4773 bool success =
4774 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004775 ? channel->SetLocalContent(content_desc, type, &error)
4776 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004777 if (!success) {
4778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4779 }
4780 }
4781
4782 // If using the RtpDataChannel, push down the new SDP section for it too.
4783 if (rtp_data_channel_) {
4784 const ContentInfo* data_content =
4785 cricket::GetFirstDataContent(sdesc->description());
4786 if (data_content && !data_content->rejected) {
4787 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004788 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004789 if (data_desc) {
4790 std::string error;
4791 bool success =
4792 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004793 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4794 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004795 &error);
4796 if (!success) {
4797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4798 std::move(error));
4799 }
Steve Anton75737c02017-11-06 10:37:17 -08004800 }
4801 }
4802 }
Steve Antoned10bd92017-12-05 10:52:59 -08004803
Steve Anton75737c02017-11-06 10:37:17 -08004804 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4805 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4806 if (sctp_transport_ && local_description() && remote_description() &&
4807 cricket::GetFirstDataContent(local_description()->description()) &&
4808 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004809 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004810 RTC_FROM_HERE,
4811 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004812 if (!success) {
4813 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4814 "Failed to push down SCTP parameters.");
4815 }
Steve Anton75737c02017-11-06 10:37:17 -08004816 }
Steve Antoned10bd92017-12-05 10:52:59 -08004817
Steve Anton8a006912017-12-04 15:25:56 -08004818 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004819}
4820
4821bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4822 RTC_DCHECK(network_thread()->IsCurrent());
4823 RTC_DCHECK(local_description());
4824 RTC_DCHECK(remote_description());
4825 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4826 // When we support "max-message-size", that would also be pushed down here.
4827 return sctp_transport_->Start(
4828 GetSctpPort(local_description()->description()),
4829 GetSctpPort(remote_description()->description()));
4830}
4831
Steve Anton8a006912017-12-04 15:25:56 -08004832RTCError PeerConnection::PushdownTransportDescription(
4833 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004834 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004835 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004836
Steve Anton8a006912017-12-04 15:25:56 -08004837 const SessionDescriptionInterface* sdesc =
4838 (source == cricket::CS_LOCAL ? local_description()
4839 : remote_description());
4840 RTC_DCHECK(sdesc);
4841 for (const cricket::TransportInfo& tinfo :
4842 sdesc->description()->transport_infos()) {
4843 std::string error;
4844 bool success;
4845 if (source == cricket::CS_LOCAL) {
4846 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004847 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004848 } else {
4849 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004850 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004851 }
4852 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004853 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4854 "Failed to push down transport description for " +
4855 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004856 }
4857 }
4858
Steve Anton8a006912017-12-04 15:25:56 -08004859 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004860}
4861
4862bool PeerConnection::GetTransportDescription(
4863 const SessionDescription* description,
4864 const std::string& content_name,
4865 cricket::TransportDescription* tdesc) {
4866 if (!description || !tdesc) {
4867 return false;
4868 }
4869 const TransportInfo* transport_info =
4870 description->GetTransportInfoByName(content_name);
4871 if (!transport_info) {
4872 return false;
4873 }
4874 *tdesc = transport_info->description;
4875 return true;
4876}
4877
4878bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4879 const std::string* first_content_name = bundle.FirstContentName();
4880 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004881 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004882 return false;
4883 }
4884 const std::string& transport_name = *first_content_name;
4885
4886 auto maybe_set_transport = [this, bundle,
4887 transport_name](cricket::BaseChannel* ch) {
4888 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004889 return;
Steve Anton75737c02017-11-06 10:37:17 -08004890 }
4891
4892 std::string old_transport_name = ch->transport_name();
4893 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004894 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4895 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004896 return;
Steve Anton75737c02017-11-06 10:37:17 -08004897 }
4898
4899 cricket::DtlsTransportInternal* rtp_dtls_transport =
4900 transport_controller_->CreateDtlsTransport(
4901 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4902 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4903 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4904 if (need_rtcp) {
4905 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4906 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4907 }
4908
4909 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004910 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4911 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004912 transport_controller_->DestroyDtlsTransport(
4913 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4914 // If the channel needs rtcp, it means that the channel used to have a
4915 // rtcp transport which needs to be deleted now.
4916 if (need_rtcp) {
4917 transport_controller_->DestroyDtlsTransport(
4918 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4919 }
Steve Anton75737c02017-11-06 10:37:17 -08004920 };
4921
Steve Antoned10bd92017-12-05 10:52:59 -08004922 for (auto transceiver : transceivers_) {
4923 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004924 }
Steve Antoned10bd92017-12-05 10:52:59 -08004925 maybe_set_transport(rtp_data_channel_);
4926
Steve Anton75737c02017-11-06 10:37:17 -08004927 // For SCTP, transport creation/deletion happens here instead of in the
4928 // object itself.
4929 if (sctp_transport_) {
4930 RTC_DCHECK(sctp_transport_name_);
4931 RTC_DCHECK(sctp_content_name_);
4932 if (transport_name != *sctp_transport_name_ &&
4933 bundle.HasContentName(*sctp_content_name_)) {
4934 network_thread()->Invoke<void>(
4935 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4936 transport_name));
4937 }
4938 }
4939
4940 return true;
4941}
4942
Steve Anton75737c02017-11-06 10:37:17 -08004943cricket::IceConfig PeerConnection::ParseIceConfig(
4944 const PeerConnectionInterface::RTCConfiguration& config) const {
4945 cricket::ContinualGatheringPolicy gathering_policy;
4946 // TODO(honghaiz): Add the third continual gathering policy in
4947 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4948 switch (config.continual_gathering_policy) {
4949 case PeerConnectionInterface::GATHER_ONCE:
4950 gathering_policy = cricket::GATHER_ONCE;
4951 break;
4952 case PeerConnectionInterface::GATHER_CONTINUALLY:
4953 gathering_policy = cricket::GATHER_CONTINUALLY;
4954 break;
4955 default:
4956 RTC_NOTREACHED();
4957 gathering_policy = cricket::GATHER_ONCE;
4958 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004959
Steve Anton75737c02017-11-06 10:37:17 -08004960 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004961 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4962 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004963 ice_config.prioritize_most_likely_candidate_pairs =
4964 config.prioritize_most_likely_ice_candidate_pairs;
4965 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004966 RTCConfigurationToIceConfigOptionalInt(
4967 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004968 ice_config.continual_gathering_policy = gathering_policy;
4969 ice_config.presume_writable_when_fully_relayed =
4970 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004971 ice_config.ice_check_interval_strong_connectivity =
4972 config.ice_check_interval_strong_connectivity;
4973 ice_config.ice_check_interval_weak_connectivity =
4974 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004975 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004976 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004977 ice_config.regather_all_networks_interval_range =
4978 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004979 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004980 return ice_config;
4981}
4982
Steve Anton75737c02017-11-06 10:37:17 -08004983bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4984 std::string* track_id) {
4985 if (!local_description()) {
4986 return false;
4987 }
4988 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4989 track_id);
4990}
4991
4992bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4993 std::string* track_id) {
4994 if (!remote_description()) {
4995 return false;
4996 }
4997 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4998 track_id);
4999}
5000
5001bool PeerConnection::SendData(const cricket::SendDataParams& params,
5002 const rtc::CopyOnWriteBuffer& payload,
5003 cricket::SendDataResult* result) {
5004 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005005 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005006 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005007 return false;
5008 }
5009 return rtp_data_channel_
5010 ? rtp_data_channel_->SendData(params, payload, result)
5011 : network_thread()->Invoke<bool>(
5012 RTC_FROM_HERE,
5013 Bind(&cricket::SctpTransportInternal::SendData,
5014 sctp_transport_.get(), params, payload, result));
5015}
5016
5017bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5018 if (!rtp_data_channel_ && !sctp_transport_) {
5019 // Don't log an error here, because DataChannels are expected to call
5020 // ConnectDataChannel in this state. It's the only way to initially tell
5021 // whether or not the underlying transport is ready.
5022 return false;
5023 }
5024 if (rtp_data_channel_) {
5025 rtp_data_channel_->SignalReadyToSendData.connect(
5026 webrtc_data_channel, &DataChannel::OnChannelReady);
5027 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5028 &DataChannel::OnDataReceived);
5029 } else {
5030 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5031 &DataChannel::OnChannelReady);
5032 SignalSctpDataReceived.connect(webrtc_data_channel,
5033 &DataChannel::OnDataReceived);
5034 SignalSctpStreamClosedRemotely.connect(
5035 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5036 }
5037 return true;
5038}
5039
5040void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5041 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005042 RTC_LOG(LS_ERROR)
5043 << "DisconnectDataChannel called when rtp_data_channel_ and "
5044 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005045 return;
5046 }
5047 if (rtp_data_channel_) {
5048 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5049 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5050 } else {
5051 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5052 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5053 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5054 }
5055}
5056
5057void PeerConnection::AddSctpDataStream(int sid) {
5058 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005059 RTC_LOG(LS_ERROR)
5060 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005061 return;
5062 }
5063 network_thread()->Invoke<void>(
5064 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5065 sctp_transport_.get(), sid));
5066}
5067
5068void PeerConnection::RemoveSctpDataStream(int sid) {
5069 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005070 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005071 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005072 return;
5073 }
5074 network_thread()->Invoke<void>(
5075 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5076 sctp_transport_.get(), sid));
5077}
5078
5079bool PeerConnection::ReadyToSendData() const {
5080 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5081 sctp_ready_to_send_data_;
5082}
5083
Qingsi Wang72a43a12018-02-20 16:03:18 -08005084cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5085 cricket::CandidateStatsList candidate_states_list;
5086 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5087 return candidate_states_list;
5088}
5089
Steve Anton5dfde182018-02-06 10:34:40 -08005090std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5091 const {
5092 std::map<std::string, std::string> transport_names_by_mid;
5093 for (auto transceiver : transceivers_) {
5094 cricket::BaseChannel* channel = transceiver->internal()->channel();
5095 if (channel) {
5096 transport_names_by_mid[channel->content_name()] =
5097 channel->transport_name();
5098 }
Steve Anton75737c02017-11-06 10:37:17 -08005099 }
Steve Anton5dfde182018-02-06 10:34:40 -08005100 if (rtp_data_channel_) {
5101 transport_names_by_mid[rtp_data_channel_->content_name()] =
5102 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005103 }
5104 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005105 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005106 }
Steve Anton5dfde182018-02-06 10:34:40 -08005107 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005108}
5109
Steve Anton5dfde182018-02-06 10:34:40 -08005110std::map<std::string, cricket::TransportStats>
5111PeerConnection::GetTransportStatsByNames(
5112 const std::set<std::string>& transport_names) {
5113 if (!network_thread()->IsCurrent()) {
5114 return network_thread()
5115 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5116 RTC_FROM_HERE,
5117 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005118 }
Steve Anton5dfde182018-02-06 10:34:40 -08005119 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5120 for (const std::string& transport_name : transport_names) {
5121 cricket::TransportStats transport_stats;
5122 bool success =
5123 transport_controller_->GetStats(transport_name, &transport_stats);
5124 if (success) {
5125 transport_stats_by_name[transport_name] = std::move(transport_stats);
5126 } else {
5127 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5128 << transport_name;
5129 }
5130 }
5131 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005132}
5133
5134bool PeerConnection::GetLocalCertificate(
5135 const std::string& transport_name,
5136 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5137 return transport_controller_->GetLocalCertificate(transport_name,
5138 certificate);
5139}
5140
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005141std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005142 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005143 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005144}
5145
5146cricket::DataChannelType PeerConnection::data_channel_type() const {
5147 return data_channel_type_;
5148}
5149
5150bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5151 return pending_ice_restarts_.find(content_name) !=
5152 pending_ice_restarts_.end();
5153}
5154
Steve Anton75737c02017-11-06 10:37:17 -08005155bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5156 return transport_controller_->NeedsIceRestart(content_name);
5157}
5158
5159void PeerConnection::OnCertificateReady(
5160 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5161 transport_controller_->SetLocalCertificate(certificate);
5162}
5163
5164void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005165 SetSessionError(SessionError::kTransport,
5166 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005167}
5168
5169void PeerConnection::OnTransportControllerConnectionState(
5170 cricket::IceConnectionState state) {
5171 switch (state) {
5172 case cricket::kIceConnectionConnecting:
5173 // If the current state is Connected or Completed, then there were
5174 // writable channels but now there are not, so the next state must
5175 // be Disconnected.
5176 // kIceConnectionConnecting is currently used as the default,
5177 // un-connected state by the TransportController, so its only use is
5178 // detecting disconnections.
5179 if (ice_connection_state_ ==
5180 PeerConnectionInterface::kIceConnectionConnected ||
5181 ice_connection_state_ ==
5182 PeerConnectionInterface::kIceConnectionCompleted) {
5183 SetIceConnectionState(
5184 PeerConnectionInterface::kIceConnectionDisconnected);
5185 }
5186 break;
5187 case cricket::kIceConnectionFailed:
5188 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5189 break;
5190 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005191 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005192 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005193 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5194 break;
5195 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005196 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005197 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005198 if (ice_connection_state_ !=
5199 PeerConnectionInterface::kIceConnectionConnected) {
5200 // If jumping directly from "checking" to "connected",
5201 // signal "connected" first.
5202 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5203 }
5204 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5205 if (metrics_observer()) {
5206 ReportTransportStats();
5207 }
5208 break;
5209 default:
5210 RTC_NOTREACHED();
5211 }
5212}
5213
5214void PeerConnection::OnTransportControllerCandidatesGathered(
5215 const std::string& transport_name,
5216 const cricket::Candidates& candidates) {
5217 RTC_DCHECK(signaling_thread()->IsCurrent());
5218 int sdp_mline_index;
5219 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005220 RTC_LOG(LS_ERROR)
5221 << "OnTransportControllerCandidatesGathered: content name "
5222 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005223 return;
5224 }
5225
5226 for (cricket::Candidates::const_iterator citer = candidates.begin();
5227 citer != candidates.end(); ++citer) {
5228 // Use transport_name as the candidate media id.
5229 std::unique_ptr<JsepIceCandidate> candidate(
5230 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5231 if (local_description()) {
5232 mutable_local_description()->AddCandidate(candidate.get());
5233 }
5234 OnIceCandidate(std::move(candidate));
5235 }
5236}
5237
5238void PeerConnection::OnTransportControllerCandidatesRemoved(
5239 const std::vector<cricket::Candidate>& candidates) {
5240 RTC_DCHECK(signaling_thread()->IsCurrent());
5241 // Sanity check.
5242 for (const cricket::Candidate& candidate : candidates) {
5243 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005244 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005245 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005246 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005247 return;
5248 }
5249 }
5250
5251 if (local_description()) {
5252 mutable_local_description()->RemoveCandidates(candidates);
5253 }
5254 OnIceCandidatesRemoved(candidates);
5255}
5256
5257void PeerConnection::OnTransportControllerDtlsHandshakeError(
5258 rtc::SSLHandshakeError error) {
5259 if (metrics_observer()) {
5260 metrics_observer()->IncrementEnumCounter(
5261 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5262 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5263 }
5264}
5265
Steve Antoned10bd92017-12-05 10:52:59 -08005266void PeerConnection::EnableSending() {
5267 for (auto transceiver : transceivers_) {
5268 cricket::BaseChannel* channel = transceiver->internal()->channel();
5269 if (channel && !channel->enabled()) {
5270 channel->Enable(true);
5271 }
Steve Anton75737c02017-11-06 10:37:17 -08005272 }
5273
Steve Anton4171afb2017-11-20 10:20:22 -08005274 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005275 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005276 }
Steve Anton75737c02017-11-06 10:37:17 -08005277}
5278
5279// Returns the media index for a local ice candidate given the content name.
5280bool PeerConnection::GetLocalCandidateMediaIndex(
5281 const std::string& content_name,
5282 int* sdp_mline_index) {
5283 if (!local_description() || !sdp_mline_index) {
5284 return false;
5285 }
5286
5287 bool content_found = false;
5288 const ContentInfos& contents = local_description()->description()->contents();
5289 for (size_t index = 0; index < contents.size(); ++index) {
5290 if (contents[index].name == content_name) {
5291 *sdp_mline_index = static_cast<int>(index);
5292 content_found = true;
5293 break;
5294 }
5295 }
5296 return content_found;
5297}
5298
5299bool PeerConnection::UseCandidatesInSessionDescription(
5300 const SessionDescriptionInterface* remote_desc) {
5301 if (!remote_desc) {
5302 return true;
5303 }
5304 bool ret = true;
5305
5306 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5307 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5308 for (size_t n = 0; n < candidates->count(); ++n) {
5309 const IceCandidateInterface* candidate = candidates->at(n);
5310 bool valid = false;
5311 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5312 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005313 RTC_LOG(LS_INFO)
5314 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005315 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005316 }
5317 continue;
5318 }
5319 ret = UseCandidate(candidate);
5320 if (!ret) {
5321 break;
5322 }
5323 }
5324 }
5325 return ret;
5326}
5327
5328bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5329 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5330 size_t remote_content_size =
5331 remote_description()->description()->contents().size();
5332 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005333 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005334 return false;
5335 }
5336
5337 cricket::ContentInfo content =
5338 remote_description()->description()->contents()[mediacontent_index];
5339 std::vector<cricket::Candidate> candidates;
5340 candidates.push_back(candidate->candidate());
5341 // Invoking BaseSession method to handle remote candidates.
5342 std::string error;
5343 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5344 &error)) {
5345 // Candidates successfully submitted for checking.
5346 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5347 ice_connection_state_ ==
5348 PeerConnectionInterface::kIceConnectionDisconnected) {
5349 // If state is New, then the session has just gotten its first remote ICE
5350 // candidates, so go to Checking.
5351 // If state is Disconnected, the session is re-using old candidates or
5352 // receiving additional ones, so go to Checking.
5353 // If state is Connected, stay Connected.
5354 // TODO(bemasc): If state is Connected, and the new candidates are for a
5355 // newly added transport, then the state actually _should_ move to
5356 // checking. Add a way to distinguish that case.
5357 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5358 }
5359 // TODO(bemasc): If state is Completed, go back to Connected.
5360 } else {
5361 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005362 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005363 }
5364 }
5365 return true;
5366}
5367
5368void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005369 // Destroy video channel first since it may have a pointer to the
5370 // voice channel.
5371 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005372 if (!video_info || video_info->rejected) {
5373 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005374 }
5375
Steve Anton6fec8802017-12-04 10:37:29 -08005376 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5377 if (!audio_info || audio_info->rejected) {
5378 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005379 }
5380
5381 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5382 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005383 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005384 }
5385}
5386
Steve Antoneda6ccd2017-12-04 10:21:55 -08005387std::string PeerConnection::GetTransportNameForMediaSection(
5388 const std::string& mid,
5389 const cricket::ContentGroup* bundle_group) const {
5390 if (!bundle_group) {
5391 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005392 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005393 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005394 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005395 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005396 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005397 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005398 if (!bundle_group->HasContentName(mid)) {
5399 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5400 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005401 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005402 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5403 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005404}
5405
Steve Antondcc3c022017-12-22 16:02:54 -08005406RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5407 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005408 const cricket::ContentGroup* bundle_group = nullptr;
5409 if (configuration_.bundle_policy ==
5410 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005411 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005412 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005413 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5414 "max-bundle configured but session description "
5415 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005416 }
5417 }
Steve Antondcc3c022017-12-22 16:02:54 -08005418 return std::move(bundle_group);
5419}
5420
5421RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5422 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5423 if (!bundle_group_or_error.ok()) {
5424 return bundle_group_or_error.MoveError();
5425 }
5426 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005427
Steve Antoneda6ccd2017-12-04 10:21:55 -08005428 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005429 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005430 if (voice && !voice->rejected &&
5431 !GetAudioTransceiver()->internal()->channel()) {
5432 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5433 voice->name,
5434 GetTransportNameForMediaSection(voice->name, bundle_group));
5435 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005436 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5437 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005438 }
5439 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5440 }
5441
Steve Antondcc3c022017-12-22 16:02:54 -08005442 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005443 if (video && !video->rejected &&
5444 !GetVideoTransceiver()->internal()->channel()) {
5445 cricket::VideoChannel* video_channel = CreateVideoChannel(
5446 video->name,
5447 GetTransportNameForMediaSection(video->name, bundle_group));
5448 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005449 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5450 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005451 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005452 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005453 }
5454
Steve Antondcc3c022017-12-22 16:02:54 -08005455 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005456 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5457 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005458 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5459 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005460 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5461 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
5463 }
5464
Steve Anton8a006912017-12-04 15:25:56 -08005465 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005466}
5467
Steve Anton4171afb2017-11-20 10:20:22 -08005468// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005469cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5470 const std::string& mid,
5471 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005472 cricket::DtlsTransportInternal* rtp_dtls_transport =
5473 transport_controller_->CreateDtlsTransport(
5474 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5475 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5476 if (configuration_.rtcp_mux_policy !=
5477 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5478 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5479 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5480 }
5481
5482 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5483 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005484 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5485 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005486 if (!voice_channel) {
5487 transport_controller_->DestroyDtlsTransport(
5488 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5489 if (rtcp_dtls_transport) {
5490 transport_controller_->DestroyDtlsTransport(
5491 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5492 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005493 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005494 }
Steve Anton75737c02017-11-06 10:37:17 -08005495 voice_channel->SignalRtcpMuxFullyActive.connect(
5496 this, &PeerConnection::DestroyRtcpTransport_n);
5497 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5498 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005499 voice_channel->SignalSentPacket.connect(this,
5500 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005501 if (uma_observer_) {
5502 voice_channel->SetMetricsObserver(uma_observer_);
5503 }
Steve Anton4171afb2017-11-20 10:20:22 -08005504
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005506}
5507
Steve Anton4171afb2017-11-20 10:20:22 -08005508// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005509cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5510 const std::string& mid,
5511 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005512 cricket::DtlsTransportInternal* rtp_dtls_transport =
5513 transport_controller_->CreateDtlsTransport(
5514 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5515 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5516 if (configuration_.rtcp_mux_policy !=
5517 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5518 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5519 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5520 }
5521
5522 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5523 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005524 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5525 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005526
5527 if (!video_channel) {
5528 transport_controller_->DestroyDtlsTransport(
5529 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5530 if (rtcp_dtls_transport) {
5531 transport_controller_->DestroyDtlsTransport(
5532 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5533 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005534 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005535 }
Steve Anton75737c02017-11-06 10:37:17 -08005536 video_channel->SignalRtcpMuxFullyActive.connect(
5537 this, &PeerConnection::DestroyRtcpTransport_n);
5538 video_channel->SignalDtlsSrtpSetupFailure.connect(
5539 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005540 video_channel->SignalSentPacket.connect(this,
5541 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005542 if (uma_observer_) {
5543 video_channel->SetMetricsObserver(uma_observer_);
5544 }
Steve Anton4171afb2017-11-20 10:20:22 -08005545
Steve Antoneda6ccd2017-12-04 10:21:55 -08005546 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005547}
5548
Steve Antoneda6ccd2017-12-04 10:21:55 -08005549bool PeerConnection::CreateDataChannel(const std::string& mid,
5550 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005551 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5552 if (sctp) {
5553 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005554 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005555 << "Trying to create SCTP transport, but didn't compile with "
5556 "SCTP support (HAVE_SCTP)";
5557 return false;
5558 }
5559 if (!network_thread()->Invoke<bool>(
5560 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005561 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005562 return false;
5563 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005564 for (const auto& channel : sctp_data_channels_) {
5565 channel->OnTransportChannelCreated();
5566 }
Steve Anton75737c02017-11-06 10:37:17 -08005567 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005568 cricket::DtlsTransportInternal* rtp_dtls_transport =
5569 transport_controller_->CreateDtlsTransport(
5570 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5571 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5572 if (configuration_.rtcp_mux_policy !=
5573 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5574 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5575 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5576 }
5577
5578 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5579 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005580 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005581
5582 if (!rtp_data_channel_) {
5583 transport_controller_->DestroyDtlsTransport(
5584 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5585 if (rtcp_dtls_transport) {
5586 transport_controller_->DestroyDtlsTransport(
5587 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5588 }
5589 return false;
5590 }
5591
5592 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5593 this, &PeerConnection::DestroyRtcpTransport_n);
5594 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5595 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5596 rtp_data_channel_->SignalSentPacket.connect(
5597 this, &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005598 if (uma_observer_) {
5599 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5600 }
Steve Anton75737c02017-11-06 10:37:17 -08005601 }
5602
Steve Anton75737c02017-11-06 10:37:17 -08005603 return true;
5604}
5605
5606Call::Stats PeerConnection::GetCallStats() {
5607 if (!worker_thread()->IsCurrent()) {
5608 return worker_thread()->Invoke<Call::Stats>(
5609 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5610 }
5611 if (call_) {
5612 return call_->GetStats();
5613 } else {
5614 return Call::Stats();
5615 }
5616}
5617
Steve Anton75737c02017-11-06 10:37:17 -08005618bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5619 const std::string& transport_name) {
5620 RTC_DCHECK(network_thread()->IsCurrent());
5621 RTC_DCHECK(sctp_factory_);
5622 cricket::DtlsTransportInternal* tc =
5623 transport_controller_->CreateDtlsTransport_n(
5624 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5625 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5626 RTC_DCHECK(sctp_transport_);
5627 sctp_invoker_.reset(new rtc::AsyncInvoker());
5628 sctp_transport_->SignalReadyToSendData.connect(
5629 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5630 sctp_transport_->SignalDataReceived.connect(
5631 this, &PeerConnection::OnSctpTransportDataReceived_n);
5632 sctp_transport_->SignalStreamClosedRemotely.connect(
5633 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005634 sctp_transport_name_ = transport_name;
5635 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005636 return true;
5637}
5638
5639void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5640 RTC_DCHECK(network_thread()->IsCurrent());
5641 RTC_DCHECK(sctp_transport_);
5642 RTC_DCHECK(sctp_transport_name_);
5643 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005644 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005645 cricket::DtlsTransportInternal* tc =
5646 transport_controller_->CreateDtlsTransport_n(
5647 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5648 sctp_transport_->SetTransportChannel(tc);
5649 transport_controller_->DestroyDtlsTransport_n(
5650 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5651}
5652
5653void PeerConnection::DestroySctpTransport_n() {
5654 RTC_DCHECK(network_thread()->IsCurrent());
5655 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005656 transport_controller_->DestroyDtlsTransport_n(
5657 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005658 sctp_content_name_.reset();
5659 sctp_transport_name_.reset();
5660 sctp_invoker_.reset(nullptr);
5661 sctp_ready_to_send_data_ = false;
5662}
5663
5664void PeerConnection::OnSctpTransportReadyToSendData_n() {
5665 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5666 RTC_DCHECK(network_thread()->IsCurrent());
5667 // Note: Cannot use rtc::Bind here because it will grab a reference to
5668 // PeerConnection and potentially cause PeerConnection to live longer than
5669 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5670 // be destroyed before PeerConnection is destroyed, and at that point all
5671 // pending tasks will be cleared.
5672 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5673 OnSctpTransportReadyToSendData_s(true);
5674 });
5675}
5676
5677void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5678 RTC_DCHECK(signaling_thread()->IsCurrent());
5679 sctp_ready_to_send_data_ = ready;
5680 SignalSctpReadyToSendData(ready);
5681}
5682
5683void PeerConnection::OnSctpTransportDataReceived_n(
5684 const cricket::ReceiveDataParams& params,
5685 const rtc::CopyOnWriteBuffer& payload) {
5686 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5687 RTC_DCHECK(network_thread()->IsCurrent());
5688 // Note: Cannot use rtc::Bind here because it will grab a reference to
5689 // PeerConnection and potentially cause PeerConnection to live longer than
5690 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5691 // be destroyed before PeerConnection is destroyed, and at that point all
5692 // pending tasks will be cleared.
5693 sctp_invoker_->AsyncInvoke<void>(
5694 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5695 OnSctpTransportDataReceived_s(params, payload);
5696 });
5697}
5698
5699void PeerConnection::OnSctpTransportDataReceived_s(
5700 const cricket::ReceiveDataParams& params,
5701 const rtc::CopyOnWriteBuffer& payload) {
5702 RTC_DCHECK(signaling_thread()->IsCurrent());
5703 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5704 // Received OPEN message; parse and signal that a new data channel should
5705 // be created.
5706 std::string label;
5707 InternalDataChannelInit config;
5708 config.id = params.ssrc;
5709 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005710 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5711 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005712 return;
5713 }
5714 config.open_handshake_role = InternalDataChannelInit::kAcker;
5715 OnDataChannelOpenMessage(label, config);
5716 } else {
5717 // Otherwise just forward the signal.
5718 SignalSctpDataReceived(params, payload);
5719 }
5720}
5721
5722void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5723 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5724 RTC_DCHECK(network_thread()->IsCurrent());
5725 sctp_invoker_->AsyncInvoke<void>(
5726 RTC_FROM_HERE, signaling_thread(),
5727 rtc::Bind(&sigslot::signal1<int>::operator(),
5728 &SignalSctpStreamClosedRemotely, sid));
5729}
5730
5731// Returns false if bundle is enabled and rtcp_mux is disabled.
5732bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5733 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5734 if (!bundle_enabled)
5735 return true;
5736
5737 const cricket::ContentGroup* bundle_group =
5738 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5739 RTC_DCHECK(bundle_group != NULL);
5740
5741 const cricket::ContentInfos& contents = desc->contents();
5742 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5743 citer != contents.end(); ++citer) {
5744 const cricket::ContentInfo* content = (&*citer);
5745 RTC_DCHECK(content != NULL);
5746 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005747 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005748 if (!HasRtcpMuxEnabled(content))
5749 return false;
5750 }
5751 }
5752 // RTCP-MUX is enabled in all the contents.
5753 return true;
5754}
5755
5756bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005757 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005758}
5759
Steve Anton8a006912017-12-04 15:25:56 -08005760RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005761 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005762 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005763 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005764 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766
5767 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005768 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770
Steve Anton3828c062017-12-06 10:34:51 -08005771 SdpType type = sdesc->GetType();
5772 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5773 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005774 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005775 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005776 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778
5779 // Verify crypto settings.
5780 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005781 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5782 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005783 RTCError crypto_error =
5784 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005785 if (!crypto_error.ok()) {
5786 return crypto_error;
5787 }
Steve Anton75737c02017-11-06 10:37:17 -08005788 }
5789
5790 // Verify ice-ufrag and ice-pwd.
5791 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5793 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795
5796 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005797 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5798 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005799 }
5800
5801 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5802 // m-lines that do not rtcp-mux enabled.
5803
5804 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005805 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 // With an answer we want to compare the new answer session description with
5807 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005808 const cricket::SessionDescription* offer_desc =
5809 (source == cricket::CS_LOCAL) ? remote_description()->description()
5810 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005811 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5812 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5813 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5815 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005816 }
5817 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005818 // The re-offers should respect the order of m= sections in current
5819 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005820 // With a re-offer, either the current local or current remote descriptions
5821 // could be the most up to date, so we would like to check against both of
5822 // them if they exist. It could be the case that one of them has a 0 port
5823 // for a media section, but the other does not. This is important to check
5824 // against in the case that we are recycling an m= section.
5825 const cricket::SessionDescription* current_desc = nullptr;
5826 const cricket::SessionDescription* secondary_current_desc = nullptr;
5827 if (local_description()) {
5828 current_desc = local_description()->description();
5829 if (remote_description()) {
5830 secondary_current_desc = remote_description()->description();
5831 }
5832 } else if (remote_description()) {
5833 current_desc = remote_description()->description();
5834 }
Steve Anton75737c02017-11-06 10:37:17 -08005835 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005836 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5837 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5839 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005840 }
5841 }
5842
Steve Anton8a006912017-12-04 15:25:56 -08005843 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005844}
5845
Steve Anton3828c062017-12-06 10:34:51 -08005846bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005847 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005848 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005849 return (state == PeerConnectionInterface::kStable) ||
5850 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005851 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005852 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005853 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5854 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5855 }
5856}
5857
Steve Anton3828c062017-12-06 10:34:51 -08005858bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005859 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005860 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005861 return (state == PeerConnectionInterface::kStable) ||
5862 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005863 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005864 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005865 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5866 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5867 }
5868}
5869
Steve Antonf8470812017-12-04 10:46:21 -08005870const char* PeerConnection::SessionErrorToString(SessionError error) const {
5871 switch (error) {
5872 case SessionError::kNone:
5873 return "ERROR_NONE";
5874 case SessionError::kContent:
5875 return "ERROR_CONTENT";
5876 case SessionError::kTransport:
5877 return "ERROR_TRANSPORT";
5878 }
5879 RTC_NOTREACHED();
5880 return "";
5881}
5882
Steve Anton75737c02017-11-06 10:37:17 -08005883std::string PeerConnection::GetSessionErrorMsg() {
5884 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005885 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5886 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005887 return desc.str();
5888}
5889
Steve Anton8e20f172018-03-06 10:55:04 -08005890void PeerConnection::ReportSdpFormatReceived(
5891 const SessionDescriptionInterface& remote_offer) {
5892 if (!uma_observer_) {
5893 return;
5894 }
5895 int num_audio_mlines = 0;
5896 int num_video_mlines = 0;
5897 int num_audio_tracks = 0;
5898 int num_video_tracks = 0;
5899 for (const ContentInfo& content : remote_offer.description()->contents()) {
5900 cricket::MediaType media_type = content.media_description()->type();
5901 int num_tracks = std::max(
5902 1, static_cast<int>(content.media_description()->streams().size()));
5903 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5904 num_audio_mlines += 1;
5905 num_audio_tracks += num_tracks;
5906 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5907 num_video_mlines += 1;
5908 num_video_tracks += num_tracks;
5909 }
5910 }
5911 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5912 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5913 format = kSdpFormatReceivedComplexUnifiedPlan;
5914 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5915 format = kSdpFormatReceivedComplexPlanB;
5916 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5917 format = kSdpFormatReceivedSimple;
5918 }
5919 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5920 kSdpFormatReceivedMax);
5921}
5922
Steve Anton0ffaaa22018-02-23 10:31:30 -08005923void PeerConnection::ReportNegotiatedSdpSemantics(
5924 const SessionDescriptionInterface& answer) {
5925 if (!uma_observer_) {
5926 return;
5927 }
5928 switch (answer.description()->msid_signaling()) {
5929 case 0:
5930 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5931 kSdpSemanticNegotiatedNone,
5932 kSdpSemanticNegotiatedMax);
5933 break;
5934 case cricket::kMsidSignalingMediaSection:
5935 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5936 kSdpSemanticNegotiatedUnifiedPlan,
5937 kSdpSemanticNegotiatedMax);
5938 break;
5939 case cricket::kMsidSignalingSsrcAttribute:
5940 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5941 kSdpSemanticNegotiatedPlanB,
5942 kSdpSemanticNegotiatedMax);
5943 break;
5944 case cricket::kMsidSignalingMediaSection |
5945 cricket::kMsidSignalingSsrcAttribute:
5946 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5947 kSdpSemanticNegotiatedMixed,
5948 kSdpSemanticNegotiatedMax);
5949 break;
5950 default:
5951 RTC_NOTREACHED();
5952 }
5953}
5954
Steve Anton75737c02017-11-06 10:37:17 -08005955// We need to check the local/remote description for the Transport instead of
5956// the session, because a new Transport added during renegotiation may have
5957// them unset while the session has them set from the previous negotiation.
5958// Not doing so may trigger the auto generation of transport description and
5959// mess up DTLS identity information, ICE credential, etc.
5960bool PeerConnection::ReadyToUseRemoteCandidate(
5961 const IceCandidateInterface* candidate,
5962 const SessionDescriptionInterface* remote_desc,
5963 bool* valid) {
5964 *valid = true;
5965
5966 const SessionDescriptionInterface* current_remote_desc =
5967 remote_desc ? remote_desc : remote_description();
5968
5969 if (!current_remote_desc) {
5970 return false;
5971 }
5972
5973 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5974 size_t remote_content_size =
5975 current_remote_desc->description()->contents().size();
5976 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005977 RTC_LOG(LS_ERROR)
5978 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5979 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005980
5981 *valid = false;
5982 return false;
5983 }
5984
5985 cricket::ContentInfo content =
5986 current_remote_desc->description()->contents()[mediacontent_index];
5987
5988 const std::string transport_name = GetTransportName(content.name);
5989 if (transport_name.empty()) {
5990 return false;
5991 }
5992 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5993}
5994
5995bool PeerConnection::SrtpRequired() const {
5996 return dtls_enabled_ ||
5997 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5998}
5999
6000void PeerConnection::OnTransportControllerGatheringState(
6001 cricket::IceGatheringState state) {
6002 RTC_DCHECK(signaling_thread()->IsCurrent());
6003 if (state == cricket::kIceGatheringGathering) {
6004 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6005 } else if (state == cricket::kIceGatheringComplete) {
6006 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6007 }
6008}
6009
6010void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006011 std::map<std::string, std::set<cricket::MediaType>>
6012 media_types_by_transport_name;
6013 for (auto transceiver : transceivers_) {
6014 if (transceiver->internal()->channel()) {
6015 const std::string& transport_name =
6016 transceiver->internal()->channel()->transport_name();
6017 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006018 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006019 }
Steve Anton75737c02017-11-06 10:37:17 -08006020 }
6021 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006022 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6023 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006024 }
6025 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006026 media_types_by_transport_name[*sctp_transport_name_].insert(
6027 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006028 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 for (const auto& entry : media_types_by_transport_name) {
6030 const std::string& transport_name = entry.first;
6031 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006032 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006033 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006034 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006035 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006036 }
6037 }
6038}
6039// Walk through the ConnectionInfos to gather best connection usage
6040// for IPv4 and IPv6.
6041void PeerConnection::ReportBestConnectionState(
6042 const cricket::TransportStats& stats) {
6043 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006044 for (const cricket::TransportChannelStats& channel_stats :
6045 stats.channel_stats) {
6046 for (const cricket::ConnectionInfo& connection_info :
6047 channel_stats.connection_infos) {
6048 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006049 continue;
6050 }
6051
6052 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006053 const cricket::Candidate& local = connection_info.local_candidate;
6054 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006055
6056 // Increment the counter for IceCandidatePairType.
6057 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6058 (local.type() == RELAY_PORT_TYPE &&
6059 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6060 type = kEnumCounterIceCandidatePairTypeTcp;
6061 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6062 type = kEnumCounterIceCandidatePairTypeUdp;
6063 } else {
6064 RTC_CHECK(0);
6065 }
6066 metrics_observer()->IncrementEnumCounter(
6067 type, GetIceCandidatePairCounter(local, remote),
6068 kIceCandidatePairMax);
6069
6070 // Increment the counter for IP type.
6071 if (local.address().family() == AF_INET) {
6072 metrics_observer()->IncrementEnumCounter(
6073 kEnumCounterAddressFamily, kBestConnections_IPv4,
6074 kPeerConnectionAddressFamilyCounter_Max);
6075
6076 } else if (local.address().family() == AF_INET6) {
6077 metrics_observer()->IncrementEnumCounter(
6078 kEnumCounterAddressFamily, kBestConnections_IPv6,
6079 kPeerConnectionAddressFamilyCounter_Max);
6080 } else {
6081 RTC_CHECK(0);
6082 }
6083
6084 return;
6085 }
6086 }
6087}
6088
6089void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006090 const cricket::TransportStats& stats,
6091 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006092 RTC_DCHECK(metrics_observer());
6093 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6094 return;
6095 }
6096
6097 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6098 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6099 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6100 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6101 return;
6102 }
6103
Steve Antonc7b964c2018-02-01 14:39:45 -08006104 for (cricket::MediaType media_type : media_types) {
6105 PeerConnectionEnumCounterType srtp_counter_type;
6106 PeerConnectionEnumCounterType ssl_counter_type;
6107 switch (media_type) {
6108 case cricket::MEDIA_TYPE_AUDIO:
6109 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6110 ssl_counter_type = kEnumCounterAudioSslCipher;
6111 break;
6112 case cricket::MEDIA_TYPE_VIDEO:
6113 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6114 ssl_counter_type = kEnumCounterVideoSslCipher;
6115 break;
6116 case cricket::MEDIA_TYPE_DATA:
6117 srtp_counter_type = kEnumCounterDataSrtpCipher;
6118 ssl_counter_type = kEnumCounterDataSslCipher;
6119 break;
6120 default:
6121 RTC_NOTREACHED();
6122 continue;
6123 }
6124 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6125 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6126 srtp_crypto_suite);
6127 }
6128 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6129 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6130 ssl_cipher_suite);
6131 }
Steve Anton75737c02017-11-06 10:37:17 -08006132 }
6133}
6134
6135void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6136 RTC_DCHECK(worker_thread()->IsCurrent());
6137 RTC_DCHECK(call_);
6138 call_->OnSentPacket(sent_packet);
6139}
6140
6141const std::string PeerConnection::GetTransportName(
6142 const std::string& content_name) {
6143 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006144 if (channel) {
6145 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006146 }
Steve Anton6fec8802017-12-04 10:37:29 -08006147 if (sctp_transport_) {
6148 RTC_DCHECK(sctp_content_name_);
6149 RTC_DCHECK(sctp_transport_name_);
6150 if (content_name == *sctp_content_name_) {
6151 return *sctp_transport_name_;
6152 }
6153 }
6154 // Return an empty string if failed to retrieve the transport name.
6155 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006156}
6157
6158void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6159 RTC_DCHECK(network_thread()->IsCurrent());
6160 transport_controller_->DestroyDtlsTransport_n(
6161 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6162}
6163
Steve Anton6fec8802017-12-04 10:37:29 -08006164void PeerConnection::DestroyTransceiverChannel(
6165 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6166 transceiver) {
6167 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006168
Steve Anton6fec8802017-12-04 10:37:29 -08006169 cricket::BaseChannel* channel = transceiver->internal()->channel();
6170 if (channel) {
6171 transceiver->internal()->SetChannel(nullptr);
6172 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006173 }
6174}
6175
6176void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006177 if (rtp_data_channel_) {
6178 OnDataChannelDestroyed();
6179 DestroyBaseChannel(rtp_data_channel_);
6180 rtp_data_channel_ = nullptr;
6181 }
6182
6183 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6184 // grab a reference to this PeerConnection. If this is called from the
6185 // PeerConnection destructor, the RefCountedObject vtable will have already
6186 // been destroyed (since it is a subclass of PeerConnection) and using
6187 // rtc::Bind will cause "Pure virtual function called" error to appear.
6188
6189 if (sctp_transport_) {
6190 OnDataChannelDestroyed();
6191 network_thread()->Invoke<void>(RTC_FROM_HERE,
6192 [this] { DestroySctpTransport_n(); });
6193 }
6194}
6195
6196void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6197 RTC_DCHECK(channel);
Zhi Huang95e7dbb2018-03-29 00:08:03 +00006198 RTC_DCHECK(channel->rtp_dtls_transport());
6199
Steve Anton6fec8802017-12-04 10:37:29 -08006200 // Need to cache these before destroying the base channel so that we do not
6201 // access uninitialized memory.
Zhi Huang95e7dbb2018-03-29 00:08:03 +00006202 const std::string transport_name =
6203 channel->rtp_dtls_transport()->transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006204 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6205
6206 switch (channel->media_type()) {
6207 case cricket::MEDIA_TYPE_AUDIO:
6208 channel_manager()->DestroyVoiceChannel(
6209 static_cast<cricket::VoiceChannel*>(channel));
6210 break;
6211 case cricket::MEDIA_TYPE_VIDEO:
6212 channel_manager()->DestroyVideoChannel(
6213 static_cast<cricket::VideoChannel*>(channel));
6214 break;
6215 case cricket::MEDIA_TYPE_DATA:
6216 channel_manager()->DestroyRtpDataChannel(
6217 static_cast<cricket::RtpDataChannel*>(channel));
6218 break;
6219 default:
6220 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6221 break;
6222 }
6223
6224 // |channel| can no longer be used.
6225
Steve Anton75737c02017-11-06 10:37:17 -08006226 transport_controller_->DestroyDtlsTransport(
6227 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6228 if (need_to_delete_rtcp) {
6229 transport_controller_->DestroyDtlsTransport(
6230 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6231 }
6232}
6233
Harald Alvestrand89061872018-01-02 14:08:34 +01006234void PeerConnection::ClearStatsCache() {
6235 if (stats_collector_) {
6236 stats_collector_->ClearCachedStatsReport();
6237 }
6238}
6239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006240} // namespace webrtc