blob: b66b89419f9e4df629f59aaafe9dbd7de7feb1a8 [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>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
23#include "api/mediaconstraintsinterface.h"
24#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
26#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800109 MSG_FREE_DATACHANNELS,
Harald Alvestrand19793842018-06-25 12:03:50 +0200110 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111};
112
Harald Alvestrand19793842018-06-25 12:03:50 +0200113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200118 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100121 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122};
123
deadbeefab9b2d12015-10-14 11:33:11 -0700124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100130 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700131};
132
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200136 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139};
140
deadbeefab9b2d12015-10-14 11:33:11 -0700141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
176 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 } else {
184 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
185 if (video_media_description_options) {
186 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700187 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700188 }
189 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700190 }
zhihuang1c378ed2017-08-17 14:10:50 -0700191}
olka3c747662017-08-17 06:50:32 -0700192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |session_options| from |rtp_data_channels|.
194void AddRtpDataChannelOptions(
195 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
196 rtp_data_channels,
197 cricket::MediaDescriptionOptions* data_media_description_options) {
198 if (!data_media_description_options) {
199 return;
200 }
deadbeefab9b2d12015-10-14 11:33:11 -0700201 // Check for data channels.
202 for (const auto& kv : rtp_data_channels) {
203 const DataChannel* channel = kv.second;
204 if (channel->state() == DataChannel::kConnecting ||
205 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700206 // Legacy RTP data channels are signaled with the track/stream ID set to
207 // the data channel's label.
208 data_media_description_options->AddRtpDataChannel(channel->label(),
209 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700210 }
211 }
212}
213
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700214uint32_t ConvertIceTransportTypeToCandidateFilter(
215 PeerConnectionInterface::IceTransportsType type) {
216 switch (type) {
217 case PeerConnectionInterface::kNone:
218 return cricket::CF_NONE;
219 case PeerConnectionInterface::kRelay:
220 return cricket::CF_RELAY;
221 case PeerConnectionInterface::kNoHost:
222 return (cricket::CF_ALL & ~cricket::CF_HOST);
223 case PeerConnectionInterface::kAll:
224 return cricket::CF_ALL;
225 default:
nissec80e7412017-01-11 05:56:46 -0800226 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700227 }
228 return cricket::CF_NONE;
229}
230
deadbeef293e9262017-01-11 12:28:30 -0800231// Helper to set an error and return from a method.
232bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
233 if (error) {
234 error->set_type(type);
235 }
236 return type == webrtc::RTCErrorType::NONE;
237}
238
Steve Anton038834f2017-07-14 15:59:59 -0700239bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
240 if (error_out) {
241 *error_out = std::move(error);
242 }
243 return error.ok();
244}
245
Steve Antonba818672017-11-06 10:21:57 -0800246std::string GetSignalingStateString(
247 PeerConnectionInterface::SignalingState state) {
248 switch (state) {
249 case PeerConnectionInterface::kStable:
250 return "kStable";
251 case PeerConnectionInterface::kHaveLocalOffer:
252 return "kHaveLocalOffer";
253 case PeerConnectionInterface::kHaveLocalPrAnswer:
254 return "kHavePrAnswer";
255 case PeerConnectionInterface::kHaveRemoteOffer:
256 return "kHaveRemoteOffer";
257 case PeerConnectionInterface::kHaveRemotePrAnswer:
258 return "kHaveRemotePrAnswer";
259 case PeerConnectionInterface::kClosed:
260 return "kClosed";
261 }
262 RTC_NOTREACHED();
263 return "";
264}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265
Steve Anton75737c02017-11-06 10:37:17 -0800266IceCandidatePairType GetIceCandidatePairCounter(
267 const cricket::Candidate& local,
268 const cricket::Candidate& remote) {
269 const auto& l = local.type();
270 const auto& r = remote.type();
271 const auto& host = LOCAL_PORT_TYPE;
272 const auto& srflx = STUN_PORT_TYPE;
273 const auto& relay = RELAY_PORT_TYPE;
274 const auto& prflx = PRFLX_PORT_TYPE;
275 if (l == host && r == host) {
276 bool local_private = IPIsPrivate(local.address().ipaddr());
277 bool remote_private = IPIsPrivate(remote.address().ipaddr());
278 if (local_private) {
279 if (remote_private) {
280 return kIceCandidatePairHostPrivateHostPrivate;
281 } else {
282 return kIceCandidatePairHostPrivateHostPublic;
283 }
284 } else {
285 if (remote_private) {
286 return kIceCandidatePairHostPublicHostPrivate;
287 } else {
288 return kIceCandidatePairHostPublicHostPublic;
289 }
290 }
291 }
292 if (l == host && r == srflx)
293 return kIceCandidatePairHostSrflx;
294 if (l == host && r == relay)
295 return kIceCandidatePairHostRelay;
296 if (l == host && r == prflx)
297 return kIceCandidatePairHostPrflx;
298 if (l == srflx && r == host)
299 return kIceCandidatePairSrflxHost;
300 if (l == srflx && r == srflx)
301 return kIceCandidatePairSrflxSrflx;
302 if (l == srflx && r == relay)
303 return kIceCandidatePairSrflxRelay;
304 if (l == srflx && r == prflx)
305 return kIceCandidatePairSrflxPrflx;
306 if (l == relay && r == host)
307 return kIceCandidatePairRelayHost;
308 if (l == relay && r == srflx)
309 return kIceCandidatePairRelaySrflx;
310 if (l == relay && r == relay)
311 return kIceCandidatePairRelayRelay;
312 if (l == relay && r == prflx)
313 return kIceCandidatePairRelayPrflx;
314 if (l == prflx && r == host)
315 return kIceCandidatePairPrflxHost;
316 if (l == prflx && r == srflx)
317 return kIceCandidatePairPrflxSrflx;
318 if (l == prflx && r == relay)
319 return kIceCandidatePairPrflxRelay;
320 return kIceCandidatePairMax;
321}
322
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800323// Logic to decide if an m= section can be recycled. This means that the new
324// m= section is not rejected, but the old local or remote m= section is
325// rejected. |old_content_one| and |old_content_two| refer to the m= section
326// of the old remote and old local descriptions in no particular order.
327// We need to check both the old local and remote because either
328// could be the most current from the latest negotation.
329bool IsMediaSectionBeingRecycled(SdpType type,
330 const ContentInfo& content,
331 const ContentInfo* old_content_one,
332 const ContentInfo* old_content_two) {
333 return type == SdpType::kOffer && !content.rejected &&
334 ((old_content_one && old_content_one->rejected) ||
335 (old_content_two && old_content_two->rejected));
336}
337
Steve Anton75737c02017-11-06 10:37:17 -0800338// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800339// |current_desc|. The number of m= sections in |new_desc| should be no
340// less than |current_desc|. In the case of checking an answer's
341// |new_desc|, the |current_desc| is the last offer that was set as the
342// local or remote. In the case of checking an offer's |new_desc| we
343// check against the local and remote descriptions stored from the last
344// negotiation, because either of these could be the most up to date for
345// possible rejected m sections. These are the |current_desc| and
346// |secondary_current_desc|.
347bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
348 const SessionDescription* secondary_current_desc,
349 const SessionDescription& new_desc,
350 const SdpType type) {
351 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800352 return false;
353 }
354
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800355 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
356 const cricket::ContentInfo* secondary_content_info = nullptr;
357 if (secondary_current_desc &&
358 i < secondary_current_desc->contents().size()) {
359 secondary_content_info = &secondary_current_desc->contents()[i];
360 }
361 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
362 &current_desc.contents()[i],
363 secondary_content_info)) {
364 // For new offer descriptions, if the media section can be recycled, it's
365 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800366 continue;
367 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800369 return false;
370 }
371 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 new_desc.contents()[i].media_description();
373 const MediaContentDescription* current_desc_mdesc =
374 current_desc.contents()[i].media_description();
375 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800376 return false;
377 }
378 }
379 return true;
380}
381
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800382bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
383 const SessionDescription& desc2) {
384 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800385}
386
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700387void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
388 cricket::MediaType media_type) {
389 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
390 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100391 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
392 KeyExchangeProtocolMedia>
393 proto_media_counter_map = {
394 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
395 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
396 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
397 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
399 kEnumCounterKeyProtocolMediaTypeDtlsData},
400 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
401 kEnumCounterKeyProtocolMediaTypeSdesAudio},
402 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
403 kEnumCounterKeyProtocolMediaTypeSdesVideo},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
405 kEnumCounterKeyProtocolMediaTypeSdesData}};
406
407 auto it = proto_media_counter_map.find({protocol_type, media_type});
408 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700409 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
410 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100411 }
412}
413
Harald Alvestrand76829d72018-07-18 23:24:36 +0200414void NoteAddIceCandidateResult(int result) {
415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
416 kAddIceCandidateMax);
417}
418
Steve Anton75737c02017-11-06 10:37:17 -0800419// Checks that each non-rejected content has SDES crypto keys or a DTLS
420// fingerprint, unless it's in a BUNDLE group, in which case only the
421// BUNDLE-tag section (first media section/description in the BUNDLE group)
422// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
423// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
424// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700425RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800430 continue;
431 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100432 // Note what media is used with each crypto protocol, for all sections.
433 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
434 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700435 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800436 const std::string& mid = content_info.name;
437 if (bundle && bundle->HasContentName(mid) &&
438 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 // This isn't the first media section in the BUNDLE group, so it's not
440 // required to have crypto attributes, since only the crypto attributes
441 // from the first section actually get used.
442 continue;
443 }
444
445 // If the content isn't rejected or bundled into another m= section, crypto
446 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800447 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800448 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800449 if (!media || !tinfo) {
450 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800452 }
453 if (dtls_enabled) {
454 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_WARNING)
456 << "Session description must have DTLS fingerprint if "
457 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800458 return RTCError(RTCErrorType::INVALID_PARAMETER,
459 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800460 }
461 } else {
462 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800464 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800465 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800466 }
467 }
468 }
Steve Anton8a006912017-12-04 15:25:56 -0800469 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800470}
471
472// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
473// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
474// media section/description in the BUNDLE group) needs a ufrag and pwd.
475bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 const std::string& mid = content_info.name;
483 if (bundle && bundle->HasContentName(mid) &&
484 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800485 // This isn't the first media section in the BUNDLE group, so it's not
486 // required to have ufrag/password, since only the ufrag/password from
487 // the first section actually get used.
488 continue;
489 }
490
491 // If the content isn't rejected or bundled into another m= section,
492 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800493 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800494 if (!tinfo) {
495 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800497 return false;
498 }
499 if (tinfo->description.ice_ufrag.empty() ||
500 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800502 return false;
503 }
504 }
505 return true;
506}
507
508bool GetTrackIdBySsrc(const SessionDescription* session_description,
509 uint32_t ssrc,
510 std::string* track_id) {
511 RTC_DCHECK(track_id != NULL);
512
Steve Antonb1c1de12017-12-21 15:14:30 -0800513 const cricket::AudioContentDescription* audio_desc =
514 cricket::GetFirstAudioContentDescription(session_description);
515 if (audio_desc) {
516 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800517 if (found) {
518 *track_id = found->id;
519 return true;
520 }
521 }
522
Steve Antonb1c1de12017-12-21 15:14:30 -0800523 const cricket::VideoContentDescription* video_desc =
524 cricket::GetFirstVideoContentDescription(session_description);
525 if (video_desc) {
526 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800527 if (found) {
528 *track_id = found->id;
529 return true;
530 }
531 }
532 return false;
533}
534
535// Get the SCTP port out of a SessionDescription.
536// Return -1 if not found.
537int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800538 const cricket::DataContentDescription* data_desc =
539 GetFirstDataContentDescription(session_description);
540 RTC_DCHECK(data_desc);
541 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800542 return -1;
543 }
Steve Anton75737c02017-11-06 10:37:17 -0800544 std::string value;
545 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
546 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800547 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!codec.Matches(match_pattern)) {
549 continue;
550 }
551 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
552 return rtc::FromString<int>(value);
553 }
554 }
555 return -1;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
595 std::ostringstream oss;
596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
598 return oss.str();
599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Steve Anton75737c02017-11-06 10:37:17 -0800621} // namespace
622
Henrik Boström31638672017-11-23 17:48:32 +0100623// Upon completion, posts a task to execute the callback of the
624// SetSessionDescriptionObserver asynchronously on the same thread. At this
625// point, the state of the peer connection might no longer reflect the effects
626// of the SetRemoteDescription operation, as the peer connection could have been
627// modified during the post.
628// TODO(hbos): Remove this class once we remove the version of
629// PeerConnectionInterface::SetRemoteDescription() that takes a
630// SetSessionDescriptionObserver as an argument.
631class PeerConnection::SetRemoteDescriptionObserverAdapter
632 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
633 public:
634 SetRemoteDescriptionObserverAdapter(
635 rtc::scoped_refptr<PeerConnection> pc,
636 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
637 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
638
639 // SetRemoteDescriptionObserverInterface implementation.
640 void OnSetRemoteDescriptionComplete(RTCError error) override {
641 if (error.ok())
642 pc_->PostSetSessionDescriptionSuccess(wrapper_);
643 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100644 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100645 }
646
647 private:
648 rtc::scoped_refptr<PeerConnection> pc_;
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
650};
651
deadbeef293e9262017-01-11 12:28:30 -0800652bool PeerConnectionInterface::RTCConfiguration::operator==(
653 const PeerConnectionInterface::RTCConfiguration& o) const {
654 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700655 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800656 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000657 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800659 BundlePolicy bundle_policy;
660 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
662 int ice_candidate_pool_size;
663 bool disable_ipv6;
664 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700665 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100666 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200668 absl::optional<int> screencast_min_bitrate;
669 absl::optional<bool> combined_audio_video_bwe;
670 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800671 TcpCandidatePolicy tcp_candidate_policy;
672 CandidateNetworkPolicy candidate_network_policy;
673 int audio_jitter_buffer_max_packets;
674 bool audio_jitter_buffer_fast_accelerate;
675 int ice_connection_receiving_timeout;
676 int ice_backup_candidate_pair_ping_interval;
677 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800678 bool prioritize_most_likely_ice_candidate_pairs;
679 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prune_turn_ports;
681 bool presume_writable_when_fully_relayed;
682 bool enable_ice_renomination;
683 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200684 absl::optional<int> ice_check_interval_strong_connectivity;
685 absl::optional<int> ice_check_interval_weak_connectivity;
686 absl::optional<int> ice_check_min_interval;
687 absl::optional<int> ice_unwritable_timeout;
688 absl::optional<int> ice_unwritable_min_checks;
689 absl::optional<int> stun_candidate_keepalive_interval;
690 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200691 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800692 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200693 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700694 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800695 };
696 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
697 "Did you add something to RTCConfiguration and forget to "
698 "update operator==?");
699 return type == o.type && servers == o.servers &&
700 bundle_policy == o.bundle_policy &&
701 rtcp_mux_policy == o.rtcp_mux_policy &&
702 tcp_candidate_policy == o.tcp_candidate_policy &&
703 candidate_network_policy == o.candidate_network_policy &&
704 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
705 audio_jitter_buffer_fast_accelerate ==
706 o.audio_jitter_buffer_fast_accelerate &&
707 ice_connection_receiving_timeout ==
708 o.ice_connection_receiving_timeout &&
709 ice_backup_candidate_pair_ping_interval ==
710 o.ice_backup_candidate_pair_ping_interval &&
711 continual_gathering_policy == o.continual_gathering_policy &&
712 certificates == o.certificates &&
713 prioritize_most_likely_ice_candidate_pairs ==
714 o.prioritize_most_likely_ice_candidate_pairs &&
715 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800716 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700717 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100718 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800719 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800720 screencast_min_bitrate == o.screencast_min_bitrate &&
721 combined_audio_video_bwe == o.combined_audio_video_bwe &&
722 enable_dtls_srtp == o.enable_dtls_srtp &&
723 ice_candidate_pool_size == o.ice_candidate_pool_size &&
724 prune_turn_ports == o.prune_turn_ports &&
725 presume_writable_when_fully_relayed ==
726 o.presume_writable_when_fully_relayed &&
727 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800728 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800729 ice_check_interval_strong_connectivity ==
730 o.ice_check_interval_strong_connectivity &&
731 ice_check_interval_weak_connectivity ==
732 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700734 ice_unwritable_timeout == o.ice_unwritable_timeout &&
735 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800736 stun_candidate_keepalive_interval ==
737 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200738 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800739 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800740 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700741 network_preference == o.network_preference &&
742 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800743}
744
745bool PeerConnectionInterface::RTCConfiguration::operator!=(
746 const PeerConnectionInterface::RTCConfiguration& o) const {
747 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800748}
749
zhihuang8f65cdf2016-05-06 18:40:30 -0700750// Generate a RTCP CNAME when a PeerConnection is created.
751std::string GenerateRtcpCname() {
752 std::string cname;
753 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100754 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800755 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700756 }
757 return cname;
758}
759
zhihuang1c378ed2017-08-17 14:10:50 -0700760bool ValidateOfferAnswerOptions(
761 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
762 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
763 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700764}
765
zhihuang1c378ed2017-08-17 14:10:50 -0700766// From |rtc_options|, fill parts of |session_options| shared by all generated
767// m= sections (in other words, nothing that involves a map/array).
768void ExtractSharedMediaSessionOptions(
769 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
770 cricket::MediaSessionOptions* session_options) {
771 session_options->vad_enabled = rtc_options.voice_activity_detection;
772 session_options->bundle_enabled = rtc_options.use_rtp_mux;
773}
zhihuanga77e6bb2017-08-14 18:17:48 -0700774
zhihuang1c378ed2017-08-17 14:10:50 -0700775bool ConvertConstraintsToOfferAnswerOptions(
776 const MediaConstraintsInterface* constraints,
777 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700778 if (!constraints) {
779 return true;
780 }
zhihuang1c378ed2017-08-17 14:10:50 -0700781
782 bool value = false;
783 size_t mandatory_constraints_satisfied = 0;
784
785 if (FindConstraint(constraints,
786 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
787 &mandatory_constraints_satisfied)) {
788 offer_answer_options->offer_to_receive_audio =
789 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
790 kOfferToReceiveMediaTrue
791 : 0;
792 }
793
794 if (FindConstraint(constraints,
795 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
796 &mandatory_constraints_satisfied)) {
797 offer_answer_options->offer_to_receive_video =
798 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
799 kOfferToReceiveMediaTrue
800 : 0;
801 }
802 if (FindConstraint(constraints,
803 MediaConstraintsInterface::kVoiceActivityDetection, &value,
804 &mandatory_constraints_satisfied)) {
805 offer_answer_options->voice_activity_detection = value;
806 }
807 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
808 &mandatory_constraints_satisfied)) {
809 offer_answer_options->use_rtp_mux = value;
810 }
811 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
812 &value, &mandatory_constraints_satisfied)) {
813 offer_answer_options->ice_restart = value;
814 }
815
deadbeefab9b2d12015-10-14 11:33:11 -0700816 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
817}
818
zhihuang38ede132017-06-15 12:52:32 -0700819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 11:20:13 -0800833 // Need to stop transceivers before destroying the stats collector because
834 // AudioRtpSender has a reference to the StatsCollector it will update when
835 // stopping.
836 for (auto transceiver : transceivers_) {
837 transceiver->Stop();
838 }
Steve Anton4171afb2017-11-20 10:20:22 -0800839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Don't destroy BaseChannels until after stats has been cleaned up so that
847 // the last stats request can still read from the channels.
848 DestroyAllChannels();
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 16:55:30 -0700857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700862 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800863 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700864 event_log_.reset();
865 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866}
867
Steve Anton8af21862017-12-15 11:20:13 -0800868void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800869 // Destroy video channels first since they may have a pointer to a voice
870 // channel.
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800872 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800878 DestroyTransceiverChannel(transceiver);
879 }
880 }
881 DestroyDataChannel();
882}
883
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000885 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700886 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700888
889 RTCError config_error = ValidateConfiguration(configuration);
890 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700892 return false;
893 }
894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_ERROR)
897 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100898 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800899 return false;
900 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200901
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800903 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100905 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800906 return false;
907 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 observer_ = dependencies.observer;
910 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800912
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200913 cricket::ServerAddresses stun_servers;
914 std::vector<cricket::RelayServerConfig> turn_servers;
915
916 RTCErrorType parse_error =
917 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
918 if (parse_error != RTCErrorType::NONE) {
919 return false;
920 }
921
deadbeef91dd5672016-05-18 16:55:30 -0700922 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700923 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700924 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200925 RTC_FROM_HERE,
926 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
927 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928 return false;
929 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200930 // If initialization was successful, note if STUN or TURN servers
931 // were supplied.
932 if (!stun_servers.empty()) {
933 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
934 }
935 if (!turn_servers.empty()) {
936 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
937 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700939 // Send information about IPv4/IPv6 status.
940 PeerConnectionAddressFamilyCounter address_family;
941 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
942 address_family = kPeerConnection_IPv6;
943 } else {
944 address_family = kPeerConnection_IPv4;
945 }
946 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
947 kPeerConnectionAddressFamilyCounter_Max);
948
Zhi Huange830e682018-03-30 10:48:35 -0700949 const PeerConnectionFactoryInterface::Options& options = factory_->options();
950
Steve Anton75737c02017-11-06 10:37:17 -0800951 // RFC 3264: The numeric value of the session id and version in the
952 // o line MUST be representable with a "64 bit signed integer".
953 // Due to this constraint session id |session_id_| is max limited to
954 // LLONG_MAX.
955 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700956 JsepTransportController::Config config;
957 config.redetermine_role_on_ice_restart =
958 configuration.redetermine_role_on_ice_restart;
959 config.ssl_max_version = factory_->options().ssl_max_version;
960 config.disable_encryption = options.disable_encryption;
961 config.bundle_policy = configuration.bundle_policy;
962 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
963 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700964 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700965 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700966#if defined(ENABLE_EXTERNAL_AUTH)
967 config.enable_external_auth = true;
968#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700969 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700970 transport_controller_.reset(new JsepTransportController(
971 signaling_thread(), network_thread(), port_allocator_.get(), config));
972 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800973 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700974 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800975 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700976 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800977 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700978 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800979 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
980 transport_controller_->SignalDtlsHandshakeError.connect(
981 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
982
983 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700984
deadbeefab9b2d12015-10-14 11:33:11 -0700985 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700986 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987
Steve Antonba818672017-11-06 10:21:57 -0800988 configuration_ = configuration;
989
Steve Anton75737c02017-11-06 10:37:17 -0800990 // Obtain a certificate from RTCConfiguration if any were provided (optional).
991 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
992 if (!configuration.certificates.empty()) {
993 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
994 // just picking the first one. The decision should be made based on the DTLS
995 // handshake. The DTLS negotiations need to know about all certificates.
996 certificate = configuration.certificates[0];
997 }
998
Steve Antond25da372017-11-06 14:50:29 -0800999 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001000
1001 if (options.disable_encryption) {
1002 dtls_enabled_ = false;
1003 } else {
1004 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001006 // |configuration| can override the default |dtls_enabled_| value.
1007 if (configuration.enable_dtls_srtp) {
1008 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1009 }
1010 }
1011
1012 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1013 // It takes precendence over the disable_sctp_data_channels
1014 // PeerConnectionFactoryInterface::Options.
1015 if (configuration.enable_rtp_data_channel) {
1016 data_channel_type_ = cricket::DCT_RTP;
1017 } else {
1018 // DTLS has to be enabled to use SCTP.
1019 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1020 data_channel_type_ = cricket::DCT_SCTP;
1021 }
1022 }
1023
1024 video_options_.screencast_min_bitrate_kbps =
1025 configuration.screencast_min_bitrate;
1026 audio_options_.combined_audio_video_bwe =
1027 configuration.combined_audio_video_bwe;
1028
1029 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001030 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001031
1032 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001033 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001034
1035 // Whether the certificate generator/certificate is null or not determines
1036 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1037 // the right instructions by clearing the variables if needed.
1038 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001039 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001040 certificate = nullptr;
1041 } else if (certificate) {
1042 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001043 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001044 }
1045
1046 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1047 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001048 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001049 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1050 this, &PeerConnection::OnCertificateReady);
1051
1052 if (options.disable_encryption) {
1053 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1054 }
1055
1056 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1057 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058
Steve Anton4171afb2017-11-20 10:20:22 -08001059 // Add default audio/video transceivers for Plan B SDP.
1060 if (!IsUnifiedPlan()) {
1061 transceivers_.push_back(
1062 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1063 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1064 transceivers_.push_back(
1065 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1066 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1067 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001068 int delay_ms =
1069 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1070 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1071 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 return true;
1073}
1074
Steve Anton038834f2017-07-14 15:59:59 -07001075RTCError PeerConnection::ValidateConfiguration(
1076 const RTCConfiguration& config) const {
1077 if (config.ice_regather_interval_range &&
1078 config.continual_gathering_policy == GATHER_ONCE) {
1079 return RTCError(RTCErrorType::INVALID_PARAMETER,
1080 "ice_regather_interval_range specified but continual "
1081 "gathering policy is GATHER_ONCE");
1082 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001083 auto result =
1084 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1085 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001086}
1087
Yves Gerey665174f2018-06-19 15:03:05 +02001088rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001089 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1090 "Plan SdpSemantics. Please use GetSenders "
1091 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001092 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093}
1094
Yves Gerey665174f2018-06-19 15:03:05 +02001095rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001096 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1097 "Plan SdpSemantics. Please use GetReceivers "
1098 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001099 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100}
1101
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001102bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001103 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1104 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001105 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 if (IsClosed()) {
1107 return false;
1108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 return false;
1111 }
deadbeefab9b2d12015-10-14 11:33:11 -07001112
1113 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001114 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1115 observer->SignalAudioTrackAdded.connect(this,
1116 &PeerConnection::OnAudioTrackAdded);
1117 observer->SignalAudioTrackRemoved.connect(
1118 this, &PeerConnection::OnAudioTrackRemoved);
1119 observer->SignalVideoTrackAdded.connect(this,
1120 &PeerConnection::OnVideoTrackAdded);
1121 observer->SignalVideoTrackRemoved.connect(
1122 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001123 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001124
deadbeefab9b2d12015-10-14 11:33:11 -07001125 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001126 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001127 }
1128 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001129 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001130 }
1131
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001132 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001133 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134 return true;
1135}
1136
1137void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001138 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1139 "Plan SdpSemantics. Please use RemoveTrack "
1140 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001141 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001142 if (!IsClosed()) {
1143 for (const auto& track : local_stream->GetAudioTracks()) {
1144 RemoveAudioTrack(track.get(), local_stream);
1145 }
1146 for (const auto& track : local_stream->GetVideoTracks()) {
1147 RemoveVideoTrack(track.get(), local_stream);
1148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001151 stream_observers_.erase(
1152 std::remove_if(
1153 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001154 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001155 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001156 }),
1157 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001158
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159 if (IsClosed()) {
1160 return;
1161 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001162 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163}
1164
Steve Anton2d6c76a2018-01-05 17:10:52 -08001165RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001166 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001167 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001168 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001169 if (!track) {
1170 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1171 }
1172 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1173 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1174 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1175 "Track has invalid kind: " + track->kind());
1176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 if (IsClosed()) {
1178 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1179 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001180 }
Steve Anton4171afb2017-11-20 10:20:22 -08001181 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001182 LOG_AND_RETURN_ERROR(
1183 RTCErrorType::INVALID_PARAMETER,
1184 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001185 }
Steve Antonf9381f02017-12-14 10:23:57 -08001186 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1188 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001189 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001190 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001191 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001192 }
1193 return sender_or_error;
1194}
deadbeefe1f9d832016-01-14 15:35:42 -08001195
Steve Antonf9381f02017-12-14 10:23:57 -08001196RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1197PeerConnection::AddTrackPlanB(
1198 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001199 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 if (stream_ids.size() > 1u) {
1201 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1202 "AddTrack with more than one stream is not "
1203 "supported with Plan B semantics.");
1204 }
1205 std::vector<std::string> adjusted_stream_ids = stream_ids;
1206 if (adjusted_stream_ids.empty()) {
1207 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1208 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001209 cricket::MediaType media_type =
1210 (track->kind() == MediaStreamTrackInterface::kAudioKind
1211 ? cricket::MEDIA_TYPE_AUDIO
1212 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001213 auto new_sender =
1214 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001215 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001216 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001218 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001219 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001220 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001221 if (sender_info) {
1222 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 } else {
1225 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001226 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001227 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001228 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001229 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001230 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001231 if (sender_info) {
1232 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001233 }
deadbeefe1f9d832016-01-14 15:35:42 -08001234 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001235 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001236}
deadbeefe1f9d832016-01-14 15:35:42 -08001237
Steve Antonf9381f02017-12-14 10:23:57 -08001238RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1239PeerConnection::AddTrackUnifiedPlan(
1240 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001241 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001242 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1243 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001244 RTC_LOG(LS_INFO) << "Reusing an existing "
1245 << cricket::MediaTypeToString(transceiver->media_type())
1246 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001247 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001248 transceiver->internal()->set_direction(
1249 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001250 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001251 transceiver->internal()->set_direction(
1252 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001253 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001254 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001255 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001256 } else {
1257 cricket::MediaType media_type =
1258 (track->kind() == MediaStreamTrackInterface::kAudioKind
1259 ? cricket::MEDIA_TYPE_AUDIO
1260 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001261 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1262 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001263 std::string sender_id = track->id();
1264 // Avoid creating a sender with an existing ID by generating a random ID.
1265 // This can happen if this is the second time AddTrack has created a sender
1266 // for this track.
1267 if (FindSenderById(sender_id)) {
1268 sender_id = rtc::CreateRandomUuid();
1269 }
1270 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001271 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1272 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001273 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001274 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001275 }
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return transceiver->sender();
1277}
1278
1279rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1280PeerConnection::FindFirstTransceiverForAddedTrack(
1281 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1282 RTC_DCHECK(track);
1283 for (auto transceiver : transceivers_) {
1284 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001285 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001286 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001287 !transceiver->internal()->has_ever_been_used_to_send() &&
1288 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001289 return transceiver;
1290 }
1291 }
1292 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001293}
1294
1295bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1296 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001297 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001298}
1299
Steve Anton24db5732018-07-23 10:27:33 -07001300RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001301 rtc::scoped_refptr<RtpSenderInterface> sender) {
1302 if (!sender) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1304 }
deadbeefe1f9d832016-01-14 15:35:42 -08001305 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001306 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1307 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001308 }
Steve Antonf9381f02017-12-14 10:23:57 -08001309 if (IsUnifiedPlan()) {
1310 auto transceiver = FindTransceiverBySender(sender);
1311 if (!transceiver || !sender->track()) {
1312 return RTCError::OK();
1313 }
1314 sender->SetTrack(nullptr);
1315 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001316 transceiver->internal()->set_direction(
1317 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001318 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001319 transceiver->internal()->set_direction(
1320 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 }
Steve Anton4171afb2017-11-20 10:20:22 -08001322 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001323 bool removed;
1324 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1325 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1326 } else {
1327 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1328 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1329 }
1330 if (!removed) {
1331 LOG_AND_RETURN_ERROR(
1332 RTCErrorType::INVALID_PARAMETER,
1333 "Couldn't find sender " + sender->id() + " to remove.");
1334 }
Steve Anton4171afb2017-11-20 10:20:22 -08001335 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001336 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001337 return RTCError::OK();
1338}
1339
1340rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1341PeerConnection::FindTransceiverBySender(
1342 rtc::scoped_refptr<RtpSenderInterface> sender) {
1343 for (auto transceiver : transceivers_) {
1344 if (transceiver->sender() == sender) {
1345 return transceiver;
1346 }
1347 }
1348 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001349}
1350
Steve Anton9158ef62017-11-27 13:01:52 -08001351RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1352PeerConnection::AddTransceiver(
1353 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1354 return AddTransceiver(track, RtpTransceiverInit());
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(
1359 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1360 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001361 RTC_CHECK(IsUnifiedPlan())
1362 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001363 if (!track) {
1364 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1365 }
1366 cricket::MediaType media_type;
1367 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1368 media_type = cricket::MEDIA_TYPE_AUDIO;
1369 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1370 media_type = cricket::MEDIA_TYPE_VIDEO;
1371 } else {
1372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1373 "Track kind is not audio or video");
1374 }
1375 return AddTransceiver(media_type, track, init);
1376}
1377
1378RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1379PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1380 return AddTransceiver(media_type, RtpTransceiverInit());
1381}
1382
1383RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1384PeerConnection::AddTransceiver(cricket::MediaType media_type,
1385 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001386 RTC_CHECK(IsUnifiedPlan())
1387 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001388 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1389 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1391 "media type is not audio or video");
1392 }
1393 return AddTransceiver(media_type, nullptr, init);
1394}
1395
1396RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1397PeerConnection::AddTransceiver(
1398 cricket::MediaType media_type,
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001400 const RtpTransceiverInit& init,
1401 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001402 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1403 media_type == cricket::MEDIA_TYPE_VIDEO));
1404 if (track) {
1405 RTC_DCHECK_EQ(media_type,
1406 (track->kind() == MediaStreamTrackInterface::kAudioKind
1407 ? cricket::MEDIA_TYPE_AUDIO
1408 : cricket::MEDIA_TYPE_VIDEO));
1409 }
1410
1411 // TODO(bugs.webrtc.org/7600): Verify init.
1412
Steve Anton3d954a62018-04-02 11:27:23 -07001413 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1414 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001415 // Set the sender ID equal to the track ID if the track is specified unless
1416 // that sender ID is already in use.
1417 std::string sender_id =
1418 (track && !FindSenderById(track->id()) ? track->id()
1419 : rtc::CreateRandomUuid());
1420 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1422 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1423 transceiver->internal()->set_direction(init.direction);
1424
Steve Anton22da89f2018-01-25 13:58:07 -08001425 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001426 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001427 }
Steve Antonf9381f02017-12-14 10:23:57 -08001428
1429 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1430}
1431
Steve Anton02ee47c2018-01-10 16:26:06 -08001432rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1433PeerConnection::CreateSender(
1434 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001435 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001436 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001437 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001438 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001439 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1440 RTC_DCHECK(!track ||
1441 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1442 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1443 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001444 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001445 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 } else {
1447 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1448 RTC_DCHECK(!track ||
1449 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1450 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001451 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001452 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001453 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001454 bool set_track_succeeded = sender->SetTrack(track);
1455 RTC_DCHECK(set_track_succeeded);
1456 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001457 return sender;
1458}
1459
1460rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1461PeerConnection::CreateReceiver(cricket::MediaType media_type,
1462 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001463 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1464 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001465 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001466 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001467 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1468 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001469 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001470 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001471 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001472 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001473 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1474 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001475 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001476 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001477 return receiver;
1478}
1479
1480rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1481PeerConnection::CreateAndAddTransceiver(
1482 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1483 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1484 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001485 // Ensure that the new sender does not have an ID that is already in use by
1486 // another sender.
1487 // Allow receiver IDs to conflict since those come from remote SDP (which
1488 // could be invalid, but should not cause a crash).
1489 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001490 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1491 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001492 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001493 transceiver->internal()->SignalNegotiationNeeded.connect(
1494 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001495 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001496}
1497
Steve Anton52d86772018-02-20 15:48:12 -08001498void PeerConnection::OnNegotiationNeeded() {
1499 RTC_DCHECK_RUN_ON(signaling_thread());
1500 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001501 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001502}
1503
deadbeeffac06552015-11-25 11:26:01 -08001504rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001505 const std::string& kind,
1506 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001507 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1508 "Plan SdpSemantics. Please use AddTransceiver "
1509 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001510 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001511 if (IsClosed()) {
1512 return nullptr;
1513 }
Steve Anton4171afb2017-11-20 10:20:22 -08001514
Seth Hampson5b4f0752018-04-02 16:31:36 -07001515 // Internally we need to have one stream with Plan B semantics, so we
1516 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001517 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001518 if (stream_id.empty()) {
1519 stream_ids.push_back(rtc::CreateRandomUuid());
1520 RTC_LOG(LS_INFO)
1521 << "No stream_id specified for sender. Generated stream ID: "
1522 << stream_ids[0];
1523 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001524 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001525 }
1526
Steve Anton4171afb2017-11-20 10:20:22 -08001527 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001528 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001529 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001530 auto* audio_sender = new AudioRtpSender(
1531 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001532 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001533 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001535 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001536 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001537 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001538 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001539 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001540 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001541 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001542 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001543 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001544 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001545 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001546 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001547 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001548
deadbeefe1f9d832016-01-14 15:35:42 -08001549 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001550}
1551
deadbeef70ab1a12015-09-28 16:53:55 -07001552std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1553 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001554 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001555 for (auto sender : GetSendersInternal()) {
1556 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001557 }
1558 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001559}
1560
Steve Anton4171afb2017-11-20 10:20:22 -08001561std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1562PeerConnection::GetSendersInternal() const {
1563 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1564 all_senders;
1565 for (auto transceiver : transceivers_) {
1566 auto senders = transceiver->internal()->senders();
1567 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1568 }
1569 return all_senders;
1570}
1571
deadbeef70ab1a12015-09-28 16:53:55 -07001572std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1573PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001574 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001575 for (const auto& receiver : GetReceiversInternal()) {
1576 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001577 }
1578 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001579}
1580
Steve Anton4171afb2017-11-20 10:20:22 -08001581std::vector<
1582 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1583PeerConnection::GetReceiversInternal() const {
1584 std::vector<
1585 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1586 all_receivers;
1587 for (auto transceiver : transceivers_) {
1588 auto receivers = transceiver->internal()->receivers();
1589 all_receivers.insert(all_receivers.end(), receivers.begin(),
1590 receivers.end());
1591 }
1592 return all_receivers;
1593}
1594
Steve Anton9158ef62017-11-27 13:01:52 -08001595std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1596PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001597 RTC_CHECK(IsUnifiedPlan())
1598 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001599 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1600 for (auto transceiver : transceivers_) {
1601 all_transceivers.push_back(transceiver);
1602 }
1603 return all_transceivers;
1604}
1605
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001607 MediaStreamTrackInterface* track,
1608 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001609 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001610 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001611 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001612 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001613 return false;
1614 }
1615
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001616 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001617 // The StatsCollector is used to tell if a track is valid because it may
1618 // remember tracks that the PeerConnection previously removed.
1619 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001620 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1621 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001622 return false;
1623 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001624 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001625 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 return true;
1627}
1628
hbos74e1a4f2016-09-15 23:33:01 -07001629void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001630 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001631 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001632 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001633 stats_collector_->GetStatsReport(callback);
1634}
1635
Henrik Boström1df1bf82018-03-20 13:24:20 +01001636void PeerConnection::GetStats(
1637 rtc::scoped_refptr<RtpSenderInterface> selector,
1638 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1639 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1640 RTC_DCHECK(callback);
1641 RTC_DCHECK(stats_collector_);
1642 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1643 if (selector) {
1644 for (const auto& proxy_transceiver : transceivers_) {
1645 for (const auto& proxy_sender :
1646 proxy_transceiver->internal()->senders()) {
1647 if (proxy_sender == selector) {
1648 internal_sender = proxy_sender->internal();
1649 break;
1650 }
1651 }
1652 if (internal_sender)
1653 break;
1654 }
1655 }
1656 // If there is no |internal_sender| then |selector| is either null or does not
1657 // belong to the PeerConnection (in Plan B, senders can be removed from the
1658 // PeerConnection). This means that "all the stats objects representing the
1659 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1660 // produces an empty stats report.
1661 stats_collector_->GetStatsReport(internal_sender, callback);
1662}
1663
1664void PeerConnection::GetStats(
1665 rtc::scoped_refptr<RtpReceiverInterface> selector,
1666 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1667 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1668 RTC_DCHECK(callback);
1669 RTC_DCHECK(stats_collector_);
1670 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1671 if (selector) {
1672 for (const auto& proxy_transceiver : transceivers_) {
1673 for (const auto& proxy_receiver :
1674 proxy_transceiver->internal()->receivers()) {
1675 if (proxy_receiver == selector) {
1676 internal_receiver = proxy_receiver->internal();
1677 break;
1678 }
1679 }
1680 if (internal_receiver)
1681 break;
1682 }
1683 }
1684 // If there is no |internal_receiver| then |selector| is either null or does
1685 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1686 // the PeerConnection). This means that "all the stats objects representing
1687 // the selector" is an empty set. Invoking GetStatsReport() with a null
1688 // selector produces an empty stats report.
1689 stats_collector_->GetStatsReport(internal_receiver, callback);
1690}
1691
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1693 return signaling_state_;
1694}
1695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696PeerConnectionInterface::IceConnectionState
1697PeerConnection::ice_connection_state() {
1698 return ice_connection_state_;
1699}
1700
1701PeerConnectionInterface::IceGatheringState
1702PeerConnection::ice_gathering_state() {
1703 return ice_gathering_state_;
1704}
1705
Yves Gerey665174f2018-06-19 15:03:05 +02001706rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 const std::string& label,
1708 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001709 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001710
deadbeefab9b2d12015-10-14 11:33:11 -07001711 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001712
kwibergd1fe2812016-04-27 06:47:29 -07001713 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001714 if (config) {
1715 internal_config.reset(new InternalDataChannelInit(*config));
1716 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001717 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001718 InternalCreateDataChannel(label, internal_config.get()));
1719 if (!channel.get()) {
1720 return nullptr;
1721 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001723 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1724 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001725 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001726 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001727 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001728 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729 return DataChannelProxy::Create(signaling_thread(), channel.get());
1730}
1731
1732void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1733 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001734 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001735
zhihuang1c378ed2017-08-17 14:10:50 -07001736 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1737 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1738 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1739 // compares the mandatory fields parsed with the mandatory fields added in the
1740 // |constraints| and some downstream applications might create offers with
1741 // mandatory fields which would not be parsed in the helper method. For
1742 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1743 // |constraints| as a mandatory field but it is not parsed.
1744 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001745
zhihuang1c378ed2017-08-17 14:10:50 -07001746 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001747}
1748
1749void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1750 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001751 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001752
nisse7ce109a2017-01-31 00:57:56 -08001753 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001754 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001755 return;
1756 }
deadbeefab9b2d12015-10-14 11:33:11 -07001757
Steve Anton8d3444d2017-10-20 15:30:51 -07001758 if (IsClosed()) {
1759 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001761 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001762 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001763 return;
1764 }
1765
zhihuang1c378ed2017-08-17 14:10:50 -07001766 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001767 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001769 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001770 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001771 return;
1772 }
1773
Steve Anton22da89f2018-01-25 13:58:07 -08001774 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1775 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1776 if (IsUnifiedPlan()) {
1777 RTCError error = HandleLegacyOfferOptions(options);
1778 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001779 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001780 return;
1781 }
1782 }
1783
zhihuang1c378ed2017-08-17 14:10:50 -07001784 cricket::MediaSessionOptions session_options;
1785 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001786 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787}
1788
Steve Anton22da89f2018-01-25 13:58:07 -08001789RTCError PeerConnection::HandleLegacyOfferOptions(
1790 const RTCOfferAnswerOptions& options) {
1791 RTC_DCHECK(IsUnifiedPlan());
1792
1793 if (options.offer_to_receive_audio == 0) {
1794 RemoveRecvDirectionFromReceivingTransceiversOfType(
1795 cricket::MEDIA_TYPE_AUDIO);
1796 } else if (options.offer_to_receive_audio == 1) {
1797 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1798 } else if (options.offer_to_receive_audio > 1) {
1799 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1800 "offer_to_receive_audio > 1 is not supported.");
1801 }
1802
1803 if (options.offer_to_receive_video == 0) {
1804 RemoveRecvDirectionFromReceivingTransceiversOfType(
1805 cricket::MEDIA_TYPE_VIDEO);
1806 } else if (options.offer_to_receive_video == 1) {
1807 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1808 } else if (options.offer_to_receive_video > 1) {
1809 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1810 "offer_to_receive_video > 1 is not supported.");
1811 }
1812
1813 return RTCError::OK();
1814}
1815
1816void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1817 cricket::MediaType media_type) {
1818 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001819 RtpTransceiverDirection new_direction =
1820 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1821 if (new_direction != transceiver->direction()) {
1822 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1823 << " transceiver (MID="
1824 << transceiver->mid().value_or("<not set>") << ") from "
1825 << RtpTransceiverDirectionToString(
1826 transceiver->direction())
1827 << " to "
1828 << RtpTransceiverDirectionToString(new_direction)
1829 << " since CreateOffer specified offer_to_receive=0";
1830 transceiver->internal()->set_direction(new_direction);
1831 }
Steve Anton22da89f2018-01-25 13:58:07 -08001832 }
1833}
1834
1835void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1836 cricket::MediaType media_type) {
1837 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001838 RTC_LOG(LS_INFO)
1839 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1840 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001841 RtpTransceiverInit init;
1842 init.direction = RtpTransceiverDirection::kRecvOnly;
1843 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1844 }
1845}
1846
1847std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1848PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1849 std::vector<
1850 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1851 receiving_transceivers;
1852 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001853 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001854 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1855 receiving_transceivers.push_back(transceiver);
1856 }
1857 }
1858 return receiving_transceivers;
1859}
1860
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861void PeerConnection::CreateAnswer(
1862 CreateSessionDescriptionObserver* observer,
1863 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001864 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001865
nisse7ce109a2017-01-31 00:57:56 -08001866 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001868 return;
1869 }
deadbeefab9b2d12015-10-14 11:33:11 -07001870
zhihuang1c378ed2017-08-17 14:10:50 -07001871 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1872 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1873 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001874 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001875 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001876 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001877 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001878 return;
1879 }
1880
Steve Anton8d3444d2017-10-20 15:30:51 -07001881 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001882}
1883
1884void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1885 const RTCOfferAnswerOptions& options) {
1886 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001887 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001888 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001889 return;
1890 }
1891
Steve Antondffead82018-02-06 10:31:29 -08001892 if (!(signaling_state_ == kHaveRemoteOffer ||
1893 signaling_state_ == kHaveLocalPrAnswer)) {
1894 std::string error =
1895 "PeerConnection cannot create an answer in a state other than "
1896 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001897 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001898 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001899 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001900 return;
1901 }
1902
Steve Antondffead82018-02-06 10:31:29 -08001903 // The remote description should be set if we're in the right state.
1904 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001905
Steve Anton22da89f2018-01-25 13:58:07 -08001906 if (IsUnifiedPlan()) {
1907 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1908 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1909 "supported with Unified Plan semantics. Use the "
1910 "RtpTransceiver API instead.";
1911 }
1912 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1913 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1914 "supported with Unified Plan semantics. Use the "
1915 "RtpTransceiver API instead.";
1916 }
1917 }
1918
htaa2a49d92016-03-04 02:51:39 -08001919 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001920 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001921
Steve Antond25da372017-11-06 14:50:29 -08001922 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001923}
1924
1925void PeerConnection::SetLocalDescription(
1926 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001927 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001928 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001929
Steve Anton80dd7b52018-02-16 17:08:42 -08001930 // The SetLocalDescription contract is that we take ownership of the session
1931 // description regardless of the outcome, so wrap it in a unique_ptr right
1932 // away. Ideally, SetLocalDescription's signature will be changed to take the
1933 // description as a unique_ptr argument to formalize this agreement.
1934 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1935
nisse7ce109a2017-01-31 00:57:56 -08001936 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 return;
1939 }
Steve Anton8a006912017-12-04 15:25:56 -08001940
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001942 PostSetSessionDescriptionFailure(
1943 observer,
1944 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 return;
1946 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001947
Steve Anton80dd7b52018-02-16 17:08:42 -08001948 // If a session error has occurred the PeerConnection is in a possibly
1949 // inconsistent state so fail right away.
1950 if (session_error() != SessionError::kNone) {
1951 std::string error_message = GetSessionErrorMsg();
1952 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001953 PostSetSessionDescriptionFailure(
1954 observer,
1955 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001956 return;
1957 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001958
Steve Anton80dd7b52018-02-16 17:08:42 -08001959 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1960 if (!error.ok()) {
1961 std::string error_message = GetSetDescriptionErrorMessage(
1962 cricket::CS_LOCAL, desc->GetType(), error);
1963 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001964 PostSetSessionDescriptionFailure(
1965 observer,
1966 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001967 return;
1968 }
1969
1970 // Grab the description type before moving ownership to ApplyLocalDescription,
1971 // which may destroy it before returning.
1972 const SdpType type = desc->GetType();
1973
1974 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001975 // |desc| may be destroyed at this point.
1976
1977 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001978 // If ApplyLocalDescription fails, the PeerConnection could be in an
1979 // inconsistent state, so act conservatively here and set the session error
1980 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1981 SetSessionError(SessionError::kContent, error.message());
1982 std::string error_message =
1983 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1984 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001985 PostSetSessionDescriptionFailure(
1986 observer,
1987 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001988 return;
1989 }
Steve Anton8a006912017-12-04 15:25:56 -08001990 RTC_DCHECK(local_description());
1991
1992 PostSetSessionDescriptionSuccess(observer);
1993
Steve Anton8a006912017-12-04 15:25:56 -08001994 // MaybeStartGathering needs to be called after posting
1995 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1996 // before signaling that SetLocalDescription completed.
1997 transport_controller_->MaybeStartGathering();
1998
Steve Antona3a92c22017-12-07 10:27:41 -08001999 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002000 // TODO(deadbeef): We already had to hop to the network thread for
2001 // MaybeStartGathering...
2002 network_thread()->Invoke<void>(
2003 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2004 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002005 // Make UMA notes about what was agreed to.
2006 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002007 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002008 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002009}
2010
2011RTCError PeerConnection::ApplyLocalDescription(
2012 std::unique_ptr<SessionDescriptionInterface> desc) {
2013 RTC_DCHECK_RUN_ON(signaling_thread());
2014 RTC_DCHECK(desc);
2015
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016 // Update stats here so that we have the most recent stats for tracks and
2017 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002018 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002019
Steve Antondcc3c022017-12-22 16:02:54 -08002020 // Take a reference to the old local description since it's used below to
2021 // compare against the new local description. When setting the new local
2022 // description, grab ownership of the replaced session description in case it
2023 // is the same as |old_local_description|, to keep it alive for the duration
2024 // of the method.
2025 const SessionDescriptionInterface* old_local_description =
2026 local_description();
2027 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002028 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002029 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002030 replaced_local_description = pending_local_description_
2031 ? std::move(pending_local_description_)
2032 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002033 current_local_description_ = std::move(desc);
2034 pending_local_description_ = nullptr;
2035 current_remote_description_ = std::move(pending_remote_description_);
2036 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002037 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002038 pending_local_description_ = std::move(desc);
2039 }
2040 // The session description to apply now must be accessed by
2041 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002042 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002043
Zhi Huange830e682018-03-30 10:48:35 -07002044 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2045 if (!error.ok()) {
2046 return error;
2047 }
2048
Steve Antondcc3c022017-12-22 16:02:54 -08002049 if (IsUnifiedPlan()) {
2050 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002051 cricket::CS_LOCAL, *local_description(), old_local_description,
2052 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002053 if (!error.ok()) {
2054 return error;
2055 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002056 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2057 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002058 for (auto transceiver : transceivers_) {
2059 const ContentInfo* content =
2060 FindMediaSectionForTransceiver(transceiver, local_description());
2061 if (!content) {
2062 continue;
2063 }
2064 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002065 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2066 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002067 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002068 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2069 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2070 // "recvonly", process the removal of a remote track for the media
2071 // description, given transceiver, removeList, and muteTracks.
2072 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2073 (transceiver->internal()->fired_direction() &&
2074 RtpTransceiverDirectionHasRecv(
2075 *transceiver->internal()->fired_direction()))) {
2076 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2077 &removed_streams);
2078 }
2079 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2080 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002081 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002082 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002083 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002084 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002085 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002086 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002087 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002088 }
2089 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002090 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002091 }
2092 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002093 // Media channels will be created only when offer is set. These may use new
2094 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002095 if (type == SdpType::kOffer) {
2096 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2097 // description is applied. Restore back to old description.
2098 RTCError error = CreateChannels(*local_description()->description());
2099 if (!error.ok()) {
2100 return error;
2101 }
2102 }
Steve Antondcc3c022017-12-22 16:02:54 -08002103 // Remove unused channels if MediaContentDescription is rejected.
2104 RemoveUnusedChannels(local_description()->description());
2105 }
Steve Anton8a006912017-12-04 15:25:56 -08002106
Zhi Huange830e682018-03-30 10:48:35 -07002107 error = UpdateSessionState(type, cricket::CS_LOCAL,
2108 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002109 if (!error.ok()) {
2110 return error;
2111 }
Steve Antondcc3c022017-12-22 16:02:54 -08002112
Steve Anton8a006912017-12-04 15:25:56 -08002113 if (remote_description()) {
2114 // Now that we have a local description, we can push down remote candidates.
2115 UseCandidatesInSessionDescription(remote_description());
2116 }
2117
2118 pending_ice_restarts_.clear();
2119 if (session_error() != SessionError::kNone) {
2120 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2121 }
2122
deadbeefab9b2d12015-10-14 11:33:11 -07002123 // If setting the description decided our SSL role, allocate any necessary
2124 // SCTP sids.
2125 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002126 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002127 AllocateSctpSids(role);
2128 }
2129
Steve Antond3679212018-01-17 17:41:02 -08002130 if (IsUnifiedPlan()) {
2131 for (auto transceiver : transceivers_) {
2132 const ContentInfo* content =
2133 FindMediaSectionForTransceiver(transceiver, local_description());
2134 if (!content) {
2135 continue;
2136 }
Steve Anton74255ff2018-01-24 18:32:57 -08002137 const auto& streams = content->media_description()->streams();
2138 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002139 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002140 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002141 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002142 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002143 } else {
2144 // 0 is a special value meaning "this sender has no associated send
2145 // stream". Need to call this so the sender won't attempt to configure
2146 // a no longer existing stream and run into DCHECKs in the lower
2147 // layers.
2148 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002149 }
2150 }
2151 } else {
2152 // Plan B semantics.
2153
Steve Antondcc3c022017-12-22 16:02:54 -08002154 // Update state and SSRC of local MediaStreams and DataChannels based on the
2155 // local session description.
2156 const cricket::ContentInfo* audio_content =
2157 GetFirstAudioContent(local_description()->description());
2158 if (audio_content) {
2159 if (audio_content->rejected) {
2160 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2161 } else {
2162 const cricket::AudioContentDescription* audio_desc =
2163 audio_content->media_description()->as_audio();
2164 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2165 }
deadbeeffaac4972015-11-12 15:33:07 -08002166 }
deadbeefab9b2d12015-10-14 11:33:11 -07002167
Steve Antondcc3c022017-12-22 16:02:54 -08002168 const cricket::ContentInfo* video_content =
2169 GetFirstVideoContent(local_description()->description());
2170 if (video_content) {
2171 if (video_content->rejected) {
2172 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2173 } else {
2174 const cricket::VideoContentDescription* video_desc =
2175 video_content->media_description()->as_video();
2176 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2177 }
deadbeeffaac4972015-11-12 15:33:07 -08002178 }
deadbeefab9b2d12015-10-14 11:33:11 -07002179 }
2180
2181 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002182 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002183 if (data_content) {
2184 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002185 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002186 if (rtc::starts_with(data_desc->protocol().data(),
2187 cricket::kMediaProtocolRtpPrefix)) {
2188 UpdateLocalRtpDataChannels(data_desc->streams());
2189 }
2190 }
2191
Steve Anton8a006912017-12-04 15:25:56 -08002192 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193}
2194
2195void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002196 SetSessionDescriptionObserver* observer,
2197 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002198 SetRemoteDescription(
2199 std::unique_ptr<SessionDescriptionInterface>(desc),
2200 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2201 new SetRemoteDescriptionObserverAdapter(this, observer)));
2202}
2203
2204void PeerConnection::SetRemoteDescription(
2205 std::unique_ptr<SessionDescriptionInterface> desc,
2206 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002207 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002208
nisse7ce109a2017-01-31 00:57:56 -08002209 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002210 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 return;
2212 }
Steve Anton8a006912017-12-04 15:25:56 -08002213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002215 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002216 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 return;
2218 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002219
Steve Anton80dd7b52018-02-16 17:08:42 -08002220 // If a session error has occurred the PeerConnection is in a possibly
2221 // inconsistent state so fail right away.
2222 if (session_error() != SessionError::kNone) {
2223 std::string error_message = GetSessionErrorMsg();
2224 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2225 observer->OnSetRemoteDescriptionComplete(
2226 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2227 return;
2228 }
Steve Anton71439a62018-02-15 11:53:06 -08002229
Steve Antonba42e992018-04-09 14:10:01 -07002230 if (desc->GetType() == SdpType::kOffer) {
2231 // Report to UMA the format of the received offer.
2232 ReportSdpFormatReceived(*desc);
2233 }
2234
Steve Anton80dd7b52018-02-16 17:08:42 -08002235 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002236 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002237 std::string error_message = GetSetDescriptionErrorMessage(
2238 cricket::CS_REMOTE, desc->GetType(), error);
2239 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002240 observer->OnSetRemoteDescriptionComplete(
2241 RTCError(error.type(), std::move(error_message)));
2242 return;
2243 }
Steve Anton71439a62018-02-15 11:53:06 -08002244
Steve Anton80dd7b52018-02-16 17:08:42 -08002245 // Grab the description type before moving ownership to
2246 // ApplyRemoteDescription, which may destroy it before returning.
2247 const SdpType type = desc->GetType();
2248
2249 error = ApplyRemoteDescription(std::move(desc));
2250 // |desc| may be destroyed at this point.
2251
2252 if (!error.ok()) {
2253 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2254 // inconsistent state, so act conservatively here and set the session error
2255 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2256 SetSessionError(SessionError::kContent, error.message());
2257 std::string error_message =
2258 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2259 RTC_LOG(LS_ERROR) << error_message;
2260 observer->OnSetRemoteDescriptionComplete(
2261 RTCError(error.type(), std::move(error_message)));
2262 return;
2263 }
2264 RTC_DCHECK(remote_description());
2265
2266 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002267 // TODO(deadbeef): We already had to hop to the network thread for
2268 // MaybeStartGathering...
2269 network_thread()->Invoke<void>(
2270 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2271 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002272 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002273 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002274 }
2275
2276 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002277 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002278}
2279
2280RTCError PeerConnection::ApplyRemoteDescription(
2281 std::unique_ptr<SessionDescriptionInterface> desc) {
2282 RTC_DCHECK_RUN_ON(signaling_thread());
2283 RTC_DCHECK(desc);
2284
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285 // Update stats here so that we have the most recent stats for tracks and
2286 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002287 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002288
Steve Antondcc3c022017-12-22 16:02:54 -08002289 // Take a reference to the old remote description since it's used below to
2290 // compare against the new remote description. When setting the new remote
2291 // description, grab ownership of the replaced session description in case it
2292 // is the same as |old_remote_description|, to keep it alive for the duration
2293 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002294 const SessionDescriptionInterface* old_remote_description =
2295 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002296 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002297 SdpType type = desc->GetType();
2298 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002299 replaced_remote_description = pending_remote_description_
2300 ? std::move(pending_remote_description_)
2301 : std::move(current_remote_description_);
2302 current_remote_description_ = std::move(desc);
2303 pending_remote_description_ = nullptr;
2304 current_local_description_ = std::move(pending_local_description_);
2305 } else {
2306 replaced_remote_description = std::move(pending_remote_description_);
2307 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 }
Steve Anton8a006912017-12-04 15:25:56 -08002309 // The session description to apply now must be accessed by
2310 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002311 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312
Zhi Huange830e682018-03-30 10:48:35 -07002313 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2314 if (!error.ok()) {
2315 return error;
2316 }
Steve Anton8a006912017-12-04 15:25:56 -08002317 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002318 if (IsUnifiedPlan()) {
2319 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002320 cricket::CS_REMOTE, *remote_description(), local_description(),
2321 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002322 if (!error.ok()) {
2323 return error;
2324 }
Steve Antondcc3c022017-12-22 16:02:54 -08002325 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002326 // Media channels will be created only when offer is set. These may use new
2327 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002328 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002329 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002330 // description is applied. Restore back to old description.
2331 RTCError error = CreateChannels(*remote_description()->description());
2332 if (!error.ok()) {
2333 return error;
2334 }
2335 }
Steve Antondcc3c022017-12-22 16:02:54 -08002336 // Remove unused channels if MediaContentDescription is rejected.
2337 RemoveUnusedChannels(remote_description()->description());
2338 }
Steve Anton8a006912017-12-04 15:25:56 -08002339
Zhi Huange830e682018-03-30 10:48:35 -07002340 // NOTE: Candidates allocation will be initiated only when
2341 // SetLocalDescription is called.
2342 error = UpdateSessionState(type, cricket::CS_REMOTE,
2343 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002344 if (!error.ok()) {
2345 return error;
2346 }
2347
2348 if (local_description() &&
2349 !UseCandidatesInSessionDescription(remote_description())) {
2350 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2351 }
2352
2353 if (old_remote_description) {
2354 for (const cricket::ContentInfo& content :
2355 old_remote_description->description()->contents()) {
2356 // Check if this new SessionDescription contains new ICE ufrag and
2357 // password that indicates the remote peer requests an ICE restart.
2358 // TODO(deadbeef): When we start storing both the current and pending
2359 // remote description, this should reset pending_ice_restarts and compare
2360 // against the current description.
2361 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2362 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002363 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002364 pending_ice_restarts_.insert(content.name);
2365 }
2366 } else {
2367 // We retain all received candidates only if ICE is not restarted.
2368 // When ICE is restarted, all previous candidates belong to an old
2369 // generation and should not be kept.
2370 // TODO(deadbeef): This goes against the W3C spec which says the remote
2371 // description should only contain candidates from the last set remote
2372 // description plus any candidates added since then. We should remove
2373 // this once we're sure it won't break anything.
2374 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2375 old_remote_description, content.name, mutable_remote_description());
2376 }
2377 }
2378 }
2379
2380 if (session_error() != SessionError::kNone) {
2381 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2382 }
2383
2384 // Set the the ICE connection state to connecting since the connection may
2385 // become writable with peer reflexive candidates before any remote candidate
2386 // is signaled.
2387 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2388 // is to have a new signal the indicates a change in checking state from the
2389 // transport and expose a new checking() member from transport that can be
2390 // read to determine the current checking state. The existing SignalConnecting
2391 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002392 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002393 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002394 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2395 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2396 }
2397
deadbeefab9b2d12015-10-14 11:33:11 -07002398 // If setting the description decided our SSL role, allocate any necessary
2399 // SCTP sids.
2400 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002401 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002402 AllocateSctpSids(role);
2403 }
2404
Steve Antondcc3c022017-12-22 16:02:54 -08002405 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002406 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002407 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002408 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002409 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002410 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002411 for (auto transceiver : transceivers_) {
2412 const ContentInfo* content =
2413 FindMediaSectionForTransceiver(transceiver, remote_description());
2414 if (!content) {
2415 continue;
2416 }
2417 const MediaContentDescription* media_desc = content->media_description();
2418 RtpTransceiverDirection local_direction =
2419 RtpTransceiverDirectionReversed(media_desc->direction());
2420 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2421 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2422 // transceiver's current direction is neither sendrecv nor recvonly,
2423 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002424 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002425 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002426 // The remote description has signaled the stream IDs.
2427 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002428 }
Steve Antondcc3c022017-12-22 16:02:54 -08002429 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002430 (!transceiver->fired_direction() ||
2431 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002432 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002433 << content->name << " (added to "
2434 << GetStreamIdsString(stream_ids) << ").";
2435
2436 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2437 for (const std::string& stream_id : stream_ids) {
2438 rtc::scoped_refptr<MediaStreamInterface> stream =
2439 remote_streams_->find(stream_id);
2440 if (!stream) {
2441 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2442 MediaStream::Create(stream_id));
2443 remote_streams_->AddStream(stream);
2444 added_streams.push_back(stream);
2445 }
2446 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002447 }
Steve Anton3172c032018-05-03 15:30:18 -07002448 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002449 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2450 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002451 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002452 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002453 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002454 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2455 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2456 // removal of a remote track for the media description, given transceiver,
2457 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002458 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002459 (transceiver->fired_direction() &&
2460 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2461 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2462 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002463 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002464 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2465 transceiver->internal()->set_fired_direction(local_direction);
2466 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2467 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002468 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002469 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2470 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002471 transceiver->internal()->set_current_direction(local_direction);
2472 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002473 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2474 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002475 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002476 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2477 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002478 transceiver->Stop();
2479 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002480 if (!content->rejected &&
2481 RtpTransceiverDirectionHasRecv(local_direction)) {
2482 // Set ssrc to 0 in the case of an unsignalled ssrc.
2483 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002484 if (!media_desc->streams().empty() &&
2485 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002486 ssrc = media_desc->streams()[0].first_ssrc();
2487 }
2488 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002489 }
Steve Antondcc3c022017-12-22 16:02:54 -08002490 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002491 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002492 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002493 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002494 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002495 observer->OnTrack(transceiver);
2496 observer->OnAddTrack(transceiver->receiver(),
2497 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002498 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002499 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002500 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002501 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002502 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002503 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002504 }
2505 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002506 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002507 }
Steve Antondcc3c022017-12-22 16:02:54 -08002508 }
2509
Henrik Boströmfdb92012017-11-09 19:55:44 +01002510 const cricket::ContentInfo* audio_content =
2511 GetFirstAudioContent(remote_description()->description());
2512 const cricket::ContentInfo* video_content =
2513 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002514 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002515 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002516 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002517 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002518 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002519 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002520
2521 // Check if the descriptions include streams, just in case the peer supports
2522 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002523 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002524 (audio_desc && !audio_desc->streams().empty()) ||
2525 (video_desc && !video_desc->streams().empty())) {
2526 remote_peer_supports_msid_ = true;
2527 }
deadbeefab9b2d12015-10-14 11:33:11 -07002528
2529 // We wait to signal new streams until we finish processing the description,
2530 // since only at that point will new streams have all their tracks.
2531 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2532
Steve Antondcc3c022017-12-22 16:02:54 -08002533 if (!IsUnifiedPlan()) {
2534 // TODO(steveanton): When removing RTP senders/receivers in response to a
2535 // rejected media section, there is some cleanup logic that expects the
2536 // voice/ video channel to still be set. But in this method the voice/video
2537 // channel would have been destroyed by the SetRemoteDescription caller
2538 // above so the cleanup that relies on them fails to run. The RemoveSenders
2539 // calls should be moved to right before the DestroyChannel calls to fix
2540 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002541
Steve Antondcc3c022017-12-22 16:02:54 -08002542 // Find all audio rtp streams and create corresponding remote AudioTracks
2543 // and MediaStreams.
2544 if (audio_content) {
2545 if (audio_content->rejected) {
2546 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2547 } else {
2548 bool default_audio_track_needed =
2549 !remote_peer_supports_msid_ &&
2550 RtpTransceiverDirectionHasSend(audio_desc->direction());
2551 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2552 default_audio_track_needed, audio_desc->type(),
2553 new_streams);
2554 }
deadbeeffaac4972015-11-12 15:33:07 -08002555 }
deadbeefab9b2d12015-10-14 11:33:11 -07002556
Steve Antondcc3c022017-12-22 16:02:54 -08002557 // Find all video rtp streams and create corresponding remote VideoTracks
2558 // and MediaStreams.
2559 if (video_content) {
2560 if (video_content->rejected) {
2561 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2562 } else {
2563 bool default_video_track_needed =
2564 !remote_peer_supports_msid_ &&
2565 RtpTransceiverDirectionHasSend(video_desc->direction());
2566 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2567 default_video_track_needed, video_desc->type(),
2568 new_streams);
2569 }
deadbeeffaac4972015-11-12 15:33:07 -08002570 }
deadbeefab9b2d12015-10-14 11:33:11 -07002571
Steve Antondcc3c022017-12-22 16:02:54 -08002572 // Update the DataChannels with the information from the remote peer.
2573 if (data_desc) {
2574 if (rtc::starts_with(data_desc->protocol().data(),
2575 cricket::kMediaProtocolRtpPrefix)) {
2576 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2577 }
deadbeefab9b2d12015-10-14 11:33:11 -07002578 }
deadbeefab9b2d12015-10-14 11:33:11 -07002579
Steve Antondcc3c022017-12-22 16:02:54 -08002580 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002581 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002582 for (size_t i = 0; i < new_streams->count(); ++i) {
2583 MediaStreamInterface* new_stream = new_streams->at(i);
2584 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002585 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002586 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2587 }
deadbeefab9b2d12015-10-14 11:33:11 -07002588
Steve Antondcc3c022017-12-22 16:02:54 -08002589 UpdateEndedRemoteMediaStreams();
2590 }
deadbeefab9b2d12015-10-14 11:33:11 -07002591
Steve Anton8a006912017-12-04 15:25:56 -08002592 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002593}
2594
Steve Anton0f5400a2018-07-17 14:25:36 -07002595void PeerConnection::ProcessRemovalOfRemoteTrack(
2596 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2597 transceiver,
2598 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2599 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2600 RTC_DCHECK(transceiver->mid());
2601 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2602 << *transceiver->mid();
2603 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2604 transceiver->internal()->receiver_internal()->streams();
2605 // This will remove the remote track from the streams.
2606 transceiver->internal()->receiver_internal()->set_stream_ids({});
2607 remove_list->push_back(transceiver);
2608 // Remove any streams that no longer have tracks.
2609 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2610 // of streams, see if the stream was removed by checking if this was the
2611 // last receiver with that stream ID.
2612 for (auto stream : media_streams) {
2613 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2614 remote_streams_->RemoveStream(stream);
2615 removed_streams->push_back(stream);
2616 }
2617 }
2618}
2619
Steve Antondcc3c022017-12-22 16:02:54 -08002620RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2621 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002622 const SessionDescriptionInterface& new_session,
2623 const SessionDescriptionInterface* old_local_description,
2624 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002625 RTC_DCHECK(IsUnifiedPlan());
2626
Steve Anton7464fca2018-01-19 11:10:37 -08002627 const cricket::ContentGroup* bundle_group = nullptr;
2628 if (new_session.GetType() == SdpType::kOffer) {
2629 auto bundle_group_or_error =
2630 GetEarlyBundleGroup(*new_session.description());
2631 if (!bundle_group_or_error.ok()) {
2632 return bundle_group_or_error.MoveError();
2633 }
2634 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002635 }
Steve Antondcc3c022017-12-22 16:02:54 -08002636
Steve Antondcc3c022017-12-22 16:02:54 -08002637 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002638 for (size_t i = 0; i < new_contents.size(); ++i) {
2639 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002640 cricket::MediaType media_type = new_content.media_description()->type();
2641 seen_mids_.insert(new_content.name);
2642 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2643 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002644 const cricket::ContentInfo* old_local_content = nullptr;
2645 if (old_local_description &&
2646 i < old_local_description->description()->contents().size()) {
2647 old_local_content =
2648 &old_local_description->description()->contents()[i];
2649 }
2650 const cricket::ContentInfo* old_remote_content = nullptr;
2651 if (old_remote_description &&
2652 i < old_remote_description->description()->contents().size()) {
2653 old_remote_content =
2654 &old_remote_description->description()->contents()[i];
2655 }
Steve Antondcc3c022017-12-22 16:02:54 -08002656 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002657 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2658 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002659 if (!transceiver_or_error.ok()) {
2660 return transceiver_or_error.MoveError();
2661 }
2662 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002663 RTCError error =
2664 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2665 if (!error.ok()) {
2666 return error;
2667 }
2668 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002669 if (GetDataMid() && new_content.name != *GetDataMid()) {
2670 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002671 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2672 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002673 continue;
2674 }
2675 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2676 if (!error.ok()) {
2677 return error;
2678 }
Steve Antondcc3c022017-12-22 16:02:54 -08002679 } else {
2680 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2681 "Unknown section type.");
2682 }
2683 }
2684
2685 return RTCError::OK();
2686}
2687
2688RTCError PeerConnection::UpdateTransceiverChannel(
2689 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2690 transceiver,
2691 const cricket::ContentInfo& content,
2692 const cricket::ContentGroup* bundle_group) {
2693 RTC_DCHECK(IsUnifiedPlan());
2694 RTC_DCHECK(transceiver);
2695 cricket::BaseChannel* channel = transceiver->internal()->channel();
2696 if (content.rejected) {
2697 if (channel) {
2698 transceiver->internal()->SetChannel(nullptr);
2699 DestroyBaseChannel(channel);
2700 }
2701 } else {
2702 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002703 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002704 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002705 } else {
Steve Anton69470252018-02-09 11:43:08 -08002706 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002707 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002708 }
2709 if (!channel) {
2710 LOG_AND_RETURN_ERROR(
2711 RTCErrorType::INTERNAL_ERROR,
2712 "Failed to create channel for mid=" + content.name);
2713 }
2714 transceiver->internal()->SetChannel(channel);
2715 }
2716 }
2717 return RTCError::OK();
2718}
2719
Steve Antonfa2260d2017-12-28 16:38:23 -08002720RTCError PeerConnection::UpdateDataChannel(
2721 cricket::ContentSource source,
2722 const cricket::ContentInfo& content,
2723 const cricket::ContentGroup* bundle_group) {
2724 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002725 // If data channels are disabled, ignore this media section. CreateAnswer
2726 // will take care of rejecting it.
2727 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002728 }
2729 if (content.rejected) {
2730 DestroyDataChannel();
2731 } else {
2732 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002733 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002734 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2735 "Failed to create data channel.");
2736 }
2737 }
2738 if (source == cricket::CS_REMOTE) {
2739 const MediaContentDescription* data_desc = content.media_description();
2740 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2741 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2742 }
2743 }
2744 }
2745 return RTCError::OK();
2746}
2747
Steve Antondcc3c022017-12-22 16:02:54 -08002748RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2749PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002750 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002751 size_t mline_index,
2752 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002753 const ContentInfo* old_local_content,
2754 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002755 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002756 // If this is an offer then the m= section might be recycled. If the m=
2757 // section is being recycled (defined as: rejected in the current local or
2758 // remote description and not rejected in new description), dissociate the
2759 // currently associated RtpTransceiver by setting its mid property to null,
2760 // and discard the mapping between the transceiver and its m= section index.
2761 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2762 old_remote_content)) {
2763 // We want to dissociate the transceiver that has the rejected mid.
2764 const std::string& old_mid =
2765 (old_local_content && old_local_content->rejected)
2766 ? old_local_content->name
2767 : old_remote_content->name;
2768 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002769 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002770 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2771 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002772 old_transceiver->internal()->set_mid(absl::nullopt);
2773 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002774 }
2775 }
2776 const MediaContentDescription* media_desc = content.media_description();
2777 auto transceiver = GetAssociatedTransceiver(content.name);
2778 if (source == cricket::CS_LOCAL) {
2779 // Find the RtpTransceiver that corresponds to this m= section, using the
2780 // mapping between transceivers and m= section indices established when
2781 // creating the offer.
2782 if (!transceiver) {
2783 transceiver = GetTransceiverByMLineIndex(mline_index);
2784 }
2785 if (!transceiver) {
2786 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2787 "Unknown transceiver");
2788 }
2789 } else {
2790 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2791 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2792 // of the same type...
2793 if (!transceiver &&
2794 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2795 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2796 }
2797 // If no RtpTransceiver was found in the previous step, create one with a
2798 // recvonly direction.
2799 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002800 RTC_LOG(LS_INFO) << "Adding "
2801 << cricket::MediaTypeToString(media_desc->type())
2802 << " transceiver for MID=" << content.name
2803 << " at i=" << mline_index
2804 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002805 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002806 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002807 std::string receiver_id;
2808 if (!media_desc->streams().empty()) {
2809 receiver_id = media_desc->streams()[0].id;
2810 } else {
2811 receiver_id = rtc::CreateRandomUuid();
2812 }
2813 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002814 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002815 transceiver->internal()->set_direction(
2816 RtpTransceiverDirection::kRecvOnly);
2817 }
2818 }
2819 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002820 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002821 LOG_AND_RETURN_ERROR(
2822 RTCErrorType::INVALID_PARAMETER,
2823 "Transceiver type does not match media description type.");
2824 }
2825 // Associate the found or created RtpTransceiver with the m= section by
2826 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2827 // section, and establish a mapping between the transceiver and the index of
2828 // the m= section.
2829 transceiver->internal()->set_mid(content.name);
2830 transceiver->internal()->set_mline_index(mline_index);
2831 return std::move(transceiver);
2832}
2833
2834rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2835PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2836 RTC_DCHECK(IsUnifiedPlan());
2837 for (auto transceiver : transceivers_) {
2838 if (transceiver->mid() == mid) {
2839 return transceiver;
2840 }
2841 }
2842 return nullptr;
2843}
2844
2845rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2846PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2847 RTC_DCHECK(IsUnifiedPlan());
2848 for (auto transceiver : transceivers_) {
2849 if (transceiver->internal()->mline_index() == mline_index) {
2850 return transceiver;
2851 }
2852 }
2853 return nullptr;
2854}
2855
2856rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2857PeerConnection::FindAvailableTransceiverToReceive(
2858 cricket::MediaType media_type) const {
2859 RTC_DCHECK(IsUnifiedPlan());
2860 // From JSEP section 5.10 (Applying a Remote Description):
2861 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2862 // the same type that were added to the PeerConnection by addTrack and are not
2863 // associated with any m= section and are not stopped, find the first such
2864 // RtpTransceiver.
2865 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002866 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002867 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2868 !transceiver->stopped()) {
2869 return transceiver;
2870 }
2871 }
2872 return nullptr;
2873}
2874
Steve Antoned10bd92017-12-05 10:52:59 -08002875const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2876 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2877 transceiver,
2878 const SessionDescriptionInterface* sdesc) const {
2879 RTC_DCHECK(transceiver);
2880 RTC_DCHECK(sdesc);
2881 if (IsUnifiedPlan()) {
2882 if (!transceiver->internal()->mid()) {
2883 // This transceiver is not associated with a media section yet.
2884 return nullptr;
2885 }
2886 return sdesc->description()->GetContentByName(
2887 *transceiver->internal()->mid());
2888 } else {
2889 // Plan B only allows at most one audio and one video section, so use the
2890 // first media section of that type.
2891 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002892 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002893 }
2894}
2895
deadbeef46c73892016-11-16 19:42:04 -08002896PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2897 return configuration_;
2898}
2899
deadbeef293e9262017-01-11 12:28:30 -08002900bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2901 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002902 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002903 if (IsClosed()) {
2904 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2905 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2906 }
2907
Qingsi Wanga2d60672018-04-11 16:57:45 -07002908 // According to JSEP, after setLocalDescription, changing the candidate pool
2909 // size is not allowed, and changing the set of ICE servers will not result
2910 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002911 if (local_description() && configuration.ice_candidate_pool_size !=
2912 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002913 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2914 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002915 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002916 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002917
deadbeef293e9262017-01-11 12:28:30 -08002918 // The simplest (and most future-compatible) way to tell if the config was
2919 // modified in an invalid way is to copy each property we do support
2920 // modifying, then use operator==. There are far more properties we don't
2921 // support modifying than those we do, and more could be added.
2922 RTCConfiguration modified_config = configuration_;
2923 modified_config.servers = configuration.servers;
2924 modified_config.type = configuration.type;
2925 modified_config.ice_candidate_pool_size =
2926 configuration.ice_candidate_pool_size;
2927 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002928 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002929 modified_config.ice_check_interval_strong_connectivity =
2930 configuration.ice_check_interval_strong_connectivity;
2931 modified_config.ice_check_interval_weak_connectivity =
2932 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002933 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2934 modified_config.ice_unwritable_min_checks =
2935 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002936 modified_config.stun_candidate_keepalive_interval =
2937 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002938 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002939 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002940 modified_config.active_reset_srtp_params =
2941 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002942 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002943 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002944 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2945 }
2946
Steve Anton038834f2017-07-14 15:59:59 -07002947 // Validate the modified configuration.
2948 RTCError validate_error = ValidateConfiguration(modified_config);
2949 if (!validate_error.ok()) {
2950 return SafeSetError(std::move(validate_error), error);
2951 }
2952
deadbeef293e9262017-01-11 12:28:30 -08002953 // Note that this isn't possible through chromium, since it's an unsigned
2954 // short in WebIDL.
2955 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002956 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002957 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2958 }
2959
2960 // Parse ICE servers before hopping to network thread.
2961 cricket::ServerAddresses stun_servers;
2962 std::vector<cricket::RelayServerConfig> turn_servers;
2963 RTCErrorType parse_error =
2964 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2965 if (parse_error != RTCErrorType::NONE) {
2966 return SafeSetError(parse_error, error);
2967 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002968 // Note if STUN or TURN servers were supplied.
2969 if (!stun_servers.empty()) {
2970 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2971 }
2972 if (!turn_servers.empty()) {
2973 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2974 }
deadbeef293e9262017-01-11 12:28:30 -08002975
2976 // In theory this shouldn't fail.
2977 if (!network_thread()->Invoke<bool>(
2978 RTC_FROM_HERE,
2979 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2980 stun_servers, turn_servers, modified_config.type,
2981 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002982 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002983 modified_config.turn_customizer,
2984 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002985 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002986 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2987 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002988
deadbeefd1a38b52016-12-10 13:15:33 -08002989 // As described in JSEP, calling setConfiguration with new ICE servers or
2990 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2991 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002992 if (modified_config.servers != configuration_.servers ||
2993 modified_config.type != configuration_.type ||
2994 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002995 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002996 }
skvladd1f5fda2017-02-03 16:54:05 -08002997
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002998 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002999
Zhi Huangb57e1692018-06-12 11:41:11 -07003000 if (configuration_.active_reset_srtp_params !=
3001 modified_config.active_reset_srtp_params) {
3002 transport_controller_->SetActiveResetSrtpParams(
3003 modified_config.active_reset_srtp_params);
3004 }
3005
deadbeef293e9262017-01-11 12:28:30 -08003006 configuration_ = modified_config;
3007 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003008}
3009
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003010bool PeerConnection::AddIceCandidate(
3011 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003012 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003013 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003015 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003016 return false;
3017 }
Steve Antond25da372017-11-06 14:50:29 -08003018
3019 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003020 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003021 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003022 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003023 return false;
3024 }
3025
3026 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003027 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003028 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003029 return false;
3030 }
3031
3032 bool valid = false;
3033 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3034 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003035 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003036 return false;
3037 }
3038
3039 // Add this candidate to the remote session description.
3040 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003041 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003042 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003043 return false;
3044 }
3045
3046 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003047 bool result = UseCandidate(ice_candidate);
3048 if (result) {
3049 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3050 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3051 } else {
3052 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3053 }
3054 return result;
Steve Antond25da372017-11-06 14:50:29 -08003055 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003056 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003057 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003058 return true;
3059 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060}
3061
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003062bool PeerConnection::RemoveIceCandidates(
3063 const std::vector<cricket::Candidate>& candidates) {
3064 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003065 if (IsClosed()) {
3066 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3067 return false;
3068 }
3069
Steve Antond25da372017-11-06 14:50:29 -08003070 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003071 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3072 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003073 return false;
3074 }
3075
3076 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003077 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003078 return false;
3079 }
3080
3081 size_t number_removed =
3082 mutable_remote_description()->RemoveCandidates(candidates);
3083 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003084 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003085 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003086 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003087 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003088 }
3089
3090 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003091 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3092 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003093 RTC_LOG(LS_ERROR)
3094 << "RemoveIceCandidates: Error when removing remote candidates: "
3095 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003096 }
3097 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003098}
3099
Niels Möller0c4f7be2018-05-07 14:01:37 +02003100RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003101 if (!worker_thread()->IsCurrent()) {
3102 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003103 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003104 }
3105
Niels Möller0c4f7be2018-05-07 14:01:37 +02003106 const bool has_min = bitrate.min_bitrate_bps.has_value();
3107 const bool has_start = bitrate.start_bitrate_bps.has_value();
3108 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003109 if (has_min && *bitrate.min_bitrate_bps < 0) {
3110 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3111 "min_bitrate_bps <= 0");
3112 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003113 if (has_start) {
3114 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003116 "start_bitrate_bps < min_bitrate_bps");
3117 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3119 "curent_bitrate_bps < 0");
3120 }
3121 }
3122 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003123 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003124 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003125 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003126 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3127 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3128 "max_bitrate_bps < min_bitrate_bps");
3129 } else if (*bitrate.max_bitrate_bps < 0) {
3130 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3131 "max_bitrate_bps < 0");
3132 }
3133 }
3134
zstein4b979802017-06-02 14:37:37 -07003135 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003136 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003137
3138 return RTCError::OK();
3139}
3140
Alex Narest78609d52017-10-20 10:37:47 +02003141void PeerConnection::SetBitrateAllocationStrategy(
3142 std::unique_ptr<rtc::BitrateAllocationStrategy>
3143 bitrate_allocation_strategy) {
3144 rtc::Thread* worker_thread = factory_->worker_thread();
3145 if (!worker_thread->IsCurrent()) {
3146 rtc::BitrateAllocationStrategy* strategy_raw =
3147 bitrate_allocation_strategy.release();
3148 auto functor = [this, strategy_raw]() {
3149 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003150 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003151 };
3152 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3153 return;
3154 }
3155 RTC_DCHECK(call_.get());
3156 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3157}
3158
henrika5f6bf242017-11-01 11:06:56 +01003159void PeerConnection::SetAudioPlayout(bool playout) {
3160 if (!worker_thread()->IsCurrent()) {
3161 worker_thread()->Invoke<void>(
3162 RTC_FROM_HERE,
3163 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3164 return;
3165 }
3166 auto audio_state =
3167 factory_->channel_manager()->media_engine()->GetAudioState();
3168 audio_state->SetPlayout(playout);
3169}
3170
3171void PeerConnection::SetAudioRecording(bool recording) {
3172 if (!worker_thread()->IsCurrent()) {
3173 worker_thread()->Invoke<void>(
3174 RTC_FROM_HERE,
3175 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3176 return;
3177 }
3178 auto audio_state =
3179 factory_->channel_manager()->media_engine()->GetAudioState();
3180 audio_state->SetRecording(recording);
3181}
3182
Steve Anton8c0f7a72017-10-03 10:03:10 -07003183std::unique_ptr<rtc::SSLCertificate>
3184PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003185 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3186 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003187 return nullptr;
3188 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003189 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003190}
3191
Zhi Huang70b820f2018-01-27 14:16:15 -08003192std::unique_ptr<rtc::SSLCertChain>
3193PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003194 auto audio_transceiver = GetFirstAudioTransceiver();
3195 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003196 return nullptr;
3197 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003198 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003199 audio_transceiver->internal()->channel()->transport_name());
3200}
3201
3202rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3203PeerConnection::GetFirstAudioTransceiver() const {
3204 for (auto transceiver : transceivers_) {
3205 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3206 return transceiver;
3207 }
3208 }
3209 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003210}
3211
ivoc14d5dbe2016-07-04 07:06:55 -07003212bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3213 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003214 // TODO(eladalon): It would be better to not allow negative values into PC.
3215 const size_t max_size = (max_size_bytes < 0)
3216 ? RtcEventLog::kUnlimitedOutput
3217 : rtc::saturated_cast<size_t>(max_size_bytes);
3218 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003219 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003220 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003221}
3222
Bjorn Tereliusde939432017-11-20 17:38:14 +01003223bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3224 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003225 // TODO(eladalon): In C++14, this can be done with a lambda.
3226 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003227 bool operator()() {
3228 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3229 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003230 PeerConnection* const pc;
3231 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003232 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003233 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003234 return worker_thread()->Invoke<bool>(
3235 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003236}
3237
3238void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003239 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003240 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3241}
3242
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003244 return pending_local_description_ ? pending_local_description_.get()
3245 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246}
3247
3248const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003249 return pending_remote_description_ ? pending_remote_description_.get()
3250 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251}
3252
deadbeeffe4a8a42016-12-20 17:56:17 -08003253const SessionDescriptionInterface* PeerConnection::current_local_description()
3254 const {
Steve Anton75737c02017-11-06 10:37:17 -08003255 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003256}
3257
3258const SessionDescriptionInterface* PeerConnection::current_remote_description()
3259 const {
Steve Anton75737c02017-11-06 10:37:17 -08003260 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003261}
3262
3263const SessionDescriptionInterface* PeerConnection::pending_local_description()
3264 const {
Steve Anton75737c02017-11-06 10:37:17 -08003265 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003266}
3267
3268const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3269 const {
Steve Anton75737c02017-11-06 10:37:17 -08003270 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003271}
3272
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003274 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 // Update stats here so that we have the most recent stats for tracks and
3276 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003277 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278
Steve Anton75737c02017-11-06 10:37:17 -08003279 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003280 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003281
Steve Anton8af21862017-12-15 11:20:13 -08003282 for (auto transceiver : transceivers_) {
3283 transceiver->Stop();
3284 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003285
3286 // Ensure that all asynchronous stats requests are completed before destroying
3287 // the transport controller below.
3288 if (stats_collector_) {
3289 stats_collector_->WaitForPendingRequest();
3290 }
3291
3292 // Don't destroy BaseChannels until after stats has been cleaned up so that
3293 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003294 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003295
Qingsi Wang93a84392018-01-30 17:13:09 -08003296 // The event log is used in the transport controller, which must be outlived
3297 // by the former. CreateOffer by the peer connection is implemented
3298 // asynchronously and if the peer connection is closed without resetting the
3299 // WebRTC session description factory, the session description factory would
3300 // call the transport controller.
3301 webrtc_session_desc_factory_.reset();
3302 transport_controller_.reset();
3303
deadbeef42a42632017-03-10 15:18:00 -08003304 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003305 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3306 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003307
Steve Anton978b8762017-09-29 12:15:02 -07003308 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003309 call_.reset();
3310 // The event log must outlive call (and any other object that uses it).
3311 event_log_.reset();
3312 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003313 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003314 // The .h file says that observer can be discarded after close() returns.
3315 // Make sure this is true.
3316 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317}
3318
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003319void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3322 SetSessionDescriptionMsg* param =
3323 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3324 param->observer->OnSuccess();
3325 delete param;
3326 break;
3327 }
3328 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3329 SetSessionDescriptionMsg* param =
3330 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003331 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332 delete param;
3333 break;
3334 }
deadbeefab9b2d12015-10-14 11:33:11 -07003335 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3336 CreateSessionDescriptionMsg* param =
3337 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003338 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003339 delete param;
3340 break;
3341 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342 case MSG_GETSTATS: {
3343 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003344 StatsReports reports;
3345 stats_->GetStats(param->track, &reports);
3346 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347 delete param;
3348 break;
3349 }
deadbeefbd292462015-12-14 18:15:29 -08003350 case MSG_FREE_DATACHANNELS: {
3351 sctp_data_channels_to_free_.clear();
3352 break;
3353 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003354 case MSG_REPORT_USAGE_PATTERN: {
3355 ReportUsagePattern();
3356 break;
3357 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003359 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003360 break;
3361 }
3362}
3363
Steve Antonafb0bb72018-02-20 11:35:37 -08003364cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3365 RTC_DCHECK(!IsUnifiedPlan());
3366 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3367 GetAudioTransceiver()->internal()->channel());
3368 if (voice_channel) {
3369 return voice_channel->media_channel();
3370 } else {
3371 return nullptr;
3372 }
3373}
3374
3375cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3376 RTC_DCHECK(!IsUnifiedPlan());
3377 auto* video_channel = static_cast<cricket::VideoChannel*>(
3378 GetVideoTransceiver()->internal()->channel());
3379 if (video_channel) {
3380 return video_channel->media_channel();
3381 } else {
3382 return nullptr;
3383 }
3384}
3385
Steve Anton4171afb2017-11-20 10:20:22 -08003386void PeerConnection::CreateAudioReceiver(
3387 MediaStreamInterface* stream,
3388 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003389 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3390 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003391 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3392 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003393 auto* audio_receiver = new AudioRtpReceiver(
3394 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003395 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003396 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3397 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3398 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003399 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003400 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003401 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402}
3403
Steve Anton4171afb2017-11-20 10:20:22 -08003404void PeerConnection::CreateVideoReceiver(
3405 MediaStreamInterface* stream,
3406 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003407 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3408 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003409 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3410 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003411 auto* video_receiver = new VideoRtpReceiver(
3412 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003413 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003414 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3415 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3416 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003417 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003418 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003419 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003420}
3421
deadbeef70ab1a12015-09-28 16:53:55 -07003422// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3423// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003424rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003425 const RtpSenderInfo& remote_sender_info) {
3426 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3427 if (!receiver) {
3428 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3429 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003430 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003431 }
Steve Anton4171afb2017-11-20 10:20:22 -08003432 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3433 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3434 } else {
3435 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3436 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003437 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438}
3439
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003440void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3441 MediaStreamInterface* stream) {
3442 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003443 RTC_DCHECK(track);
3444 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003445 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003446 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 // We already have a sender for this track, so just change the stream_id
3448 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003449 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003450 return;
3451 }
3452
3453 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003454 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3455 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003456 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003457 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003458 // If the sender has already been configured in SDP, we call SetSsrc,
3459 // which will connect the sender to the underlying transport. This can
3460 // occur if a local session description that contains the ID of the sender
3461 // is set before AddStream is called. It can also occur if the local
3462 // session description is not changed and RemoveStream is called, and
3463 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003464 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003465 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003466 if (sender_info) {
3467 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468 }
3469}
3470
3471// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3472// indefinitely, when we have unified plan SDP.
3473void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3474 MediaStreamInterface* stream) {
3475 RTC_DCHECK(!IsClosed());
3476 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003477 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003478 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3479 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480 return;
3481 }
Steve Anton4171afb2017-11-20 10:20:22 -08003482 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003483}
3484
3485void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3486 MediaStreamInterface* stream) {
3487 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003488 RTC_DCHECK(track);
3489 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003490 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003491 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003492 // We already have a sender for this track, so just change the stream_id
3493 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003494 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003495 return;
3496 }
3497
3498 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003499 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3500 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003501 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003502 GetVideoTransceiver()->internal()->AddSender(new_sender);
3503 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003504 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003505 if (sender_info) {
3506 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003507 }
3508}
3509
3510void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3511 MediaStreamInterface* stream) {
3512 RTC_DCHECK(!IsClosed());
3513 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003514 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003515 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3516 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003517 return;
3518 }
Steve Anton4171afb2017-11-20 10:20:22 -08003519 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003520}
3521
Steve Antonba818672017-11-06 10:21:57 -08003522void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003523 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003524 if (ice_connection_state_ == new_state) {
3525 return;
3526 }
3527
deadbeefcbecd352015-09-23 11:50:27 -07003528 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003529 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003530 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003531 return;
3532 }
Steve Antonba818672017-11-06 10:21:57 -08003533
Mirko Bonadei675513b2017-11-09 11:09:25 +01003534 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3535 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003536 RTC_DCHECK(ice_connection_state_ !=
3537 PeerConnectionInterface::kIceConnectionClosed);
3538
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003540 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003541}
3542
3543void PeerConnection::OnIceGatheringChange(
3544 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003545 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003546 if (IsClosed()) {
3547 return;
3548 }
3549 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003550 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003551}
3552
jbauch81bf7b02017-03-25 08:31:12 -07003553void PeerConnection::OnIceCandidate(
3554 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003555 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003556 if (IsClosed()) {
3557 return;
3558 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003559 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003560 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3561 candidate->candidate().address().IsPrivateIP()) {
3562 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3563 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003564 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565}
3566
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003567void PeerConnection::OnIceCandidatesRemoved(
3568 const std::vector<cricket::Candidate>& candidates) {
3569 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003570 if (IsClosed()) {
3571 return;
3572 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003573 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003574}
3575
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003576void PeerConnection::ChangeSignalingState(
3577 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003578 RTC_DCHECK(signaling_thread()->IsCurrent());
3579 if (signaling_state_ == signaling_state) {
3580 return;
3581 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003582 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3583 << GetSignalingStateString(signaling_state_)
3584 << " New state: "
3585 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003586 signaling_state_ = signaling_state;
3587 if (signaling_state == kClosed) {
3588 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003589 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003590 if (ice_gathering_state_ != kIceGatheringComplete) {
3591 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003592 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003593 }
3594 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003595 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003596}
3597
deadbeefeb459812015-12-15 19:24:43 -08003598void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3599 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003600 if (IsClosed()) {
3601 return;
3602 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003603 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003604 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003605}
3606
deadbeefeb459812015-12-15 19:24:43 -08003607void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3608 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003609 if (IsClosed()) {
3610 return;
3611 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003612 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003613 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003614}
3615
3616void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3617 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003618 if (IsClosed()) {
3619 return;
3620 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003621 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003622 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003623}
3624
3625void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3626 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003627 if (IsClosed()) {
3628 return;
3629 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003630 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003631 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003632}
3633
Henrik Boström31638672017-11-23 17:48:32 +01003634void PeerConnection::PostSetSessionDescriptionSuccess(
3635 SetSessionDescriptionObserver* observer) {
3636 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3637 signaling_thread()->Post(RTC_FROM_HERE, this,
3638 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3639}
3640
deadbeefab9b2d12015-10-14 11:33:11 -07003641void PeerConnection::PostSetSessionDescriptionFailure(
3642 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003643 RTCError&& error) {
3644 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003645 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003646 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003647 signaling_thread()->Post(RTC_FROM_HERE, this,
3648 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003649}
3650
3651void PeerConnection::PostCreateSessionDescriptionFailure(
3652 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003653 RTCError error) {
3654 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003655 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003656 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003657 signaling_thread()->Post(RTC_FROM_HERE, this,
3658 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003659}
3660
zhihuang1c378ed2017-08-17 14:10:50 -07003661void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003662 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003663 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003664 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003665
Steve Antondcc3c022017-12-22 16:02:54 -08003666 if (IsUnifiedPlan()) {
3667 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3668 } else {
3669 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3670 }
3671
Steve Antonfa2260d2017-12-28 16:38:23 -08003672 // Intentionally unset the data channel type for RTP data channel with the
3673 // second condition. Otherwise the RTP data channels would be successfully
3674 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3675 // when building with chromium. We want to leave RTP data channels broken, so
3676 // people won't try to use them.
3677 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3678 session_options->data_channel_type = data_channel_type();
3679 }
3680
Steve Antondcc3c022017-12-22 16:02:54 -08003681 // Apply ICE restart flag and renomination flag.
3682 for (auto& options : session_options->media_description_options) {
3683 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3684 options.transport_options.enable_ice_renomination =
3685 configuration_.enable_ice_renomination;
3686 }
3687
3688 session_options->rtcp_cname = rtcp_cname_;
3689 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003690 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003691}
3692
3693void PeerConnection::GetOptionsForPlanBOffer(
3694 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3695 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003696 // Figure out transceiver directional preferences.
3697 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3698 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3699
3700 // By default, generate sendrecv/recvonly m= sections.
3701 bool recv_audio = true;
3702 bool recv_video = true;
3703
3704 // By default, only offer a new m= section if we have media to send with it.
3705 bool offer_new_audio_description = send_audio;
3706 bool offer_new_video_description = send_video;
3707 bool offer_new_data_description = HasDataChannels();
3708
3709 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003710 if (offer_answer_options.offer_to_receive_audio !=
3711 RTCOfferAnswerOptions::kUndefined) {
3712 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003713 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003714 offer_new_audio_description ||
3715 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003716 }
Steve Antondcc3c022017-12-22 16:02:54 -08003717 if (offer_answer_options.offer_to_receive_video !=
3718 RTCOfferAnswerOptions::kUndefined) {
3719 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003720 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003721 offer_new_video_description ||
3722 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003723 }
3724
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003725 absl::optional<size_t> audio_index;
3726 absl::optional<size_t> video_index;
3727 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003728 // If a current description exists, generate m= sections in the same order,
3729 // using the first audio/video/data section that appears and rejecting
3730 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003731 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003732 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003733 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003734 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3735 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3736 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003737 }
3738
zhihuang1c378ed2017-08-17 14:10:50 -07003739 // Add audio/video/data m= sections to the end if needed.
3740 if (!audio_index && offer_new_audio_description) {
3741 session_options->media_description_options.push_back(
3742 cricket::MediaDescriptionOptions(
3743 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003744 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3745 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003746 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003747 }
zhihuang1c378ed2017-08-17 14:10:50 -07003748 if (!video_index && offer_new_video_description) {
3749 session_options->media_description_options.push_back(
3750 cricket::MediaDescriptionOptions(
3751 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003752 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3753 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003754 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003755 }
zhihuang1c378ed2017-08-17 14:10:50 -07003756 if (!data_index && offer_new_data_description) {
3757 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003758 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003759 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003760 }
3761
3762 cricket::MediaDescriptionOptions* audio_media_description_options =
3763 !audio_index ? nullptr
3764 : &session_options->media_description_options[*audio_index];
3765 cricket::MediaDescriptionOptions* video_media_description_options =
3766 !video_index ? nullptr
3767 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003768
Steve Anton4171afb2017-11-20 10:20:22 -08003769 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003770 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003771}
3772
3773// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3774// and return a reference to it.
3775// Generated MIDs should be no more than 3 bytes long to take up less space in
3776// the RTP packet.
3777static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3778 RTC_DCHECK(used_mids);
3779 // We're boring: just generate MIDs 0, 1, 2, ...
3780 size_t i = 0;
3781 std::set<std::string>::iterator it;
3782 bool inserted;
3783 do {
3784 std::string mid = rtc::ToString(i++);
3785 auto insert_result = used_mids->insert(mid);
3786 it = insert_result.first;
3787 inserted = insert_result.second;
3788 } while (!inserted);
3789 return *it;
3790}
3791
3792static cricket::MediaDescriptionOptions
3793GetMediaDescriptionOptionsForTransceiver(
3794 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3795 transceiver,
3796 const std::string& mid) {
3797 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003798 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003799 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003800 // This behavior is specified in JSEP. The gist is that:
3801 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3802 // sendrecv.
3803 // 2. If the MSID is included, then it must be included in any subsequent
3804 // offer/answer exactly the same until the RtpTransceiver is stopped.
3805 if (!transceiver->stopped() &&
3806 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3807 transceiver->internal()->has_ever_been_used_to_send())) {
3808 cricket::SenderOptions sender_options;
3809 sender_options.track_id = transceiver->sender()->id();
3810 sender_options.stream_ids = transceiver->sender()->stream_ids();
3811 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3812 // set in the RTP parameters when the transceiver was added.
3813 sender_options.num_sim_layers = 1;
3814 media_description_options.sender_options.push_back(sender_options);
3815 }
Steve Antondcc3c022017-12-22 16:02:54 -08003816 return media_description_options;
3817}
3818
3819void PeerConnection::GetOptionsForUnifiedPlanOffer(
3820 const RTCOfferAnswerOptions& offer_answer_options,
3821 cricket::MediaSessionOptions* session_options) {
3822 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3823 // Offers) and 5.2.2 (Subsequent Offers).
3824 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3825 const ContentInfos& local_contents =
3826 (local_description() ? local_description()->description()->contents()
3827 : ContentInfos());
3828 const ContentInfos& remote_contents =
3829 (remote_description() ? remote_description()->description()->contents()
3830 : ContentInfos());
3831 // The mline indices that can be recycled. New transceivers should reuse these
3832 // slots first.
3833 std::queue<size_t> recycleable_mline_indices;
3834 // Track the MIDs used in previous offer/answer exchanges and the current
3835 // offer so that new, unique MIDs are generated.
3836 std::set<std::string> used_mids = seen_mids_;
3837 // First, go through each media section that exists in either the local or
3838 // remote description and generate a media section in this offer for the
3839 // associated transceiver. If a media section can be recycled, generate a
3840 // default, rejected media section here that can be later overwritten.
3841 for (size_t i = 0;
3842 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3843 // Either |local_content| or |remote_content| is non-null.
3844 const ContentInfo* local_content =
3845 (i < local_contents.size() ? &local_contents[i] : nullptr);
3846 const ContentInfo* remote_content =
3847 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3848 bool had_been_rejected = (local_content && local_content->rejected) ||
3849 (remote_content && remote_content->rejected);
3850 const std::string& mid =
3851 (local_content ? local_content->name : remote_content->name);
3852 cricket::MediaType media_type =
3853 (local_content ? local_content->media_description()->type()
3854 : remote_content->media_description()->type());
3855 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3856 media_type == cricket::MEDIA_TYPE_VIDEO) {
3857 auto transceiver = GetAssociatedTransceiver(mid);
3858 RTC_CHECK(transceiver);
3859 // A media section is considered eligible for recycling if it is marked as
3860 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003861 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003862 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003863 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3864 RtpTransceiverDirection::kInactive,
3865 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003866 recycleable_mline_indices.push(i);
3867 } else {
3868 session_options->media_description_options.push_back(
3869 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3870 // CreateOffer shouldn't really cause any state changes in
3871 // PeerConnection, but we need a way to match new transceivers to new
3872 // media sections in SetLocalDescription and JSEP specifies this is done
3873 // by recording the index of the media section generated for the
3874 // transceiver in the offer.
3875 transceiver->internal()->set_mline_index(i);
3876 }
3877 } else {
3878 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003879 RTC_CHECK(GetDataMid());
3880 if (had_been_rejected || mid != *GetDataMid()) {
3881 session_options->media_description_options.push_back(
3882 GetMediaDescriptionOptionsForRejectedData(mid));
3883 } else {
3884 session_options->media_description_options.push_back(
3885 GetMediaDescriptionOptionsForActiveData(mid));
3886 }
Steve Antondcc3c022017-12-22 16:02:54 -08003887 }
3888 }
3889 // Next, look for transceivers that are newly added (that is, are not stopped
3890 // and not associated). Reuse media sections marked as recyclable first,
3891 // otherwise append to the end of the offer. New media sections should be
3892 // added in the order they were added to the PeerConnection.
3893 for (auto transceiver : transceivers_) {
3894 if (transceiver->mid() || transceiver->stopped()) {
3895 continue;
3896 }
3897 size_t mline_index;
3898 if (!recycleable_mline_indices.empty()) {
3899 mline_index = recycleable_mline_indices.front();
3900 recycleable_mline_indices.pop();
3901 session_options->media_description_options[mline_index] =
3902 GetMediaDescriptionOptionsForTransceiver(transceiver,
3903 AllocateMid(&used_mids));
3904 } else {
3905 mline_index = session_options->media_description_options.size();
3906 session_options->media_description_options.push_back(
3907 GetMediaDescriptionOptionsForTransceiver(transceiver,
3908 AllocateMid(&used_mids)));
3909 }
3910 // See comment above for why CreateOffer changes the transceiver's state.
3911 transceiver->internal()->set_mline_index(mline_index);
3912 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003913 // Lastly, add a m-section if we have local data channels and an m section
3914 // does not already exist.
3915 if (!GetDataMid() && HasDataChannels()) {
3916 session_options->media_description_options.push_back(
3917 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3918 }
Steve Antondcc3c022017-12-22 16:02:54 -08003919}
3920
3921void PeerConnection::GetOptionsForAnswer(
3922 const RTCOfferAnswerOptions& offer_answer_options,
3923 cricket::MediaSessionOptions* session_options) {
3924 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3925
3926 if (IsUnifiedPlan()) {
3927 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3928 } else {
3929 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3930 }
3931
Steve Antonfa2260d2017-12-28 16:38:23 -08003932 // Intentionally unset the data channel type for RTP data channel. Otherwise
3933 // the RTP data channels would be successfully negotiated by default and the
3934 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3935 // We want to leave RTP data channels broken, so people won't try to use them.
3936 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3937 session_options->data_channel_type = data_channel_type();
3938 }
3939
Steve Antondcc3c022017-12-22 16:02:54 -08003940 // Apply ICE renomination flag.
3941 for (auto& options : session_options->media_description_options) {
3942 options.transport_options.enable_ice_renomination =
3943 configuration_.enable_ice_renomination;
3944 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003945
3946 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003947 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003948 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003949}
3950
Steve Antondcc3c022017-12-22 16:02:54 -08003951void PeerConnection::GetOptionsForPlanBAnswer(
3952 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003953 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003954 // Figure out transceiver directional preferences.
3955 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3956 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3957
3958 // By default, generate sendrecv/recvonly m= sections. The direction is also
3959 // restricted by the direction in the offer.
3960 bool recv_audio = true;
3961 bool recv_video = true;
3962
3963 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003964 if (offer_answer_options.offer_to_receive_audio !=
3965 RTCOfferAnswerOptions::kUndefined) {
3966 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003967 }
Steve Antondcc3c022017-12-22 16:02:54 -08003968 if (offer_answer_options.offer_to_receive_video !=
3969 RTCOfferAnswerOptions::kUndefined) {
3970 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003971 }
3972
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003973 absl::optional<size_t> audio_index;
3974 absl::optional<size_t> video_index;
3975 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003976
3977 // Generate m= sections that match those in the offer.
3978 // Note that mediasession.cc will handle intersection our preferred
3979 // direction with the offered direction.
3980 GenerateMediaDescriptionOptions(
3981 remote_description(),
3982 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3983 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3984 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003985
3986 cricket::MediaDescriptionOptions* audio_media_description_options =
3987 !audio_index ? nullptr
3988 : &session_options->media_description_options[*audio_index];
3989 cricket::MediaDescriptionOptions* video_media_description_options =
3990 !video_index ? nullptr
3991 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003992
Steve Anton4171afb2017-11-20 10:20:22 -08003993 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003994 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003995}
zhihuangaf388472016-11-02 16:49:48 -07003996
Steve Antondcc3c022017-12-22 16:02:54 -08003997void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3998 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3999 cricket::MediaSessionOptions* session_options) {
4000 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4001 // Answers) and 5.3.2 (Subsequent Answers).
4002 RTC_DCHECK(remote_description());
4003 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4004 for (const ContentInfo& content :
4005 remote_description()->description()->contents()) {
4006 cricket::MediaType media_type = content.media_description()->type();
4007 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4008 media_type == cricket::MEDIA_TYPE_VIDEO) {
4009 auto transceiver = GetAssociatedTransceiver(content.name);
4010 RTC_CHECK(transceiver);
4011 session_options->media_description_options.push_back(
4012 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4013 } else {
4014 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004015 // Reject all data sections if data channels are disabled.
4016 // Reject a data section if it has already been rejected.
4017 // Reject all data sections except for the first one.
4018 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4019 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004020 session_options->media_description_options.push_back(
4021 GetMediaDescriptionOptionsForRejectedData(content.name));
4022 } else {
4023 session_options->media_description_options.push_back(
4024 GetMediaDescriptionOptionsForActiveData(content.name));
4025 }
Steve Antondcc3c022017-12-22 16:02:54 -08004026 }
4027 }
htaa2a49d92016-03-04 02:51:39 -08004028}
4029
zhihuang1c378ed2017-08-17 14:10:50 -07004030void PeerConnection::GenerateMediaDescriptionOptions(
4031 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004032 RtpTransceiverDirection audio_direction,
4033 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004034 absl::optional<size_t>* audio_index,
4035 absl::optional<size_t>* video_index,
4036 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004037 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004038 for (const cricket::ContentInfo& content :
4039 session_desc->description()->contents()) {
4040 if (IsAudioContent(&content)) {
4041 // If we already have an audio m= section, reject this extra one.
4042 if (*audio_index) {
4043 session_options->media_description_options.push_back(
4044 cricket::MediaDescriptionOptions(
4045 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004046 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004047 } else {
4048 session_options->media_description_options.push_back(
4049 cricket::MediaDescriptionOptions(
4050 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004051 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004052 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004053 }
4054 } else if (IsVideoContent(&content)) {
4055 // If we already have an video m= section, reject this extra one.
4056 if (*video_index) {
4057 session_options->media_description_options.push_back(
4058 cricket::MediaDescriptionOptions(
4059 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004060 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004061 } else {
4062 session_options->media_description_options.push_back(
4063 cricket::MediaDescriptionOptions(
4064 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004065 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004066 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004067 }
4068 } else {
4069 RTC_DCHECK(IsDataContent(&content));
4070 // If we already have an data m= section, reject this extra one.
4071 if (*data_index) {
4072 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004073 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004074 } else {
4075 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004076 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004077 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004078 }
4079 }
htaa2a49d92016-03-04 02:51:39 -08004080 }
deadbeefab9b2d12015-10-14 11:33:11 -07004081}
4082
Steve Antonfa2260d2017-12-28 16:38:23 -08004083cricket::MediaDescriptionOptions
4084PeerConnection::GetMediaDescriptionOptionsForActiveData(
4085 const std::string& mid) const {
4086 // Direction for data sections is meaningless, but legacy endpoints might
4087 // expect sendrecv.
4088 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4089 RtpTransceiverDirection::kSendRecv,
4090 /*stopped=*/false);
4091 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4092 return options;
4093}
4094
4095cricket::MediaDescriptionOptions
4096PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4097 const std::string& mid) const {
4098 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4099 RtpTransceiverDirection::kInactive,
4100 /*stopped=*/true);
4101 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4102 return options;
4103}
4104
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004105absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004106 switch (data_channel_type_) {
4107 case cricket::DCT_RTP:
4108 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004109 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004110 }
4111 return rtp_data_channel_->content_name();
4112 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004113 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004114 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004115 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004116 }
4117}
4118
Steve Anton4171afb2017-11-20 10:20:22 -08004119void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4120 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4121 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004122 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004123}
4124
Steve Anton4171afb2017-11-20 10:20:22 -08004125void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004126 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004127 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004128 cricket::MediaType media_type,
4129 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004130 RTC_DCHECK(!IsUnifiedPlan());
4131
Steve Anton4171afb2017-11-20 10:20:22 -08004132 std::vector<RtpSenderInfo>* current_senders =
4133 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004134
Steve Anton4171afb2017-11-20 10:20:22 -08004135 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004136 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004137 for (auto sender_it = current_senders->begin();
4138 sender_it != current_senders->end();
4139 /* incremented manually */) {
4140 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004141 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004142 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004143 std::string params_stream_id;
4144 if (params) {
4145 params_stream_id =
4146 (!params->first_stream_id().empty() ? params->first_stream_id()
4147 : kDefaultStreamId);
4148 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004149 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004150 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004151 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004152 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004153 sender_exists) {
4154 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004155 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004156 OnRemoteSenderRemoved(info, media_type);
4157 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004158 }
4159 }
4160
Steve Anton4171afb2017-11-20 10:20:22 -08004161 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004162 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004163 if (!params.has_ssrcs()) {
4164 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4165 // sender, this means it is coming from a Unified Plan endpoint,so we just
4166 // create a default.
4167 default_sender_needed = true;
4168 break;
4169 }
4170
Seth Hampson845e8782018-03-02 11:34:10 -08004171 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004172 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004173 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4174 // not supported in Plan B, we just take the first here and create the
4175 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004176 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004177 (!params.first_stream_id().empty() ? params.first_stream_id()
4178 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004179 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004180 uint32_t ssrc = params.first_ssrc();
4181
4182 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004183 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004184 if (!stream) {
4185 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004186 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004187 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004188 remote_streams_->AddStream(stream);
4189 new_streams->AddStream(stream);
4190 }
4191
Steve Anton4171afb2017-11-20 10:20:22 -08004192 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004193 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004194 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004195 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004196 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004197 }
4198 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004199
Steve Anton4171afb2017-11-20 10:20:22 -08004200 // Add default sender if necessary.
4201 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004202 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004203 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004204 if (!default_stream) {
4205 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004206 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004207 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004208 remote_streams_->AddStream(default_stream);
4209 new_streams->AddStream(default_stream);
4210 }
Steve Anton4171afb2017-11-20 10:20:22 -08004211 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4212 ? kDefaultAudioSenderId
4213 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004214 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004215 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004216 if (!default_sender_info) {
4217 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004218 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004219 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004220 }
4221 }
deadbeefab9b2d12015-10-14 11:33:11 -07004222}
4223
Steve Anton4171afb2017-11-20 10:20:22 -08004224void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4225 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004226 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4227 << " receiver for track_id=" << sender_info.sender_id
4228 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004229
Steve Anton3d954a62018-04-02 11:27:23 -07004230 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004231 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004232 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004233 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004234 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004235 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004236 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004237 }
4238}
4239
Steve Anton4171afb2017-11-20 10:20:22 -08004240void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4241 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004242 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4243 << " receiver for track_id=" << sender_info.sender_id
4244 << " and stream_id=" << sender_info.stream_id;
4245
Seth Hampson845e8782018-03-02 11:34:10 -08004246 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004247
Henrik Boström933d8b02017-10-10 10:05:16 -07004248 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004249 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004250 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4251 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004252 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004253 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004254 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004255 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004256 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004257 }
4258 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004259 // Stopping or destroying a VideoRtpReceiver will end the
4260 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004261 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004262 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004263 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004264 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004265 // There's no guarantee the track is still available, e.g. the track may
4266 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004267 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004268 }
4269 } else {
nisseede5da42017-01-12 05:15:36 -08004270 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004271 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004272 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004273 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004274 }
deadbeefab9b2d12015-10-14 11:33:11 -07004275}
4276
4277void PeerConnection::UpdateEndedRemoteMediaStreams() {
4278 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4279 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4280 MediaStreamInterface* stream = remote_streams_->at(i);
4281 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4282 streams_to_remove.push_back(stream);
4283 }
4284 }
4285
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004286 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004287 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004288 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004289 }
4290}
4291
Steve Anton4171afb2017-11-20 10:20:22 -08004292void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004293 const std::vector<cricket::StreamParams>& streams,
4294 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004295 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004296
Seth Hampson845e8782018-03-02 11:34:10 -08004297 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004298 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004299 for (auto sender_it = current_senders->begin();
4300 sender_it != current_senders->end();
4301 /* incremented manually */) {
4302 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004303 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004304 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4305 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004306 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004307 OnLocalSenderRemoved(info, media_type);
4308 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004309 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004310 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004311 }
4312 }
4313
Steve Anton4171afb2017-11-20 10:20:22 -08004314 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004315 for (const cricket::StreamParams& params : streams) {
4316 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004317 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004318 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004319 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004320 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004321 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004322 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004323 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004324 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004325 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004326 }
4327 }
4328}
4329
Steve Anton4171afb2017-11-20 10:20:22 -08004330void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4331 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004332 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004333 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004334 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004335 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4336 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004337 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004338 return;
4339 }
4340
deadbeeffac06552015-11-25 11:26:01 -08004341 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004342 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004343 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004344 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004345 }
deadbeeffac06552015-11-25 11:26:01 -08004346
Seth Hampson5b4f0752018-04-02 16:31:36 -07004347 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004348 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004349}
4350
Steve Anton4171afb2017-11-20 10:20:22 -08004351void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4352 cricket::MediaType media_type) {
4353 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004354 if (!sender) {
4355 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004356 // SessionDescriptions has been renegotiated.
4357 return;
4358 }
deadbeeffac06552015-11-25 11:26:01 -08004359
4360 // A sender has been removed from the SessionDescription but it's still
4361 // associated with the PeerConnection. This only occurs if the SDP doesn't
4362 // match with the calls to CreateSender, AddStream and RemoveStream.
4363 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004364 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004365 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004366 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004367 }
deadbeeffac06552015-11-25 11:26:01 -08004368
Steve Anton4171afb2017-11-20 10:20:22 -08004369 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004370}
4371
4372void PeerConnection::UpdateLocalRtpDataChannels(
4373 const cricket::StreamParamsVec& streams) {
4374 std::vector<std::string> existing_channels;
4375
4376 // Find new and active data channels.
4377 for (const cricket::StreamParams& params : streams) {
4378 // |it->sync_label| is actually the data channel label. The reason is that
4379 // we use the same naming of data channels as we do for
4380 // MediaStreams and Tracks.
4381 // For MediaStreams, the sync_label is the MediaStream label and the
4382 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004383 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004384 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004385 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004386 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004387 continue;
4388 }
4389 // Set the SSRC the data channel should use for sending.
4390 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4391 existing_channels.push_back(data_channel_it->first);
4392 }
4393
4394 UpdateClosingRtpDataChannels(existing_channels, true);
4395}
4396
4397void PeerConnection::UpdateRemoteRtpDataChannels(
4398 const cricket::StreamParamsVec& streams) {
4399 std::vector<std::string> existing_channels;
4400
4401 // Find new and active data channels.
4402 for (const cricket::StreamParams& params : streams) {
4403 // The data channel label is either the mslabel or the SSRC if the mslabel
4404 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004405 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004406 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004407 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004408 auto data_channel_it = rtp_data_channels_.find(label);
4409 if (data_channel_it == rtp_data_channels_.end()) {
4410 // This is a new data channel.
4411 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4412 } else {
4413 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4414 }
4415 existing_channels.push_back(label);
4416 }
4417
4418 UpdateClosingRtpDataChannels(existing_channels, false);
4419}
4420
4421void PeerConnection::UpdateClosingRtpDataChannels(
4422 const std::vector<std::string>& active_channels,
4423 bool is_local_update) {
4424 auto it = rtp_data_channels_.begin();
4425 while (it != rtp_data_channels_.end()) {
4426 DataChannel* data_channel = it->second;
4427 if (std::find(active_channels.begin(), active_channels.end(),
4428 data_channel->label()) != active_channels.end()) {
4429 ++it;
4430 continue;
4431 }
4432
4433 if (is_local_update) {
4434 data_channel->SetSendSsrc(0);
4435 } else {
4436 data_channel->RemotePeerRequestClose();
4437 }
4438
4439 if (data_channel->state() == DataChannel::kClosed) {
4440 rtp_data_channels_.erase(it);
4441 it = rtp_data_channels_.begin();
4442 } else {
4443 ++it;
4444 }
4445 }
4446}
4447
4448void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4449 uint32_t remote_ssrc) {
4450 rtc::scoped_refptr<DataChannel> channel(
4451 InternalCreateDataChannel(label, nullptr));
4452 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004453 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004454 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004455 return;
4456 }
4457 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004458 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4459 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004460 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004461}
4462
4463rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4464 const std::string& label,
4465 const InternalDataChannelInit* config) {
4466 if (IsClosed()) {
4467 return nullptr;
4468 }
Steve Anton75737c02017-11-06 10:37:17 -08004469 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004470 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004471 << "InternalCreateDataChannel: Data is not supported in this call.";
4472 return nullptr;
4473 }
4474 InternalDataChannelInit new_config =
4475 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004476 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004477 if (new_config.id < 0) {
4478 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004479 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004480 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004481 RTC_LOG(LS_ERROR)
4482 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004483 return nullptr;
4484 }
4485 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004486 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004487 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004488 return nullptr;
4489 }
4490 }
4491
Steve Anton75737c02017-11-06 10:37:17 -08004492 rtc::scoped_refptr<DataChannel> channel(
4493 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004494 if (!channel) {
4495 sid_allocator_.ReleaseSid(new_config.id);
4496 return nullptr;
4497 }
4498
4499 if (channel->data_channel_type() == cricket::DCT_RTP) {
4500 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004501 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4502 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004503 return nullptr;
4504 }
4505 rtp_data_channels_[channel->label()] = channel;
4506 } else {
4507 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4508 sctp_data_channels_.push_back(channel);
4509 channel->SignalClosed.connect(this,
4510 &PeerConnection::OnSctpDataChannelClosed);
4511 }
4512
Steve Anton2d8609c2018-01-23 16:38:46 -08004513 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004514 return channel;
4515}
4516
4517bool PeerConnection::HasDataChannels() const {
4518 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4519}
4520
4521void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4522 for (const auto& channel : sctp_data_channels_) {
4523 if (channel->id() < 0) {
4524 int sid;
4525 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004526 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004527 continue;
4528 }
4529 channel->SetSctpSid(sid);
4530 }
4531 }
4532}
4533
4534void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004535 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004536 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4537 ++it) {
4538 if (it->get() == channel) {
4539 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004540 // After the closing procedure is done, it's safe to use this ID for
4541 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004542 sid_allocator_.ReleaseSid(channel->id());
4543 }
deadbeefbd292462015-12-14 18:15:29 -08004544 // Since this method is triggered by a signal from the DataChannel,
4545 // we can't free it directly here; we need to free it asynchronously.
4546 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004547 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004548 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4549 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004550 return;
4551 }
4552 }
4553}
4554
deadbeefab9b2d12015-10-14 11:33:11 -07004555void PeerConnection::OnDataChannelDestroyed() {
4556 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4557 // DataChannel may callback to us and try to modify the list.
4558 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4559 temp_rtp_dcs.swap(rtp_data_channels_);
4560 for (const auto& kv : temp_rtp_dcs) {
4561 kv.second->OnTransportChannelDestroyed();
4562 }
4563
4564 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4565 temp_sctp_dcs.swap(sctp_data_channels_);
4566 for (const auto& channel : temp_sctp_dcs) {
4567 channel->OnTransportChannelDestroyed();
4568 }
4569}
4570
4571void PeerConnection::OnDataChannelOpenMessage(
4572 const std::string& label,
4573 const InternalDataChannelInit& config) {
4574 rtc::scoped_refptr<DataChannel> channel(
4575 InternalCreateDataChannel(label, &config));
4576 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004577 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004578 return;
4579 }
4580
deadbeefa601f5c2016-06-06 14:27:39 -07004581 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4582 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004583 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004584 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004585}
4586
Steve Anton4171afb2017-11-20 10:20:22 -08004587rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4588PeerConnection::GetAudioTransceiver() const {
4589 // This method only works with Plan B SDP, where there is a single
4590 // audio/video transceiver.
4591 RTC_DCHECK(!IsUnifiedPlan());
4592 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004593 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004594 return transceiver;
4595 }
4596 }
4597 RTC_NOTREACHED();
4598 return nullptr;
4599}
4600
4601rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4602PeerConnection::GetVideoTransceiver() const {
4603 // This method only works with Plan B SDP, where there is a single
4604 // audio/video transceiver.
4605 RTC_DCHECK(!IsUnifiedPlan());
4606 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004607 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004608 return transceiver;
4609 }
4610 }
4611 RTC_NOTREACHED();
4612 return nullptr;
4613}
4614
4615// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4616// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004617bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004618 switch (type) {
4619 case cricket::MEDIA_TYPE_AUDIO:
4620 return !GetAudioTransceiver()->internal()->senders().empty();
4621 case cricket::MEDIA_TYPE_VIDEO:
4622 return !GetVideoTransceiver()->internal()->senders().empty();
4623 case cricket::MEDIA_TYPE_DATA:
4624 return false;
4625 }
4626 RTC_NOTREACHED();
4627 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004628}
4629
Steve Anton4171afb2017-11-20 10:20:22 -08004630rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4631PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4632 for (auto transceiver : transceivers_) {
4633 for (auto sender : transceiver->internal()->senders()) {
4634 if (sender->track() == track) {
4635 return sender;
4636 }
4637 }
4638 }
4639 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004640}
4641
Steve Anton4171afb2017-11-20 10:20:22 -08004642rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4643PeerConnection::FindSenderById(const std::string& sender_id) const {
4644 for (auto transceiver : transceivers_) {
4645 for (auto sender : transceiver->internal()->senders()) {
4646 if (sender->id() == sender_id) {
4647 return sender;
4648 }
4649 }
4650 }
4651 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004652}
4653
Steve Anton4171afb2017-11-20 10:20:22 -08004654rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4655PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4656 for (auto transceiver : transceivers_) {
4657 for (auto receiver : transceiver->internal()->receivers()) {
4658 if (receiver->id() == receiver_id) {
4659 return receiver;
4660 }
4661 }
4662 }
4663 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004664}
4665
Steve Anton4171afb2017-11-20 10:20:22 -08004666std::vector<PeerConnection::RtpSenderInfo>*
4667PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4668 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4669 media_type == cricket::MEDIA_TYPE_VIDEO);
4670 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4671 ? &remote_audio_sender_infos_
4672 : &remote_video_sender_infos_;
4673}
4674
4675std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004676 cricket::MediaType media_type) {
4677 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4678 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004679 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4680 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004681}
4682
Steve Anton4171afb2017-11-20 10:20:22 -08004683const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4684 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004685 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004686 const std::string sender_id) const {
4687 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004688 if (sender_info.stream_id == stream_id &&
4689 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004690 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004691 }
4692 }
4693 return nullptr;
4694}
4695
4696DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4697 for (const auto& channel : sctp_data_channels_) {
4698 if (channel->id() == sid) {
4699 return channel;
4700 }
4701 }
4702 return nullptr;
4703}
4704
deadbeef91dd5672016-05-18 16:55:30 -07004705bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004706 const cricket::ServerAddresses& stun_servers,
4707 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004708 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004709 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004710 // To handle both internal and externally created port allocator, we will
4711 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004712 port_allocator_flags_ = port_allocator_->flags();
4713 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4714 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4715 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004716 // If the disable-IPv6 flag was specified, we'll not override it
4717 // by experiment.
4718 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004719 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004720 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4721 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004722 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004723 }
4724
zhihuangb09b3f92017-03-07 14:40:51 -08004725 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004726 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004727 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004728 }
4729
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004730 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004731 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004732 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733 }
4734
honghaiz60347052016-05-31 18:29:12 -07004735 if (configuration.candidate_network_policy ==
4736 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004737 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004738 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004739 }
4740
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004741 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004742 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004743 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4744 }
4745
Qingsi Wanga2d60672018-04-11 16:57:45 -07004746 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004747 // No step delay is used while allocating ports.
4748 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4749 port_allocator_->set_candidate_filter(
4750 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004751 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004752
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004753 auto turn_servers_copy = turn_servers;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004754 if (tls_cert_verifier_ != nullptr) {
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004755 for (auto& turn_server : turn_servers_copy) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004756 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4757 }
4758 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004759 // Call this last since it may create pooled allocator sessions using the
4760 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004761 port_allocator_->SetConfiguration(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004762 stun_servers, turn_servers_copy, configuration.ice_candidate_pool_size,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004763 configuration.prune_turn_ports, configuration.turn_customizer,
4764 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004765 return true;
4766}
4767
deadbeef91dd5672016-05-18 16:55:30 -07004768bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004769 const cricket::ServerAddresses& stun_servers,
4770 const std::vector<cricket::RelayServerConfig>& turn_servers,
4771 IceTransportsType type,
4772 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004773 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004774 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004775 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004776 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004777 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004778 // According to JSEP, after setLocalDescription, changing the candidate pool
4779 // size is not allowed, and changing the set of ICE servers will not result
4780 // in new candidates being gathered.
4781 if (local_description()) {
4782 port_allocator_->FreezeCandidatePool();
4783 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004784 // Call this last since it may create pooled allocator sessions using the
4785 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004786 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004787 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004788 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004789}
4790
Steve Antonba818672017-11-06 10:21:57 -08004791cricket::ChannelManager* PeerConnection::channel_manager() const {
4792 return factory_->channel_manager();
4793}
4794
Elad Alon99c3fe52017-10-13 16:29:40 +02004795bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004796 std::unique_ptr<RtcEventLogOutput> output,
4797 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004798 if (!event_log_) {
4799 return false;
4800 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004801 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004802}
4803
4804void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004805 if (event_log_) {
4806 event_log_->StopLogging();
4807 }
ivoc14d5dbe2016-07-04 07:06:55 -07004808}
nisseeaabdf62017-05-05 02:23:02 -07004809
Steve Anton75737c02017-11-06 10:37:17 -08004810cricket::BaseChannel* PeerConnection::GetChannel(
4811 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004812 for (auto transceiver : transceivers_) {
4813 cricket::BaseChannel* channel = transceiver->internal()->channel();
4814 if (channel && channel->content_name() == content_name) {
4815 return channel;
4816 }
Steve Anton75737c02017-11-06 10:37:17 -08004817 }
4818 if (rtp_data_channel() &&
4819 rtp_data_channel()->content_name() == content_name) {
4820 return rtp_data_channel();
4821 }
4822 return nullptr;
4823}
4824
4825bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4826 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004827 RTC_LOG(LS_INFO)
4828 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004829 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004830 return false;
4831 }
4832 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004833 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004834 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004835 return false;
4836 }
4837
Zhi Huange830e682018-03-30 10:48:35 -07004838 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4839 if (dtls_role) {
4840 *role = *dtls_role;
4841 return true;
4842 }
4843 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004844}
4845
4846bool PeerConnection::GetSslRole(const std::string& content_name,
4847 rtc::SSLRole* role) {
4848 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004849 RTC_LOG(LS_INFO)
4850 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004851 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004852 return false;
4853 }
4854
Zhi Huange830e682018-03-30 10:48:35 -07004855 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4856 if (dtls_role) {
4857 *role = *dtls_role;
4858 return true;
4859 }
4860 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004861}
4862
Steve Antonf8470812017-12-04 10:46:21 -08004863void PeerConnection::SetSessionError(SessionError error,
4864 const std::string& error_desc) {
4865 RTC_DCHECK_RUN_ON(signaling_thread());
4866 if (error != session_error_) {
4867 session_error_ = error;
4868 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004869 }
4870}
4871
Zhi Huange830e682018-03-30 10:48:35 -07004872RTCError PeerConnection::UpdateSessionState(
4873 SdpType type,
4874 cricket::ContentSource source,
4875 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004876 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004877
4878 // If there's already a pending error then no state transition should happen.
4879 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004880 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004881
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004882 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004883 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004884 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004885 }
4886
4887 // Update the signaling state according to the specified state machine (see
4888 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004889 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004890 ChangeSignalingState(source == cricket::CS_LOCAL
4891 ? PeerConnectionInterface::kHaveLocalOffer
4892 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004893 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004894 ChangeSignalingState(source == cricket::CS_LOCAL
4895 ? PeerConnectionInterface::kHaveLocalPrAnswer
4896 : PeerConnectionInterface::kHaveRemotePrAnswer);
4897 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004898 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004899 ChangeSignalingState(PeerConnectionInterface::kStable);
4900 }
4901
4902 // Update internal objects according to the session description's media
4903 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004904 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004905 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004906 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004907 }
4908
Steve Anton8a006912017-12-04 15:25:56 -08004909 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004910}
4911
Steve Anton8a006912017-12-04 15:25:56 -08004912RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004913 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004914 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004915 const SessionDescriptionInterface* sdesc =
4916 (source == cricket::CS_LOCAL ? local_description()
4917 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004918 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004919
4920 // Push down the new SDP media section for each audio/video transceiver.
4921 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004922 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004923 FindMediaSectionForTransceiver(transceiver, sdesc);
4924 cricket::BaseChannel* channel = transceiver->internal()->channel();
4925 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004926 continue;
4927 }
4928 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004929 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004930 if (!content_desc) {
4931 continue;
4932 }
4933 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004934 bool success = (source == cricket::CS_LOCAL)
4935 ? channel->SetLocalContent(content_desc, type, &error)
4936 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004937 if (!success) {
4938 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4939 }
4940 }
4941
4942 // If using the RtpDataChannel, push down the new SDP section for it too.
4943 if (rtp_data_channel_) {
4944 const ContentInfo* data_content =
4945 cricket::GetFirstDataContent(sdesc->description());
4946 if (data_content && !data_content->rejected) {
4947 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004948 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004949 if (data_desc) {
4950 std::string error;
4951 bool success =
4952 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004953 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004954 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004955 if (!success) {
4956 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4957 std::move(error));
4958 }
Steve Anton75737c02017-11-06 10:37:17 -08004959 }
4960 }
4961 }
Steve Antoned10bd92017-12-05 10:52:59 -08004962
Steve Anton75737c02017-11-06 10:37:17 -08004963 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4964 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4965 if (sctp_transport_ && local_description() && remote_description() &&
4966 cricket::GetFirstDataContent(local_description()->description()) &&
4967 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004968 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004969 RTC_FROM_HERE,
4970 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004971 if (!success) {
4972 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4973 "Failed to push down SCTP parameters.");
4974 }
Steve Anton75737c02017-11-06 10:37:17 -08004975 }
Steve Antoned10bd92017-12-05 10:52:59 -08004976
Steve Anton8a006912017-12-04 15:25:56 -08004977 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004978}
4979
4980bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4981 RTC_DCHECK(network_thread()->IsCurrent());
4982 RTC_DCHECK(local_description());
4983 RTC_DCHECK(remote_description());
4984 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4985 // When we support "max-message-size", that would also be pushed down here.
4986 return sctp_transport_->Start(
4987 GetSctpPort(local_description()->description()),
4988 GetSctpPort(remote_description()->description()));
4989}
4990
Steve Anton8a006912017-12-04 15:25:56 -08004991RTCError PeerConnection::PushdownTransportDescription(
4992 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004993 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004994 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004995
Zhi Huange830e682018-03-30 10:48:35 -07004996 if (source == cricket::CS_LOCAL) {
4997 const SessionDescriptionInterface* sdesc = local_description();
4998 RTC_DCHECK(sdesc);
4999 return transport_controller_->SetLocalDescription(type,
5000 sdesc->description());
5001 } else {
5002 const SessionDescriptionInterface* sdesc = remote_description();
5003 RTC_DCHECK(sdesc);
5004 return transport_controller_->SetRemoteDescription(type,
5005 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005006 }
Steve Anton75737c02017-11-06 10:37:17 -08005007}
5008
5009bool PeerConnection::GetTransportDescription(
5010 const SessionDescription* description,
5011 const std::string& content_name,
5012 cricket::TransportDescription* tdesc) {
5013 if (!description || !tdesc) {
5014 return false;
5015 }
5016 const TransportInfo* transport_info =
5017 description->GetTransportInfoByName(content_name);
5018 if (!transport_info) {
5019 return false;
5020 }
5021 *tdesc = transport_info->description;
5022 return true;
5023}
5024
Steve Anton75737c02017-11-06 10:37:17 -08005025cricket::IceConfig PeerConnection::ParseIceConfig(
5026 const PeerConnectionInterface::RTCConfiguration& config) const {
5027 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005028 switch (config.continual_gathering_policy) {
5029 case PeerConnectionInterface::GATHER_ONCE:
5030 gathering_policy = cricket::GATHER_ONCE;
5031 break;
5032 case PeerConnectionInterface::GATHER_CONTINUALLY:
5033 gathering_policy = cricket::GATHER_CONTINUALLY;
5034 break;
5035 default:
5036 RTC_NOTREACHED();
5037 gathering_policy = cricket::GATHER_ONCE;
5038 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005039
Steve Anton75737c02017-11-06 10:37:17 -08005040 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005041 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5042 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005043 ice_config.prioritize_most_likely_candidate_pairs =
5044 config.prioritize_most_likely_ice_candidate_pairs;
5045 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005046 RTCConfigurationToIceConfigOptionalInt(
5047 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005048 ice_config.continual_gathering_policy = gathering_policy;
5049 ice_config.presume_writable_when_fully_relayed =
5050 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005051 ice_config.ice_check_interval_strong_connectivity =
5052 config.ice_check_interval_strong_connectivity;
5053 ice_config.ice_check_interval_weak_connectivity =
5054 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005055 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005056 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005057 ice_config.regather_all_networks_interval_range =
5058 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005059 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005060 return ice_config;
5061}
5062
Steve Anton75737c02017-11-06 10:37:17 -08005063bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5064 std::string* track_id) {
5065 if (!local_description()) {
5066 return false;
5067 }
5068 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5069 track_id);
5070}
5071
5072bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5073 std::string* track_id) {
5074 if (!remote_description()) {
5075 return false;
5076 }
5077 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5078 track_id);
5079}
5080
5081bool PeerConnection::SendData(const cricket::SendDataParams& params,
5082 const rtc::CopyOnWriteBuffer& payload,
5083 cricket::SendDataResult* result) {
5084 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005085 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005086 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005087 return false;
5088 }
5089 return rtp_data_channel_
5090 ? rtp_data_channel_->SendData(params, payload, result)
5091 : network_thread()->Invoke<bool>(
5092 RTC_FROM_HERE,
5093 Bind(&cricket::SctpTransportInternal::SendData,
5094 sctp_transport_.get(), params, payload, result));
5095}
5096
5097bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5098 if (!rtp_data_channel_ && !sctp_transport_) {
5099 // Don't log an error here, because DataChannels are expected to call
5100 // ConnectDataChannel in this state. It's the only way to initially tell
5101 // whether or not the underlying transport is ready.
5102 return false;
5103 }
5104 if (rtp_data_channel_) {
5105 rtp_data_channel_->SignalReadyToSendData.connect(
5106 webrtc_data_channel, &DataChannel::OnChannelReady);
5107 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5108 &DataChannel::OnDataReceived);
5109 } else {
5110 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5111 &DataChannel::OnChannelReady);
5112 SignalSctpDataReceived.connect(webrtc_data_channel,
5113 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005114 SignalSctpClosingProcedureStartedRemotely.connect(
5115 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5116 SignalSctpClosingProcedureComplete.connect(
5117 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005118 }
5119 return true;
5120}
5121
5122void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5123 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005124 RTC_LOG(LS_ERROR)
5125 << "DisconnectDataChannel called when rtp_data_channel_ and "
5126 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005127 return;
5128 }
5129 if (rtp_data_channel_) {
5130 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5131 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5132 } else {
5133 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5134 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005135 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5136 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005137 }
5138}
5139
5140void PeerConnection::AddSctpDataStream(int sid) {
5141 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005142 RTC_LOG(LS_ERROR)
5143 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005144 return;
5145 }
5146 network_thread()->Invoke<void>(
5147 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5148 sctp_transport_.get(), sid));
5149}
5150
5151void PeerConnection::RemoveSctpDataStream(int sid) {
5152 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005153 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005154 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005155 return;
5156 }
5157 network_thread()->Invoke<void>(
5158 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5159 sctp_transport_.get(), sid));
5160}
5161
5162bool PeerConnection::ReadyToSendData() const {
5163 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5164 sctp_ready_to_send_data_;
5165}
5166
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005167absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005168 if (sctp_mid_ && transport_controller_) {
5169 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5170 if (dtls_transport) {
5171 return dtls_transport->transport_name();
5172 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005173 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005174 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005175 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005176}
5177
Qingsi Wang72a43a12018-02-20 16:03:18 -08005178cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5179 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005180 network_thread()->Invoke<void>(
5181 RTC_FROM_HERE,
5182 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5183 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005184 return candidate_states_list;
5185}
5186
Steve Anton5dfde182018-02-06 10:34:40 -08005187std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5188 const {
5189 std::map<std::string, std::string> transport_names_by_mid;
5190 for (auto transceiver : transceivers_) {
5191 cricket::BaseChannel* channel = transceiver->internal()->channel();
5192 if (channel) {
5193 transport_names_by_mid[channel->content_name()] =
5194 channel->transport_name();
5195 }
Steve Anton75737c02017-11-06 10:37:17 -08005196 }
Steve Anton5dfde182018-02-06 10:34:40 -08005197 if (rtp_data_channel_) {
5198 transport_names_by_mid[rtp_data_channel_->content_name()] =
5199 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005200 }
5201 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005202 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005203 RTC_DCHECK(transport_name);
5204 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005205 }
Steve Anton5dfde182018-02-06 10:34:40 -08005206 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005207}
5208
Steve Anton5dfde182018-02-06 10:34:40 -08005209std::map<std::string, cricket::TransportStats>
5210PeerConnection::GetTransportStatsByNames(
5211 const std::set<std::string>& transport_names) {
5212 if (!network_thread()->IsCurrent()) {
5213 return network_thread()
5214 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5215 RTC_FROM_HERE,
5216 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005217 }
Steve Anton5dfde182018-02-06 10:34:40 -08005218 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5219 for (const std::string& transport_name : transport_names) {
5220 cricket::TransportStats transport_stats;
5221 bool success =
5222 transport_controller_->GetStats(transport_name, &transport_stats);
5223 if (success) {
5224 transport_stats_by_name[transport_name] = std::move(transport_stats);
5225 } else {
5226 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5227 << transport_name;
5228 }
5229 }
5230 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005231}
5232
5233bool PeerConnection::GetLocalCertificate(
5234 const std::string& transport_name,
5235 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005236 if (!certificate) {
5237 return false;
5238 }
5239 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5240 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005241}
5242
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005243std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005244 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005245 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005246}
5247
5248cricket::DataChannelType PeerConnection::data_channel_type() const {
5249 return data_channel_type_;
5250}
5251
5252bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5253 return pending_ice_restarts_.find(content_name) !=
5254 pending_ice_restarts_.end();
5255}
5256
Steve Anton75737c02017-11-06 10:37:17 -08005257bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5258 return transport_controller_->NeedsIceRestart(content_name);
5259}
5260
5261void PeerConnection::OnCertificateReady(
5262 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5263 transport_controller_->SetLocalCertificate(certificate);
5264}
5265
5266void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005267 SetSessionError(SessionError::kTransport,
5268 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005269}
5270
5271void PeerConnection::OnTransportControllerConnectionState(
5272 cricket::IceConnectionState state) {
5273 switch (state) {
5274 case cricket::kIceConnectionConnecting:
5275 // If the current state is Connected or Completed, then there were
5276 // writable channels but now there are not, so the next state must
5277 // be Disconnected.
5278 // kIceConnectionConnecting is currently used as the default,
5279 // un-connected state by the TransportController, so its only use is
5280 // detecting disconnections.
5281 if (ice_connection_state_ ==
5282 PeerConnectionInterface::kIceConnectionConnected ||
5283 ice_connection_state_ ==
5284 PeerConnectionInterface::kIceConnectionCompleted) {
5285 SetIceConnectionState(
5286 PeerConnectionInterface::kIceConnectionDisconnected);
5287 }
5288 break;
5289 case cricket::kIceConnectionFailed:
5290 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5291 break;
5292 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005293 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005294 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005295 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005296 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005297 break;
5298 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005299 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005300 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005301 if (ice_connection_state_ !=
5302 PeerConnectionInterface::kIceConnectionConnected) {
5303 // If jumping directly from "checking" to "connected",
5304 // signal "connected" first.
5305 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5306 }
5307 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005308 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005309 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005310 break;
5311 default:
5312 RTC_NOTREACHED();
5313 }
5314}
5315
5316void PeerConnection::OnTransportControllerCandidatesGathered(
5317 const std::string& transport_name,
5318 const cricket::Candidates& candidates) {
5319 RTC_DCHECK(signaling_thread()->IsCurrent());
5320 int sdp_mline_index;
5321 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005322 RTC_LOG(LS_ERROR)
5323 << "OnTransportControllerCandidatesGathered: content name "
5324 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005325 return;
5326 }
5327
5328 for (cricket::Candidates::const_iterator citer = candidates.begin();
5329 citer != candidates.end(); ++citer) {
5330 // Use transport_name as the candidate media id.
5331 std::unique_ptr<JsepIceCandidate> candidate(
5332 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5333 if (local_description()) {
5334 mutable_local_description()->AddCandidate(candidate.get());
5335 }
5336 OnIceCandidate(std::move(candidate));
5337 }
5338}
5339
5340void PeerConnection::OnTransportControllerCandidatesRemoved(
5341 const std::vector<cricket::Candidate>& candidates) {
5342 RTC_DCHECK(signaling_thread()->IsCurrent());
5343 // Sanity check.
5344 for (const cricket::Candidate& candidate : candidates) {
5345 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005346 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005347 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005348 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005349 return;
5350 }
5351 }
5352
5353 if (local_description()) {
5354 mutable_local_description()->RemoveCandidates(candidates);
5355 }
5356 OnIceCandidatesRemoved(candidates);
5357}
5358
5359void PeerConnection::OnTransportControllerDtlsHandshakeError(
5360 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005361 RTC_HISTOGRAM_ENUMERATION(
5362 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5363 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005364}
5365
Steve Antoned10bd92017-12-05 10:52:59 -08005366void PeerConnection::EnableSending() {
5367 for (auto transceiver : transceivers_) {
5368 cricket::BaseChannel* channel = transceiver->internal()->channel();
5369 if (channel && !channel->enabled()) {
5370 channel->Enable(true);
5371 }
Steve Anton75737c02017-11-06 10:37:17 -08005372 }
5373
Steve Anton4171afb2017-11-20 10:20:22 -08005374 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005375 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005376 }
Steve Anton75737c02017-11-06 10:37:17 -08005377}
5378
5379// Returns the media index for a local ice candidate given the content name.
5380bool PeerConnection::GetLocalCandidateMediaIndex(
5381 const std::string& content_name,
5382 int* sdp_mline_index) {
5383 if (!local_description() || !sdp_mline_index) {
5384 return false;
5385 }
5386
5387 bool content_found = false;
5388 const ContentInfos& contents = local_description()->description()->contents();
5389 for (size_t index = 0; index < contents.size(); ++index) {
5390 if (contents[index].name == content_name) {
5391 *sdp_mline_index = static_cast<int>(index);
5392 content_found = true;
5393 break;
5394 }
5395 }
5396 return content_found;
5397}
5398
5399bool PeerConnection::UseCandidatesInSessionDescription(
5400 const SessionDescriptionInterface* remote_desc) {
5401 if (!remote_desc) {
5402 return true;
5403 }
5404 bool ret = true;
5405
5406 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5407 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5408 for (size_t n = 0; n < candidates->count(); ++n) {
5409 const IceCandidateInterface* candidate = candidates->at(n);
5410 bool valid = false;
5411 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5412 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005413 RTC_LOG(LS_INFO)
5414 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005415 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005416 }
5417 continue;
5418 }
5419 ret = UseCandidate(candidate);
5420 if (!ret) {
5421 break;
5422 }
5423 }
5424 }
5425 return ret;
5426}
5427
5428bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5429 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5430 size_t remote_content_size =
5431 remote_description()->description()->contents().size();
5432 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005433 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005434 return false;
5435 }
5436
5437 cricket::ContentInfo content =
5438 remote_description()->description()->contents()[mediacontent_index];
5439 std::vector<cricket::Candidate> candidates;
5440 candidates.push_back(candidate->candidate());
5441 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005442 RTCError error =
5443 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005444 if (error.ok()) {
5445 // Candidates successfully submitted for checking.
5446 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5447 ice_connection_state_ ==
5448 PeerConnectionInterface::kIceConnectionDisconnected) {
5449 // If state is New, then the session has just gotten its first remote ICE
5450 // candidates, so go to Checking.
5451 // If state is Disconnected, the session is re-using old candidates or
5452 // receiving additional ones, so go to Checking.
5453 // If state is Connected, stay Connected.
5454 // TODO(bemasc): If state is Connected, and the new candidates are for a
5455 // newly added transport, then the state actually _should_ move to
5456 // checking. Add a way to distinguish that case.
5457 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5458 }
5459 // TODO(bemasc): If state is Completed, go back to Connected.
5460 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005461 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
5463 return true;
5464}
5465
5466void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005467 // Destroy video channel first since it may have a pointer to the
5468 // voice channel.
5469 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005470 if (!video_info || video_info->rejected) {
5471 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005472 }
5473
Steve Anton6fec8802017-12-04 10:37:29 -08005474 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5475 if (!audio_info || audio_info->rejected) {
5476 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478
5479 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5480 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005481 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005482 }
5483}
5484
Steve Antondcc3c022017-12-22 16:02:54 -08005485RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5486 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005487 const cricket::ContentGroup* bundle_group = nullptr;
5488 if (configuration_.bundle_policy ==
5489 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005490 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005491 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005492 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5493 "max-bundle configured but session description "
5494 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005495 }
5496 }
Steve Antondcc3c022017-12-22 16:02:54 -08005497 return std::move(bundle_group);
5498}
5499
5500RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005501 // Creating the media channels. Transports should already have been created
5502 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005503 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005504 if (voice && !voice->rejected &&
5505 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005506 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005507 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005508 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5509 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005510 }
5511 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5512 }
5513
Steve Antondcc3c022017-12-22 16:02:54 -08005514 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005515 if (video && !video->rejected &&
5516 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005517 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005518 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005519 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5520 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005521 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005522 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005523 }
5524
Steve Antondcc3c022017-12-22 16:02:54 -08005525 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005526 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5527 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005528 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005529 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5530 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005531 }
5532 }
5533
Steve Anton8a006912017-12-04 15:25:56 -08005534 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005535}
5536
Steve Anton4171afb2017-11-20 10:20:22 -08005537// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005538cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005539 const std::string& mid) {
5540 RtpTransportInternal* rtp_transport =
5541 transport_controller_->GetRtpTransport(mid);
5542 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005543 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005544 call_.get(), configuration_.media_config, rtp_transport,
5545 signaling_thread(), mid, SrtpRequired(),
5546 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005547 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005548 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005549 }
Steve Anton75737c02017-11-06 10:37:17 -08005550 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5551 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005552 voice_channel->SignalSentPacket.connect(this,
5553 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005554 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005555
Steve Antoneda6ccd2017-12-04 10:21:55 -08005556 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005557}
5558
Steve Anton4171afb2017-11-20 10:20:22 -08005559// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005560cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005561 const std::string& mid) {
5562 RtpTransportInternal* rtp_transport =
5563 transport_controller_->GetRtpTransport(mid);
5564 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005565 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005566 call_.get(), configuration_.media_config, rtp_transport,
5567 signaling_thread(), mid, SrtpRequired(),
5568 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005569 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005570 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005571 }
Steve Anton75737c02017-11-06 10:37:17 -08005572 video_channel->SignalDtlsSrtpSetupFailure.connect(
5573 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005574 video_channel->SignalSentPacket.connect(this,
5575 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005576 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005577
Steve Antoneda6ccd2017-12-04 10:21:55 -08005578 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005579}
5580
Zhi Huange830e682018-03-30 10:48:35 -07005581bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005582 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5583 if (sctp) {
5584 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005585 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005586 << "Trying to create SCTP transport, but didn't compile with "
5587 "SCTP support (HAVE_SCTP)";
5588 return false;
5589 }
5590 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005591 RTC_FROM_HERE,
5592 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005593 return false;
5594 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005595 for (const auto& channel : sctp_data_channels_) {
5596 channel->OnTransportChannelCreated();
5597 }
Steve Anton75737c02017-11-06 10:37:17 -08005598 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005599 RtpTransportInternal* rtp_transport =
5600 transport_controller_->GetRtpTransport(mid);
5601 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005602 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005603 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5604 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005605 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005606 return false;
5607 }
Steve Anton75737c02017-11-06 10:37:17 -08005608 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5609 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5610 rtp_data_channel_->SignalSentPacket.connect(
5611 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005612 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005613 }
5614
Steve Anton75737c02017-11-06 10:37:17 -08005615 return true;
5616}
5617
5618Call::Stats PeerConnection::GetCallStats() {
5619 if (!worker_thread()->IsCurrent()) {
5620 return worker_thread()->Invoke<Call::Stats>(
5621 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5622 }
5623 if (call_) {
5624 return call_->GetStats();
5625 } else {
5626 return Call::Stats();
5627 }
5628}
5629
Zhi Huange830e682018-03-30 10:48:35 -07005630bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005631 RTC_DCHECK(network_thread()->IsCurrent());
5632 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005633 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005634 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005635 RTC_DCHECK(dtls_transport);
5636 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005637 RTC_DCHECK(sctp_transport_);
5638 sctp_invoker_.reset(new rtc::AsyncInvoker());
5639 sctp_transport_->SignalReadyToSendData.connect(
5640 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5641 sctp_transport_->SignalDataReceived.connect(
5642 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005643 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5644 // another thread. Would be nice if there was a helper class similar to
5645 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5646 // code.
5647 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5648 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5649 sctp_transport_->SignalClosingProcedureComplete.connect(
5650 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005651 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005652 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005653 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005654}
5655
5656void PeerConnection::DestroySctpTransport_n() {
5657 RTC_DCHECK(network_thread()->IsCurrent());
5658 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005659 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005660 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
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005722void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005723 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(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005728 &SignalSctpClosingProcedureStartedRemotely, sid));
5729}
5730
5731void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5732 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5733 RTC_DCHECK(network_thread()->IsCurrent());
5734 sctp_invoker_->AsyncInvoke<void>(
5735 RTC_FROM_HERE, signaling_thread(),
5736 rtc::Bind(&sigslot::signal1<int>::operator(),
5737 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005738}
5739
5740// Returns false if bundle is enabled and rtcp_mux is disabled.
5741bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5742 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5743 if (!bundle_enabled)
5744 return true;
5745
5746 const cricket::ContentGroup* bundle_group =
5747 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5748 RTC_DCHECK(bundle_group != NULL);
5749
5750 const cricket::ContentInfos& contents = desc->contents();
5751 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5752 citer != contents.end(); ++citer) {
5753 const cricket::ContentInfo* content = (&*citer);
5754 RTC_DCHECK(content != NULL);
5755 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005756 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005757 if (!HasRtcpMuxEnabled(content))
5758 return false;
5759 }
5760 }
5761 // RTCP-MUX is enabled in all the contents.
5762 return true;
5763}
5764
5765bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005766 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005767}
5768
Steve Anton8a006912017-12-04 15:25:56 -08005769RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005770 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005771 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005772 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775
5776 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005777 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005778 }
5779
Steve Anton3828c062017-12-06 10:34:51 -08005780 SdpType type = sdesc->GetType();
5781 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5782 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005783 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005784 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005785 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787
5788 // Verify crypto settings.
5789 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005790 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5791 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005792 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005793 if (!crypto_error.ok()) {
5794 return crypto_error;
5795 }
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797
5798 // Verify ice-ufrag and ice-pwd.
5799 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005800 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5801 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803
5804 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005805 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5806 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005807 }
5808
5809 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5810 // m-lines that do not rtcp-mux enabled.
5811
5812 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005813 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005814 // With an answer we want to compare the new answer session description with
5815 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005816 const cricket::SessionDescription* offer_desc =
5817 (source == cricket::CS_LOCAL) ? remote_description()->description()
5818 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005819 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5820 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5821 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005822 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5823 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005824 }
5825 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005826 // The re-offers should respect the order of m= sections in current
5827 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005828 // With a re-offer, either the current local or current remote descriptions
5829 // could be the most up to date, so we would like to check against both of
5830 // them if they exist. It could be the case that one of them has a 0 port
5831 // for a media section, but the other does not. This is important to check
5832 // against in the case that we are recycling an m= section.
5833 const cricket::SessionDescription* current_desc = nullptr;
5834 const cricket::SessionDescription* secondary_current_desc = nullptr;
5835 if (local_description()) {
5836 current_desc = local_description()->description();
5837 if (remote_description()) {
5838 secondary_current_desc = remote_description()->description();
5839 }
5840 } else if (remote_description()) {
5841 current_desc = remote_description()->description();
5842 }
Steve Anton75737c02017-11-06 10:37:17 -08005843 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005844 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5845 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5847 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005848 }
5849 }
5850
Steve Antonba42e992018-04-09 14:10:01 -07005851 if (IsUnifiedPlan()) {
5852 // Ensure that each audio and video media section has at most one
5853 // "StreamParams". This will return an error if receiving a session
5854 // description from a "Plan B" endpoint which adds multiple tracks of the
5855 // same type. With Unified Plan, there can only be at most one track per
5856 // media section.
5857 for (const ContentInfo& content : sdesc->description()->contents()) {
5858 const MediaContentDescription& desc = *content.description;
5859 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5860 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5861 desc.streams().size() > 1u) {
5862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5863 "Media section has more than one track specified "
5864 "with a=ssrc lines which is not supported with "
5865 "Unified Plan.");
5866 }
5867 }
5868 }
5869
Steve Anton8a006912017-12-04 15:25:56 -08005870 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005871}
5872
Steve Anton3828c062017-12-06 10:34:51 -08005873bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005874 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005875 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005876 return (state == PeerConnectionInterface::kStable) ||
5877 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005878 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005879 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005880 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5881 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5882 }
5883}
5884
Steve Anton3828c062017-12-06 10:34:51 -08005885bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005886 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005887 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005888 return (state == PeerConnectionInterface::kStable) ||
5889 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005890 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005891 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005892 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5893 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5894 }
5895}
5896
Steve Antonf8470812017-12-04 10:46:21 -08005897const char* PeerConnection::SessionErrorToString(SessionError error) const {
5898 switch (error) {
5899 case SessionError::kNone:
5900 return "ERROR_NONE";
5901 case SessionError::kContent:
5902 return "ERROR_CONTENT";
5903 case SessionError::kTransport:
5904 return "ERROR_TRANSPORT";
5905 }
5906 RTC_NOTREACHED();
5907 return "";
5908}
5909
Steve Anton75737c02017-11-06 10:37:17 -08005910std::string PeerConnection::GetSessionErrorMsg() {
5911 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005912 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5913 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005914 return desc.str();
5915}
5916
Steve Anton8e20f172018-03-06 10:55:04 -08005917void PeerConnection::ReportSdpFormatReceived(
5918 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005919 int num_audio_mlines = 0;
5920 int num_video_mlines = 0;
5921 int num_audio_tracks = 0;
5922 int num_video_tracks = 0;
5923 for (const ContentInfo& content : remote_offer.description()->contents()) {
5924 cricket::MediaType media_type = content.media_description()->type();
5925 int num_tracks = std::max(
5926 1, static_cast<int>(content.media_description()->streams().size()));
5927 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5928 num_audio_mlines += 1;
5929 num_audio_tracks += num_tracks;
5930 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5931 num_video_mlines += 1;
5932 num_video_tracks += num_tracks;
5933 }
5934 }
5935 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5936 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5937 format = kSdpFormatReceivedComplexUnifiedPlan;
5938 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5939 format = kSdpFormatReceivedComplexPlanB;
5940 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5941 format = kSdpFormatReceivedSimple;
5942 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005943 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5944 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005945}
5946
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005947void PeerConnection::NoteUsageEvent(UsageEvent event) {
5948 RTC_DCHECK_RUN_ON(signaling_thread());
5949 usage_event_accumulator_ |= static_cast<int>(event);
5950}
5951
5952void PeerConnection::ReportUsagePattern() const {
5953 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005954 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5955 usage_event_accumulator_,
5956 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005957 const int bad_bits =
5958 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5959 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5960 const int good_bits =
5961 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5962 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5963 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5964 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5965 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005966 // If called after close(), we can't report, because observer may have
5967 // been deallocated, and therefore pointer is null. Write to log instead.
5968 if (observer_) {
5969 Observer()->OnInterestingUsage(usage_event_accumulator_);
5970 } else {
5971 RTC_LOG(LS_INFO) << "Interesting usage signature "
5972 << usage_event_accumulator_
5973 << " observed after observer shutdown";
5974 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005975 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005976}
5977
Steve Anton0ffaaa22018-02-23 10:31:30 -08005978void PeerConnection::ReportNegotiatedSdpSemantics(
5979 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005980 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005981 switch (answer.description()->msid_signaling()) {
5982 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005983 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005984 break;
5985 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005986 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005987 break;
5988 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005989 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005990 break;
5991 case cricket::kMsidSignalingMediaSection |
5992 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005993 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005994 break;
5995 default:
5996 RTC_NOTREACHED();
5997 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005998 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5999 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006000}
6001
Steve Anton75737c02017-11-06 10:37:17 -08006002// We need to check the local/remote description for the Transport instead of
6003// the session, because a new Transport added during renegotiation may have
6004// them unset while the session has them set from the previous negotiation.
6005// Not doing so may trigger the auto generation of transport description and
6006// mess up DTLS identity information, ICE credential, etc.
6007bool PeerConnection::ReadyToUseRemoteCandidate(
6008 const IceCandidateInterface* candidate,
6009 const SessionDescriptionInterface* remote_desc,
6010 bool* valid) {
6011 *valid = true;
6012
6013 const SessionDescriptionInterface* current_remote_desc =
6014 remote_desc ? remote_desc : remote_description();
6015
6016 if (!current_remote_desc) {
6017 return false;
6018 }
6019
6020 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6021 size_t remote_content_size =
6022 current_remote_desc->description()->contents().size();
6023 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006024 RTC_LOG(LS_ERROR)
6025 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6026 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006027
6028 *valid = false;
6029 return false;
6030 }
6031
6032 cricket::ContentInfo content =
6033 current_remote_desc->description()->contents()[mediacontent_index];
6034
6035 const std::string transport_name = GetTransportName(content.name);
6036 if (transport_name.empty()) {
6037 return false;
6038 }
Zhi Huange830e682018-03-30 10:48:35 -07006039 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006040}
6041
6042bool PeerConnection::SrtpRequired() const {
6043 return dtls_enabled_ ||
6044 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6045}
6046
6047void PeerConnection::OnTransportControllerGatheringState(
6048 cricket::IceGatheringState state) {
6049 RTC_DCHECK(signaling_thread()->IsCurrent());
6050 if (state == cricket::kIceGatheringGathering) {
6051 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6052 } else if (state == cricket::kIceGatheringComplete) {
6053 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6054 }
6055}
6056
6057void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006058 std::map<std::string, std::set<cricket::MediaType>>
6059 media_types_by_transport_name;
6060 for (auto transceiver : transceivers_) {
6061 if (transceiver->internal()->channel()) {
6062 const std::string& transport_name =
6063 transceiver->internal()->channel()->transport_name();
6064 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006065 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006066 }
Steve Anton75737c02017-11-06 10:37:17 -08006067 }
6068 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006069 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6070 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006071 }
Zhi Huange830e682018-03-30 10:48:35 -07006072
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006073 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006074 if (transport_name) {
6075 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006076 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006077 }
Zhi Huange830e682018-03-30 10:48:35 -07006078
Steve Antonc7b964c2018-02-01 14:39:45 -08006079 for (const auto& entry : media_types_by_transport_name) {
6080 const std::string& transport_name = entry.first;
6081 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006082 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006083 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006084 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006085 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006086 }
6087 }
6088}
6089// Walk through the ConnectionInfos to gather best connection usage
6090// for IPv4 and IPv6.
6091void PeerConnection::ReportBestConnectionState(
6092 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006093 for (const cricket::TransportChannelStats& channel_stats :
6094 stats.channel_stats) {
6095 for (const cricket::ConnectionInfo& connection_info :
6096 channel_stats.connection_infos) {
6097 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006098 continue;
6099 }
6100
Steve Antonc7b964c2018-02-01 14:39:45 -08006101 const cricket::Candidate& local = connection_info.local_candidate;
6102 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006103
6104 // Increment the counter for IceCandidatePairType.
6105 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6106 (local.type() == RELAY_PORT_TYPE &&
6107 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006108 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6109 GetIceCandidatePairCounter(local, remote),
6110 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006111 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006112 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6113 GetIceCandidatePairCounter(local, remote),
6114 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006115 } else {
6116 RTC_CHECK(0);
6117 }
Steve Anton75737c02017-11-06 10:37:17 -08006118
6119 // Increment the counter for IP type.
6120 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006121 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6122 kBestConnections_IPv4,
6123 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006124 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006125 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6126 kBestConnections_IPv6,
6127 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006128 } else {
6129 RTC_CHECK(0);
6130 }
6131
6132 return;
6133 }
6134 }
6135}
6136
6137void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006138 const cricket::TransportStats& stats,
6139 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006140 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6141 return;
6142 }
6143
6144 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6145 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6146 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6147 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6148 return;
6149 }
6150
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006151 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6152 for (cricket::MediaType media_type : media_types) {
6153 switch (media_type) {
6154 case cricket::MEDIA_TYPE_AUDIO:
6155 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6156 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6157 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6158 break;
6159 case cricket::MEDIA_TYPE_VIDEO:
6160 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6161 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6162 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6163 break;
6164 case cricket::MEDIA_TYPE_DATA:
6165 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6166 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6167 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6168 break;
6169 default:
6170 RTC_NOTREACHED();
6171 continue;
6172 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006173 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006174 }
6175
6176 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6177 for (cricket::MediaType media_type : media_types) {
6178 switch (media_type) {
6179 case cricket::MEDIA_TYPE_AUDIO:
6180 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6181 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6182 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6183 break;
6184 case cricket::MEDIA_TYPE_VIDEO:
6185 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6186 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6187 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6188 break;
6189 case cricket::MEDIA_TYPE_DATA:
6190 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6191 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6192 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6193 break;
6194 default:
6195 RTC_NOTREACHED();
6196 continue;
6197 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006198 }
Steve Anton75737c02017-11-06 10:37:17 -08006199 }
6200}
6201
6202void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6203 RTC_DCHECK(worker_thread()->IsCurrent());
6204 RTC_DCHECK(call_);
6205 call_->OnSentPacket(sent_packet);
6206}
6207
6208const std::string PeerConnection::GetTransportName(
6209 const std::string& content_name) {
6210 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006211 if (channel) {
6212 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006213 }
Steve Anton6fec8802017-12-04 10:37:29 -08006214 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006215 RTC_DCHECK(sctp_mid_);
6216 if (content_name == *sctp_mid_) {
6217 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006218 }
6219 }
6220 // Return an empty string if failed to retrieve the transport name.
6221 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006222}
6223
Steve Anton6fec8802017-12-04 10:37:29 -08006224void PeerConnection::DestroyTransceiverChannel(
6225 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6226 transceiver) {
6227 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006228
Steve Anton6fec8802017-12-04 10:37:29 -08006229 cricket::BaseChannel* channel = transceiver->internal()->channel();
6230 if (channel) {
6231 transceiver->internal()->SetChannel(nullptr);
6232 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006233 }
6234}
6235
6236void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006237 if (rtp_data_channel_) {
6238 OnDataChannelDestroyed();
6239 DestroyBaseChannel(rtp_data_channel_);
6240 rtp_data_channel_ = nullptr;
6241 }
6242
6243 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6244 // grab a reference to this PeerConnection. If this is called from the
6245 // PeerConnection destructor, the RefCountedObject vtable will have already
6246 // been destroyed (since it is a subclass of PeerConnection) and using
6247 // rtc::Bind will cause "Pure virtual function called" error to appear.
6248
6249 if (sctp_transport_) {
6250 OnDataChannelDestroyed();
6251 network_thread()->Invoke<void>(RTC_FROM_HERE,
6252 [this] { DestroySctpTransport_n(); });
6253 }
6254}
6255
6256void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6257 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006258 switch (channel->media_type()) {
6259 case cricket::MEDIA_TYPE_AUDIO:
6260 channel_manager()->DestroyVoiceChannel(
6261 static_cast<cricket::VoiceChannel*>(channel));
6262 break;
6263 case cricket::MEDIA_TYPE_VIDEO:
6264 channel_manager()->DestroyVideoChannel(
6265 static_cast<cricket::VideoChannel*>(channel));
6266 break;
6267 case cricket::MEDIA_TYPE_DATA:
6268 channel_manager()->DestroyRtpDataChannel(
6269 static_cast<cricket::RtpDataChannel*>(channel));
6270 break;
6271 default:
6272 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6273 break;
6274 }
Zhi Huange830e682018-03-30 10:48:35 -07006275}
Steve Anton6fec8802017-12-04 10:37:29 -08006276
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006277bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006278 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006279 RtpTransportInternal* rtp_transport,
6280 cricket::DtlsTransportInternal* dtls_transport) {
6281 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006282 auto base_channel = GetChannel(mid);
6283 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006284 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006285 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006286 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006287 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006288 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006289 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006290}
6291
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006292PeerConnectionObserver* PeerConnection::Observer() const {
6293 // In earlier production code, the pointer was not cleared on close,
6294 // which might have led to undefined behavior if the observer was not
6295 // deallocated, or strange crashes if it was.
6296 // We use CHECK in order to catch such behavior if it exists.
6297 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6298 RTC_CHECK(observer_);
6299 return observer_;
6300}
6301
Harald Alvestrand89061872018-01-02 14:08:34 +01006302void PeerConnection::ClearStatsCache() {
6303 if (stats_collector_) {
6304 stats_collector_->ClearCachedStatsReport();
6305 }
6306}
6307
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006308void PeerConnection::RequestUsagePatternReportForTesting() {
6309 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6310 nullptr);
6311}
6312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006313} // namespace webrtc