blob: 5337fae2a4e852d20cb2718a95e1850260db07e6 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * 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:369 */
10
Mirko Bonadei92ea95e2017-09-15 04:47:3111#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Harald Alvestrand8ebba742018-05-31 12:00:3414#include <limits>
Steve Antondcc3c022017-12-23 00:02:5415#include <queue>
Steve Anton75737c02017-11-06 18:37:1716#include <set>
kwiberg0eb15ed2015-12-17 11:04:1517#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3619
Karl Wiberg918f50c2018-07-05 09:40:3320#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3121#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-31 01:13:0927#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 11:18:2628#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3129#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1732#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3133#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 22:30:0938#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3139#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1741#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4142#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3143#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 09:42:2649#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3150#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 19:54:5355#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3656
Steve Anton75737c02017-11-06 18:37:1757using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1762using 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 18:21:5769namespace webrtc {
70
Steve Anton75737c02017-11-06 18:37:1771// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1775const 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 18:37:1783const 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:3694
Steve Anton75737c02017-11-06 18:37:1795namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3696
Seth Hampson845e8782018-03-02 19:34:1097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2298static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11100
zhihuang8f65cdf2016-05-07 01:40:30101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
henrike@webrtc.org28e20752013-07-10 00:45:36104enum {
wu@webrtc.org91053e72013-08-10 07:18:04105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36106 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 18:33:11107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36108 MSG_GETSTATS,
deadbeefbd292462015-12-15 02:15:29109 MSG_FREE_DATACHANNELS,
Harald Alvestrand19793842018-06-25 10:03:50110 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36111};
112
Harald Alvestrand19793842018-06-25 10:03:50113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52115struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 13:03:05118 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36119
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 14:18:03121 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36122};
123
deadbeefab9b2d12015-10-14 18:33:11124struct 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 14:18:03130 RTCError error;
deadbeefab9b2d12015-10-14 18:33:11131};
132
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52133struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 13:03:05136 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36139};
140
deadbeefab9b2d12015-10-14 18:33:11141// 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 23:05:28147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25149 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 19:49:08155// 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 22:57:10160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 18:33:11165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 21:10:50171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50175 cricket::MediaDescriptionOptions* audio_media_description_options,
176 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 13:50:32177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50182 }
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 22:45:38187 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 21:10:50188 }
189 }
zhihuanga77e6bb2017-08-15 01:17:48190 }
zhihuang1c378ed2017-08-17 21:10:50191}
olka3c747662017-08-17 13:50:32192
zhihuang1c378ed2017-08-17 21:10:50193// 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 18:33:11201 // 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 21:10:50206 // 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 18:33:11210 }
211 }
212}
213
Taylor Brandstettera1c30352016-05-13 15:15:11214uint32_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 13:56:46226 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11227 }
228 return cricket::CF_NONE;
229}
230
deadbeef293e9262017-01-11 20:28:30231// 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 22:59:59239bool 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 18:21:57246std::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 18:38:28265
Steve Anton75737c02017-11-06 18:37:17266IceCandidatePairType 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 23:33:48323// 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 18:37:17338// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48339// |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 18:37:17352 return false;
353 }
354
Seth Hampsonae8a90a2018-02-13 23:33:48355 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-23 00:02:54366 continue;
367 }
Seth Hampsonae8a90a2018-02-13 23:33:48368 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17369 return false;
370 }
371 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48372 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 18:37:17376 return false;
377 }
378 }
379 return true;
380}
381
Seth Hampsonae8a90a2018-02-13 23:33:48382bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
383 const SessionDescription& desc2) {
384 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17385}
386
Qingsi Wang7fc821d2018-07-12 19:54:53387void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
388 cricket::MediaType media_type) {
389 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
390 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26391 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 19:54:53409 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
410 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26411 }
412}
413
Harald Alvestrand76829d72018-07-18 21:24:36414void NoteAddIceCandidateResult(int result) {
415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
416 kAddIceCandidateMax);
417}
418
Steve Anton75737c02017-11-06 18:37:17419// 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 19:54:53425RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17430 continue;
431 }
Harald Alvestrand2e180612018-03-07 09:56:14432 // 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 19:54:53435 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56436 const std::string& mid = content_info.name;
437 if (bundle && bundle->HasContentName(mid) &&
438 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17439 // 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 23:14:30447 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56448 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17449 if (!media || !tinfo) {
450 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17452 }
453 if (dtls_enabled) {
454 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25455 RTC_LOG(LS_WARNING)
456 << "Session description must have DTLS fingerprint if "
457 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56458 return RTCError(RTCErrorType::INVALID_PARAMETER,
459 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17460 }
461 } else {
462 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25463 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17464 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56465 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17466 }
467 }
468 }
Steve Anton8a006912017-12-04 23:25:56469 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17470}
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 23:25:56478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17480 continue;
481 }
Steve Anton8a006912017-12-04 23:25:56482 const std::string& mid = content_info.name;
483 if (bundle && bundle->HasContentName(mid) &&
484 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17485 // 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 23:25:56493 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17494 if (!tinfo) {
495 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25496 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17497 return false;
498 }
499 if (tinfo->description.ice_ufrag.empty() ||
500 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25501 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17502 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 23:14:30513 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 18:37:17517 if (found) {
518 *track_id = found->id;
519 return true;
520 }
521 }
522
Steve Antonb1c1de12017-12-21 23:14:30523 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 18:37:17527 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 23:14:30538 const cricket::DataContentDescription* data_desc =
539 GetFirstDataContentDescription(session_description);
540 RTC_DCHECK(data_desc);
541 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17542 return -1;
543 }
Steve Anton75737c02017-11-06 18:37:17544 std::string value;
545 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
546 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30547 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17548 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 18:37:17558// 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 10:09:25583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 18:37:17585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-17 01:08:42590// 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 23:31:36601std::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 14:47:43612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43616 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23617 }
618 return rtc_configuration_parameter;
619}
620
Steve Anton75737c02017-11-06 18:37:17621} // namespace
622
Henrik Boström31638672017-11-23 16:48:32623// 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 14:18:03644 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32645 }
646
647 private:
648 rtc::scoped_refptr<PeerConnection> pc_;
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
650};
651
deadbeef293e9262017-01-11 20:28:30652bool PeerConnectionInterface::RTCConfiguration::operator==(
653 const PeerConnectionInterface::RTCConfiguration& o) const {
654 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10655 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30656 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56657 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10658 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30659 BundlePolicy bundle_policy;
660 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10661 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
662 int ice_candidate_pool_size;
663 bool disable_ipv6;
664 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11665 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22666 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10667 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43668 absl::optional<int> screencast_min_bitrate;
669 absl::optional<bool> combined_audio_video_bwe;
670 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30671 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 20:28:30678 bool prioritize_most_likely_ice_candidate_pairs;
679 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30680 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 14:47:43684 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 12:01:40691 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56692 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43693 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11694 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30695 };
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 22:40:51716 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11717 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22718 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30719 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30720 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 19:50:14728 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14729 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 17:13:10733 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57734 ice_unwritable_timeout == o.ice_unwritable_timeout &&
735 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49736 stun_candidate_keepalive_interval ==
737 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40738 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56739 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40740 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11741 network_preference == o.network_preference &&
742 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30743}
744
745bool PeerConnectionInterface::RTCConfiguration::operator!=(
746 const PeerConnectionInterface::RTCConfiguration& o) const {
747 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26748}
749
zhihuang8f65cdf2016-05-07 01:40:30750// 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 10:09:25754 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27755 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30756 }
757 return cname;
758}
759
zhihuang1c378ed2017-08-17 21:10:50760bool 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 13:50:32764}
765
zhihuang1c378ed2017-08-17 21:10:50766// 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-15 01:17:48774
zhihuang1c378ed2017-08-17 21:10:50775bool ConvertConstraintsToOfferAnswerOptions(
776 const MediaConstraintsInterface* constraints,
777 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 13:50:32778 if (!constraints) {
779 return true;
780 }
zhihuang1c378ed2017-08-17 21:10:50781
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 18:33:11816 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
817}
818
zhihuang38ede132017-06-15 19:52:32819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36822 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 19:20:13833 // 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 18:20:22839
Taylor Brandstettera1c30352016-05-13 15:15:11840 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 18:37:17845
Steve Anton8af21862017-12-15 19:20:13846 // 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 10:09:25850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 23:55:30857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15862 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09863 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15864 event_log_.reset();
865 });
henrike@webrtc.org28e20752013-07-10 00:45:36866}
867
Steve Anton8af21862017-12-15 19:20:13868void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08869 // Destroy video channels first since they may have a pointer to a voice
870 // channel.
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08872 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08878 DestroyTransceiverChannel(transceiver);
879 }
880 }
881 DestroyDataChannel();
882}
883
henrike@webrtc.org28e20752013-07-10 00:45:36884bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45885 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47886 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17887 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59888
889 RTCError config_error = ValidateConfiguration(configuration);
890 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25891 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59892 return false;
893 }
894
Benjamin Wrightcab588882018-05-02 22:12:47895 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25896 RTC_LOG(LS_ERROR)
897 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07898 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30899 return false;
900 }
Jonas Orelandbdcee282017-10-10 12:01:40901
Benjamin Wrightcab588882018-05-02 22:12:47902 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30903 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25904 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07905 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10906 return false;
907 }
Benjamin Wrightd6f86e82018-05-08 20:12:25908
Benjamin Wrightcab588882018-05-02 22:12:47909 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15910 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47911 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25912 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10913
Harald Alvestrandb2a74782018-06-28 11:54:07914 cricket::ServerAddresses stun_servers;
915 std::vector<cricket::RelayServerConfig> turn_servers;
916
917 RTCErrorType parse_error =
918 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
919 if (parse_error != RTCErrorType::NONE) {
920 return false;
921 }
922
deadbeef91dd5672016-05-18 23:55:30923 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11924 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27925 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 11:54:07926 RTC_FROM_HERE,
927 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
928 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36929 return false;
930 }
Harald Alvestrandb2a74782018-06-28 11:54:07931 // If initialization was successful, note if STUN or TURN servers
932 // were supplied.
933 if (!stun_servers.empty()) {
934 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
935 }
936 if (!turn_servers.empty()) {
937 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
938 }
henrike@webrtc.org28e20752013-07-10 00:45:36939
Qingsi Wang7fc821d2018-07-12 19:54:53940 // Send information about IPv4/IPv6 status.
941 PeerConnectionAddressFamilyCounter address_family;
942 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
943 address_family = kPeerConnection_IPv6;
944 } else {
945 address_family = kPeerConnection_IPv4;
946 }
947 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
948 kPeerConnectionAddressFamilyCounter_Max);
949
Zhi Huange830e682018-03-30 17:48:35950 const PeerConnectionFactoryInterface::Options& options = factory_->options();
951
Steve Anton75737c02017-11-06 18:37:17952 // RFC 3264: The numeric value of the session id and version in the
953 // o line MUST be representable with a "64 bit signed integer".
954 // Due to this constraint session id |session_id_| is max limited to
955 // LLONG_MAX.
956 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35957 JsepTransportController::Config config;
958 config.redetermine_role_on_ice_restart =
959 configuration.redetermine_role_on_ice_restart;
960 config.ssl_max_version = factory_->options().ssl_max_version;
961 config.disable_encryption = options.disable_encryption;
962 config.bundle_policy = configuration.bundle_policy;
963 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
964 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:34965 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46966 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35967#if defined(ENABLE_EXTERNAL_AUTH)
968 config.enable_external_auth = true;
969#endif
Zhi Huangb57e1692018-06-12 18:41:11970 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 17:48:35971 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:15972 signaling_thread(), network_thread(), port_allocator_.get(),
973 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:35974 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 18:37:17975 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 17:48:35976 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17977 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35978 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17979 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35980 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17981 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
982 transport_controller_->SignalDtlsHandshakeError.connect(
983 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
984
985 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25986
deadbeefab9b2d12015-10-14 18:33:11987 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01988 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36989
Steve Antonba818672017-11-06 18:21:57990 configuration_ = configuration;
991
Steve Anton75737c02017-11-06 18:37:17992 // Obtain a certificate from RTCConfiguration if any were provided (optional).
993 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
994 if (!configuration.certificates.empty()) {
995 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
996 // just picking the first one. The decision should be made based on the DTLS
997 // handshake. The DTLS negotiations need to know about all certificates.
998 certificate = configuration.certificates[0];
999 }
1000
Steve Antond25da372017-11-06 22:50:291001 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171002
1003 if (options.disable_encryption) {
1004 dtls_enabled_ = false;
1005 } else {
1006 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:471007 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:171008 // |configuration| can override the default |dtls_enabled_| value.
1009 if (configuration.enable_dtls_srtp) {
1010 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1011 }
1012 }
1013
1014 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1015 // It takes precendence over the disable_sctp_data_channels
1016 // PeerConnectionFactoryInterface::Options.
1017 if (configuration.enable_rtp_data_channel) {
1018 data_channel_type_ = cricket::DCT_RTP;
1019 } else {
1020 // DTLS has to be enabled to use SCTP.
1021 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1022 data_channel_type_ = cricket::DCT_SCTP;
1023 }
1024 }
1025
1026 video_options_.screencast_min_bitrate_kbps =
1027 configuration.screencast_min_bitrate;
1028 audio_options_.combined_audio_video_bwe =
1029 configuration.combined_audio_video_bwe;
1030
1031 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301032 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171033
1034 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301035 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171036
1037 // Whether the certificate generator/certificate is null or not determines
1038 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1039 // the right instructions by clearing the variables if needed.
1040 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471041 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171042 certificate = nullptr;
1043 } else if (certificate) {
1044 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471045 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171046 }
1047
1048 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1049 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471050 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171051 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1052 this, &PeerConnection::OnCertificateReady);
1053
1054 if (options.disable_encryption) {
1055 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1056 }
1057
1058 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1059 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361060
Steve Anton4171afb2017-11-20 18:20:221061 // Add default audio/video transceivers for Plan B SDP.
1062 if (!IsUnifiedPlan()) {
1063 transceivers_.push_back(
1064 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1065 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1066 transceivers_.push_back(
1067 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1068 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1069 }
Harald Alvestrand183e09d2018-06-28 10:04:411070 int delay_ms =
1071 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1072 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1073 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:361074 return true;
1075}
1076
Steve Anton038834f2017-07-14 22:59:591077RTCError PeerConnection::ValidateConfiguration(
1078 const RTCConfiguration& config) const {
1079 if (config.ice_regather_interval_range &&
1080 config.continual_gathering_policy == GATHER_ONCE) {
1081 return RTCError(RTCErrorType::INVALID_PARAMETER,
1082 "ice_regather_interval_range specified but continual "
1083 "gathering policy is GATHER_ONCE");
1084 }
Qingsi Wangdea68892018-03-27 17:55:211085 auto result =
1086 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1087 return result;
Steve Anton038834f2017-07-14 22:59:591088}
1089
Yves Gerey665174f2018-06-19 13:03:051090rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581091 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1092 "Plan SdpSemantics. Please use GetSenders "
1093 "instead.";
deadbeefab9b2d12015-10-14 18:33:111094 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361095}
1096
Yves Gerey665174f2018-06-19 13:03:051097rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581098 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1099 "Plan SdpSemantics. Please use GetReceivers "
1100 "instead.";
deadbeefab9b2d12015-10-14 18:33:111101 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361102}
1103
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291104bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581105 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1106 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171107 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361108 if (IsClosed()) {
1109 return false;
1110 }
deadbeefab9b2d12015-10-14 18:33:111111 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361112 return false;
1113 }
deadbeefab9b2d12015-10-14 18:33:111114
1115 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431116 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1117 observer->SignalAudioTrackAdded.connect(this,
1118 &PeerConnection::OnAudioTrackAdded);
1119 observer->SignalAudioTrackRemoved.connect(
1120 this, &PeerConnection::OnAudioTrackRemoved);
1121 observer->SignalVideoTrackAdded.connect(this,
1122 &PeerConnection::OnVideoTrackAdded);
1123 observer->SignalVideoTrackRemoved.connect(
1124 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291125 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111126
deadbeefab9b2d12015-10-14 18:33:111127 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251128 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111129 }
1130 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251131 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111132 }
1133
tommi@webrtc.org03505bc2014-07-14 20:15:261134 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:161135 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361136 return true;
1137}
1138
1139void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581140 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1141 "Plan SdpSemantics. Please use RemoveTrack "
1142 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171143 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251144 if (!IsClosed()) {
1145 for (const auto& track : local_stream->GetAudioTracks()) {
1146 RemoveAudioTrack(track.get(), local_stream);
1147 }
1148 for (const auto& track : local_stream->GetVideoTracks()) {
1149 RemoveVideoTrack(track.get(), local_stream);
1150 }
deadbeefab9b2d12015-10-14 18:33:111151 }
deadbeefab9b2d12015-10-14 18:33:111152 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431153 stream_observers_.erase(
1154 std::remove_if(
1155 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291156 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281157 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431158 }),
1159 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111160
henrike@webrtc.org28e20752013-07-10 00:45:361161 if (IsClosed()) {
1162 return;
1163 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161164 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361165}
1166
Steve Anton2d6c76a2018-01-06 01:10:521167RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571168 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101169 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521170 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571171 if (!track) {
1172 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1173 }
1174 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1175 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1176 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1177 "Track has invalid kind: " + track->kind());
1178 }
Steve Antonf9381f02017-12-14 18:23:571179 if (IsClosed()) {
1180 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1181 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421182 }
Steve Anton4171afb2017-11-20 18:20:221183 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571184 LOG_AND_RETURN_ERROR(
1185 RTCErrorType::INVALID_PARAMETER,
1186 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421187 }
Steve Antonf9381f02017-12-14 18:23:571188 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361189 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1190 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571191 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161192 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171193 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571194 }
1195 return sender_or_error;
1196}
deadbeefe1f9d832016-01-14 23:35:421197
Steve Antonf9381f02017-12-14 18:23:571198RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1199PeerConnection::AddTrackPlanB(
1200 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101201 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361202 if (stream_ids.size() > 1u) {
1203 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1204 "AddTrack with more than one stream is not "
1205 "supported with Plan B semantics.");
1206 }
1207 std::vector<std::string> adjusted_stream_ids = stream_ids;
1208 if (adjusted_stream_ids.empty()) {
1209 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1210 }
Steve Anton02ee47c2018-01-11 00:26:061211 cricket::MediaType media_type =
1212 (track->kind() == MediaStreamTrackInterface::kAudioKind
1213 ? cricket::MEDIA_TYPE_AUDIO
1214 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361215 auto new_sender =
1216 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 23:35:421217 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 23:19:501218 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221219 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221220 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181221 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361222 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221223 if (sender_info) {
1224 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421225 }
Steve Antonf9381f02017-12-14 18:23:571226 } else {
1227 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 23:19:501228 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221229 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221230 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181231 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361232 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221233 if (sender_info) {
1234 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421235 }
deadbeefe1f9d832016-01-14 23:35:421236 }
Steve Anton02ee47c2018-01-11 00:26:061237 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571238}
deadbeefe1f9d832016-01-14 23:35:421239
Steve Antonf9381f02017-12-14 18:23:571240RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1241PeerConnection::AddTrackUnifiedPlan(
1242 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101243 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571244 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1245 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231246 RTC_LOG(LS_INFO) << "Reusing an existing "
1247 << cricket::MediaTypeToString(transceiver->media_type())
1248 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571249 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121250 transceiver->internal()->set_direction(
1251 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571252 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121253 transceiver->internal()->set_direction(
1254 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571255 }
Steve Anton02ee47c2018-01-11 00:26:061256 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101257 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571258 } else {
1259 cricket::MediaType media_type =
1260 (track->kind() == MediaStreamTrackInterface::kAudioKind
1261 ? cricket::MEDIA_TYPE_AUDIO
1262 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231263 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1264 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501265 std::string sender_id = track->id();
1266 // Avoid creating a sender with an existing ID by generating a random ID.
1267 // This can happen if this is the second time AddTrack has created a sender
1268 // for this track.
1269 if (FindSenderById(sender_id)) {
1270 sender_id = rtc::CreateRandomUuid();
1271 }
1272 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061273 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1274 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571275 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121276 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571277 }
Steve Antonf9381f02017-12-14 18:23:571278 return transceiver->sender();
1279}
1280
1281rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1282PeerConnection::FindFirstTransceiverForAddedTrack(
1283 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1284 RTC_DCHECK(track);
1285 for (auto transceiver : transceivers_) {
1286 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081287 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571288 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421289 !transceiver->internal()->has_ever_been_used_to_send() &&
1290 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571291 return transceiver;
1292 }
1293 }
1294 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421295}
1296
1297bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1298 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331299 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571300}
1301
Steve Anton24db5732018-07-23 17:27:331302RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571303 rtc::scoped_refptr<RtpSenderInterface> sender) {
1304 if (!sender) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1306 }
deadbeefe1f9d832016-01-14 23:35:421307 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571308 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1309 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421310 }
Steve Antonf9381f02017-12-14 18:23:571311 if (IsUnifiedPlan()) {
1312 auto transceiver = FindTransceiverBySender(sender);
1313 if (!transceiver || !sender->track()) {
1314 return RTCError::OK();
1315 }
1316 sender->SetTrack(nullptr);
1317 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121318 transceiver->internal()->set_direction(
1319 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571320 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121321 transceiver->internal()->set_direction(
1322 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571323 }
Steve Anton4171afb2017-11-20 18:20:221324 } else {
Steve Antonf9381f02017-12-14 18:23:571325 bool removed;
1326 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1327 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1328 } else {
1329 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1330 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1331 }
1332 if (!removed) {
1333 LOG_AND_RETURN_ERROR(
1334 RTCErrorType::INVALID_PARAMETER,
1335 "Couldn't find sender " + sender->id() + " to remove.");
1336 }
Steve Anton4171afb2017-11-20 18:20:221337 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161338 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571339 return RTCError::OK();
1340}
1341
1342rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1343PeerConnection::FindTransceiverBySender(
1344 rtc::scoped_refptr<RtpSenderInterface> sender) {
1345 for (auto transceiver : transceivers_) {
1346 if (transceiver->sender() == sender) {
1347 return transceiver;
1348 }
1349 }
1350 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421351}
1352
Steve Anton9158ef62017-11-27 21:01:521353RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1354PeerConnection::AddTransceiver(
1355 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1356 return AddTransceiver(track, RtpTransceiverInit());
1357}
1358
1359RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1360PeerConnection::AddTransceiver(
1361 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1362 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581363 RTC_CHECK(IsUnifiedPlan())
1364 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521365 if (!track) {
1366 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1367 }
1368 cricket::MediaType media_type;
1369 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1370 media_type = cricket::MEDIA_TYPE_AUDIO;
1371 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1372 media_type = cricket::MEDIA_TYPE_VIDEO;
1373 } else {
1374 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1375 "Track kind is not audio or video");
1376 }
1377 return AddTransceiver(media_type, track, init);
1378}
1379
1380RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1381PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1382 return AddTransceiver(media_type, RtpTransceiverInit());
1383}
1384
1385RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1386PeerConnection::AddTransceiver(cricket::MediaType media_type,
1387 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581388 RTC_CHECK(IsUnifiedPlan())
1389 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521390 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1391 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1393 "media type is not audio or video");
1394 }
1395 return AddTransceiver(media_type, nullptr, init);
1396}
1397
1398RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1399PeerConnection::AddTransceiver(
1400 cricket::MediaType media_type,
1401 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071402 const RtpTransceiverInit& init,
1403 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521404 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1405 media_type == cricket::MEDIA_TYPE_VIDEO));
1406 if (track) {
1407 RTC_DCHECK_EQ(media_type,
1408 (track->kind() == MediaStreamTrackInterface::kAudioKind
1409 ? cricket::MEDIA_TYPE_AUDIO
1410 : cricket::MEDIA_TYPE_VIDEO));
1411 }
1412
1413 // TODO(bugs.webrtc.org/7600): Verify init.
1414
Steve Anton3d954a62018-04-02 18:27:231415 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1416 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501417 // Set the sender ID equal to the track ID if the track is specified unless
1418 // that sender ID is already in use.
1419 std::string sender_id =
1420 (track && !FindSenderById(track->id()) ? track->id()
1421 : rtc::CreateRandomUuid());
1422 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061423 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1424 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1425 transceiver->internal()->set_direction(init.direction);
1426
Steve Anton22da89f2018-01-25 21:58:071427 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161428 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071429 }
Steve Antonf9381f02017-12-14 18:23:571430
1431 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1432}
1433
Steve Anton02ee47c2018-01-11 00:26:061434rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1435PeerConnection::CreateSender(
1436 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361437 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061438 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101439 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 21:01:521440 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061441 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1442 RTC_DCHECK(!track ||
1443 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1444 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1445 signaling_thread(),
Steve Anton111fdfd2018-06-25 20:03:361446 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341447 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061448 } else {
1449 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1450 RTC_DCHECK(!track ||
1451 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1452 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 20:03:361453 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341454 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061455 }
Steve Anton111fdfd2018-06-25 20:03:361456 bool set_track_succeeded = sender->SetTrack(track);
1457 RTC_DCHECK(set_track_succeeded);
1458 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061459 return sender;
1460}
1461
1462rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1463PeerConnection::CreateReceiver(cricket::MediaType media_type,
1464 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521465 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1466 receiver;
Steve Anton9158ef62017-11-27 21:01:521467 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521468 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531469 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1470 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341471 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521472 } else {
Steve Anton02ee47c2018-01-11 00:26:061473 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521474 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531475 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1476 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341477 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521478 }
Steve Anton02ee47c2018-01-11 00:26:061479 return receiver;
1480}
1481
1482rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1483PeerConnection::CreateAndAddTransceiver(
1484 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1485 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1486 receiver) {
Steve Anton07563732018-06-26 18:13:501487 // Ensure that the new sender does not have an ID that is already in use by
1488 // another sender.
1489 // Allow receiver IDs to conflict since those come from remote SDP (which
1490 // could be invalid, but should not cause a crash).
1491 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061492 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1493 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521494 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121495 transceiver->internal()->SignalNegotiationNeeded.connect(
1496 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571497 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521498}
1499
Steve Anton52d86772018-02-20 23:48:121500void PeerConnection::OnNegotiationNeeded() {
1501 RTC_DCHECK_RUN_ON(signaling_thread());
1502 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 08:50:161503 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121504}
1505
deadbeeffac06552015-11-25 19:26:011506rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441507 const std::string& kind,
1508 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581509 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1510 "Plan SdpSemantics. Please use AddTransceiver "
1511 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171512 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251513 if (IsClosed()) {
1514 return nullptr;
1515 }
Steve Anton4171afb2017-11-20 18:20:221516
Seth Hampson5b4f0752018-04-02 23:31:361517 // Internally we need to have one stream with Plan B semantics, so we
1518 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101519 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361520 if (stream_id.empty()) {
1521 stream_ids.push_back(rtc::CreateRandomUuid());
1522 RTC_LOG(LS_INFO)
1523 << "No stream_id specified for sender. Generated stream ID: "
1524 << stream_ids[0];
1525 } else {
Seth Hampson845e8782018-03-02 19:34:101526 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061527 }
1528
Steve Anton4171afb2017-11-20 18:20:221529 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391530 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011531 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 20:03:361532 auto* audio_sender = new AudioRtpSender(
1533 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 23:19:501534 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391535 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061536 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221537 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011538 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351539 auto* video_sender =
Steve Anton111fdfd2018-06-25 20:03:361540 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 23:19:501541 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391542 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061543 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221544 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011545 } else {
Mirko Bonadei675513b2017-11-09 10:09:251546 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221547 return nullptr;
deadbeeffac06552015-11-25 19:26:011548 }
Steve Anton111fdfd2018-06-25 20:03:361549 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221550
deadbeefe1f9d832016-01-14 23:35:421551 return new_sender;
deadbeeffac06552015-11-25 19:26:011552}
1553
deadbeef70ab1a12015-09-28 23:53:551554std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1555 const {
deadbeefa601f5c2016-06-06 21:27:391556 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221557 for (auto sender : GetSendersInternal()) {
1558 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391559 }
1560 return ret;
deadbeef70ab1a12015-09-28 23:53:551561}
1562
Steve Anton4171afb2017-11-20 18:20:221563std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1564PeerConnection::GetSendersInternal() const {
1565 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1566 all_senders;
1567 for (auto transceiver : transceivers_) {
1568 auto senders = transceiver->internal()->senders();
1569 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1570 }
1571 return all_senders;
1572}
1573
deadbeef70ab1a12015-09-28 23:53:551574std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1575PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391576 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221577 for (const auto& receiver : GetReceiversInternal()) {
1578 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391579 }
1580 return ret;
deadbeef70ab1a12015-09-28 23:53:551581}
1582
Steve Anton4171afb2017-11-20 18:20:221583std::vector<
1584 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1585PeerConnection::GetReceiversInternal() const {
1586 std::vector<
1587 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1588 all_receivers;
1589 for (auto transceiver : transceivers_) {
1590 auto receivers = transceiver->internal()->receivers();
1591 all_receivers.insert(all_receivers.end(), receivers.begin(),
1592 receivers.end());
1593 }
1594 return all_receivers;
1595}
1596
Steve Anton9158ef62017-11-27 21:01:521597std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1598PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581599 RTC_CHECK(IsUnifiedPlan())
1600 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521601 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1602 for (auto transceiver : transceivers_) {
1603 all_transceivers.push_back(transceiver);
1604 }
1605 return all_transceivers;
1606}
1607
henrike@webrtc.org28e20752013-07-10 00:45:361608bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491609 MediaStreamTrackInterface* track,
1610 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171611 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281612 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561613 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251614 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361615 return false;
1616 }
1617
tommi@webrtc.org03505bc2014-07-14 20:15:261618 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151619 // The StatsCollector is used to tell if a track is valid because it may
1620 // remember tracks that the PeerConnection previously removed.
1621 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251622 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1623 << track->id();
zhihuange9e94c32016-11-04 18:38:151624 return false;
1625 }
Taylor Brandstetter5d97a9a2016-06-10 21:17:271626 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:301627 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361628 return true;
1629}
1630
hbos74e1a4f2016-09-16 06:33:011631void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201632 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011633 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201634 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011635 stats_collector_->GetStatsReport(callback);
1636}
1637
Henrik Boström1df1bf82018-03-20 12:24:201638void PeerConnection::GetStats(
1639 rtc::scoped_refptr<RtpSenderInterface> selector,
1640 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1641 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1642 RTC_DCHECK(callback);
1643 RTC_DCHECK(stats_collector_);
1644 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1645 if (selector) {
1646 for (const auto& proxy_transceiver : transceivers_) {
1647 for (const auto& proxy_sender :
1648 proxy_transceiver->internal()->senders()) {
1649 if (proxy_sender == selector) {
1650 internal_sender = proxy_sender->internal();
1651 break;
1652 }
1653 }
1654 if (internal_sender)
1655 break;
1656 }
1657 }
1658 // If there is no |internal_sender| then |selector| is either null or does not
1659 // belong to the PeerConnection (in Plan B, senders can be removed from the
1660 // PeerConnection). This means that "all the stats objects representing the
1661 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1662 // produces an empty stats report.
1663 stats_collector_->GetStatsReport(internal_sender, callback);
1664}
1665
1666void PeerConnection::GetStats(
1667 rtc::scoped_refptr<RtpReceiverInterface> selector,
1668 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1669 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1670 RTC_DCHECK(callback);
1671 RTC_DCHECK(stats_collector_);
1672 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1673 if (selector) {
1674 for (const auto& proxy_transceiver : transceivers_) {
1675 for (const auto& proxy_receiver :
1676 proxy_transceiver->internal()->receivers()) {
1677 if (proxy_receiver == selector) {
1678 internal_receiver = proxy_receiver->internal();
1679 break;
1680 }
1681 }
1682 if (internal_receiver)
1683 break;
1684 }
1685 }
1686 // If there is no |internal_receiver| then |selector| is either null or does
1687 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1688 // the PeerConnection). This means that "all the stats objects representing
1689 // the selector" is an empty set. Invoking GetStatsReport() with a null
1690 // selector produces an empty stats report.
1691 stats_collector_->GetStatsReport(internal_receiver, callback);
1692}
1693
henrike@webrtc.org28e20752013-07-10 00:45:361694PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1695 return signaling_state_;
1696}
1697
henrike@webrtc.org28e20752013-07-10 00:45:361698PeerConnectionInterface::IceConnectionState
1699PeerConnection::ice_connection_state() {
1700 return ice_connection_state_;
1701}
1702
1703PeerConnectionInterface::IceGatheringState
1704PeerConnection::ice_gathering_state() {
1705 return ice_gathering_state_;
1706}
1707
Yves Gerey665174f2018-06-19 13:03:051708rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361709 const std::string& label,
1710 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171711 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501712
deadbeefab9b2d12015-10-14 18:33:111713 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111714
kwibergd1fe2812016-04-27 13:47:291715 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581716 if (config) {
1717 internal_config.reset(new InternalDataChannelInit(*config));
1718 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521719 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111720 InternalCreateDataChannel(label, internal_config.get()));
1721 if (!channel.get()) {
1722 return nullptr;
1723 }
henrike@webrtc.org28e20752013-07-10 00:45:361724
jiayl@webrtc.org001fd2d2014-05-29 15:31:111725 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1726 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171727 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161728 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111729 }
Harald Alvestrand8ebba742018-05-31 12:00:341730 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361731 return DataChannelProxy::Create(signaling_thread(), channel.get());
1732}
1733
1734void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1735 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171736 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511737
zhihuang1c378ed2017-08-17 21:10:501738 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1739 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1740 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1741 // compares the mandatory fields parsed with the mandatory fields added in the
1742 // |constraints| and some downstream applications might create offers with
1743 // mandatory fields which would not be parsed in the helper method. For
1744 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1745 // |constraints| as a mandatory field but it is not parsed.
1746 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161747
zhihuang1c378ed2017-08-17 21:10:501748 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161749}
1750
1751void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1752 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171753 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511754
nisse7ce109a2017-01-31 08:57:561755 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251756 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161757 return;
1758 }
deadbeefab9b2d12015-10-14 18:33:111759
Steve Anton8d3444d2017-10-20 22:30:511760 if (IsClosed()) {
1761 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251762 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031763 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101764 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511765 return;
1766 }
1767
zhihuang1c378ed2017-08-17 21:10:501768 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111769 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251770 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031771 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101772 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111773 return;
1774 }
1775
Steve Anton22da89f2018-01-25 21:58:071776 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1777 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1778 if (IsUnifiedPlan()) {
1779 RTCError error = HandleLegacyOfferOptions(options);
1780 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031781 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071782 return;
1783 }
1784 }
1785
zhihuang1c378ed2017-08-17 21:10:501786 cricket::MediaSessionOptions session_options;
1787 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291788 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361789}
1790
Steve Anton22da89f2018-01-25 21:58:071791RTCError PeerConnection::HandleLegacyOfferOptions(
1792 const RTCOfferAnswerOptions& options) {
1793 RTC_DCHECK(IsUnifiedPlan());
1794
1795 if (options.offer_to_receive_audio == 0) {
1796 RemoveRecvDirectionFromReceivingTransceiversOfType(
1797 cricket::MEDIA_TYPE_AUDIO);
1798 } else if (options.offer_to_receive_audio == 1) {
1799 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1800 } else if (options.offer_to_receive_audio > 1) {
1801 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1802 "offer_to_receive_audio > 1 is not supported.");
1803 }
1804
1805 if (options.offer_to_receive_video == 0) {
1806 RemoveRecvDirectionFromReceivingTransceiversOfType(
1807 cricket::MEDIA_TYPE_VIDEO);
1808 } else if (options.offer_to_receive_video == 1) {
1809 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1810 } else if (options.offer_to_receive_video > 1) {
1811 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1812 "offer_to_receive_video > 1 is not supported.");
1813 }
1814
1815 return RTCError::OK();
1816}
1817
1818void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1819 cricket::MediaType media_type) {
1820 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231821 RtpTransceiverDirection new_direction =
1822 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1823 if (new_direction != transceiver->direction()) {
1824 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1825 << " transceiver (MID="
1826 << transceiver->mid().value_or("<not set>") << ") from "
1827 << RtpTransceiverDirectionToString(
1828 transceiver->direction())
1829 << " to "
1830 << RtpTransceiverDirectionToString(new_direction)
1831 << " since CreateOffer specified offer_to_receive=0";
1832 transceiver->internal()->set_direction(new_direction);
1833 }
Steve Anton22da89f2018-01-25 21:58:071834 }
1835}
1836
1837void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1838 cricket::MediaType media_type) {
1839 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231840 RTC_LOG(LS_INFO)
1841 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1842 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071843 RtpTransceiverInit init;
1844 init.direction = RtpTransceiverDirection::kRecvOnly;
1845 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1846 }
1847}
1848
1849std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1850PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1851 std::vector<
1852 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1853 receiving_transceivers;
1854 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081855 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071856 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1857 receiving_transceivers.push_back(transceiver);
1858 }
1859 }
1860 return receiving_transceivers;
1861}
1862
henrike@webrtc.org28e20752013-07-10 00:45:361863void PeerConnection::CreateAnswer(
1864 CreateSessionDescriptionObserver* observer,
1865 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171866 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 22:30:511867
nisse7ce109a2017-01-31 08:57:561868 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251869 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361870 return;
1871 }
deadbeefab9b2d12015-10-14 18:33:111872
zhihuang1c378ed2017-08-17 21:10:501873 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1874 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1875 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 18:33:111876 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 10:09:251877 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031878 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101879 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111880 return;
1881 }
1882
Steve Anton8d3444d2017-10-20 22:30:511883 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 10:51:391884}
1885
1886void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1887 const RTCOfferAnswerOptions& options) {
1888 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561889 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251890 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391891 return;
1892 }
1893
Steve Antondffead82018-02-06 18:31:291894 if (!(signaling_state_ == kHaveRemoteOffer ||
1895 signaling_state_ == kHaveLocalPrAnswer)) {
1896 std::string error =
1897 "PeerConnection cannot create an answer in a state other than "
1898 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251899 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031900 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101901 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511902 return;
1903 }
1904
Steve Antondffead82018-02-06 18:31:291905 // The remote description should be set if we're in the right state.
1906 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511907
Steve Anton22da89f2018-01-25 21:58:071908 if (IsUnifiedPlan()) {
1909 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1910 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1911 "supported with Unified Plan semantics. Use the "
1912 "RtpTransceiver API instead.";
1913 }
1914 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1915 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1916 "supported with Unified Plan semantics. Use the "
1917 "RtpTransceiver API instead.";
1918 }
1919 }
1920
htaa2a49d92016-03-04 10:51:391921 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501922 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391923
Steve Antond25da372017-11-06 22:50:291924 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361925}
1926
1927void PeerConnection::SetLocalDescription(
1928 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421929 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171930 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561931
Steve Anton80dd7b52018-02-17 01:08:421932 // The SetLocalDescription contract is that we take ownership of the session
1933 // description regardless of the outcome, so wrap it in a unique_ptr right
1934 // away. Ideally, SetLocalDescription's signature will be changed to take the
1935 // description as a unique_ptr argument to formalize this agreement.
1936 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1937
nisse7ce109a2017-01-31 08:57:561938 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251939 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361940 return;
1941 }
Steve Anton8a006912017-12-04 23:25:561942
henrike@webrtc.org28e20752013-07-10 00:45:361943 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031944 PostSetSessionDescriptionFailure(
1945 observer,
1946 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361947 return;
1948 }
Steve Anton8d3444d2017-10-20 22:30:511949
Steve Anton80dd7b52018-02-17 01:08:421950 // If a session error has occurred the PeerConnection is in a possibly
1951 // inconsistent state so fail right away.
1952 if (session_error() != SessionError::kNone) {
1953 std::string error_message = GetSessionErrorMsg();
1954 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031955 PostSetSessionDescriptionFailure(
1956 observer,
1957 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421958 return;
1959 }
Steve Anton8d3444d2017-10-20 22:30:511960
Steve Anton80dd7b52018-02-17 01:08:421961 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1962 if (!error.ok()) {
1963 std::string error_message = GetSetDescriptionErrorMessage(
1964 cricket::CS_LOCAL, desc->GetType(), error);
1965 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031966 PostSetSessionDescriptionFailure(
1967 observer,
1968 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421969 return;
1970 }
1971
1972 // Grab the description type before moving ownership to ApplyLocalDescription,
1973 // which may destroy it before returning.
1974 const SdpType type = desc->GetType();
1975
1976 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561977 // |desc| may be destroyed at this point.
1978
1979 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421980 // If ApplyLocalDescription fails, the PeerConnection could be in an
1981 // inconsistent state, so act conservatively here and set the session error
1982 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1983 SetSessionError(SessionError::kContent, error.message());
1984 std::string error_message =
1985 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1986 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031987 PostSetSessionDescriptionFailure(
1988 observer,
1989 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511990 return;
1991 }
Steve Anton8a006912017-12-04 23:25:561992 RTC_DCHECK(local_description());
1993
1994 PostSetSessionDescriptionSuccess(observer);
1995
Steve Anton8a006912017-12-04 23:25:561996 // MaybeStartGathering needs to be called after posting
1997 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1998 // before signaling that SetLocalDescription completed.
1999 transport_controller_->MaybeStartGathering();
2000
Steve Antona3a92c22017-12-07 18:27:412001 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562002 // TODO(deadbeef): We already had to hop to the network thread for
2003 // MaybeStartGathering...
2004 network_thread()->Invoke<void>(
2005 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2006 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302007 // Make UMA notes about what was agreed to.
2008 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562009 }
Harald Alvestrand8ebba742018-05-31 12:00:342010 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562011}
2012
2013RTCError PeerConnection::ApplyLocalDescription(
2014 std::unique_ptr<SessionDescriptionInterface> desc) {
2015 RTC_DCHECK_RUN_ON(signaling_thread());
2016 RTC_DCHECK(desc);
2017
henrike@webrtc.org28e20752013-07-10 00:45:362018 // Update stats here so that we have the most recent stats for tracks and
2019 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262020 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562021
Steve Antondcc3c022017-12-23 00:02:542022 // Take a reference to the old local description since it's used below to
2023 // compare against the new local description. When setting the new local
2024 // description, grab ownership of the replaced session description in case it
2025 // is the same as |old_local_description|, to keep it alive for the duration
2026 // of the method.
2027 const SessionDescriptionInterface* old_local_description =
2028 local_description();
2029 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352030 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512031 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542032 replaced_local_description = pending_local_description_
2033 ? std::move(pending_local_description_)
2034 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562035 current_local_description_ = std::move(desc);
2036 pending_local_description_ = nullptr;
2037 current_remote_description_ = std::move(pending_remote_description_);
2038 } else {
Steve Antondcc3c022017-12-23 00:02:542039 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562040 pending_local_description_ = std::move(desc);
2041 }
2042 // The session description to apply now must be accessed by
2043 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442044 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112045
Zhi Huange830e682018-03-30 17:48:352046 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2047 if (!error.ok()) {
2048 return error;
2049 }
2050
Steve Antondcc3c022017-12-23 00:02:542051 if (IsUnifiedPlan()) {
2052 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482053 cricket::CS_LOCAL, *local_description(), old_local_description,
2054 remote_description());
Steve Anton8a006912017-12-04 23:25:562055 if (!error.ok()) {
2056 return error;
2057 }
Steve Anton0f5400a2018-07-17 21:25:362058 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2059 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542060 for (auto transceiver : transceivers_) {
2061 const ContentInfo* content =
2062 FindMediaSectionForTransceiver(transceiver, local_description());
2063 if (!content) {
2064 continue;
2065 }
2066 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362067 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2068 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542069 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362070 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2071 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2072 // "recvonly", process the removal of a remote track for the media
2073 // description, given transceiver, removeList, and muteTracks.
2074 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2075 (transceiver->internal()->fired_direction() &&
2076 RtpTransceiverDirectionHasRecv(
2077 *transceiver->internal()->fired_direction()))) {
2078 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2079 &removed_streams);
2080 }
2081 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2082 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542083 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362084 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542085 }
Steve Anton0f5400a2018-07-17 21:25:362086 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162087 auto observer = Observer();
Steve Anton0f5400a2018-07-17 21:25:362088 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162089 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362090 }
2091 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162092 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542093 }
2094 } else {
Zhi Huange830e682018-03-30 17:48:352095 // Media channels will be created only when offer is set. These may use new
2096 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542097 if (type == SdpType::kOffer) {
2098 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2099 // description is applied. Restore back to old description.
2100 RTCError error = CreateChannels(*local_description()->description());
2101 if (!error.ok()) {
2102 return error;
2103 }
2104 }
Steve Antondcc3c022017-12-23 00:02:542105 // Remove unused channels if MediaContentDescription is rejected.
2106 RemoveUnusedChannels(local_description()->description());
2107 }
Steve Anton8a006912017-12-04 23:25:562108
Zhi Huange830e682018-03-30 17:48:352109 error = UpdateSessionState(type, cricket::CS_LOCAL,
2110 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562111 if (!error.ok()) {
2112 return error;
2113 }
Steve Antondcc3c022017-12-23 00:02:542114
Steve Anton8a006912017-12-04 23:25:562115 if (remote_description()) {
2116 // Now that we have a local description, we can push down remote candidates.
2117 UseCandidatesInSessionDescription(remote_description());
2118 }
2119
2120 pending_ice_restarts_.clear();
2121 if (session_error() != SessionError::kNone) {
2122 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2123 }
2124
deadbeefab9b2d12015-10-14 18:33:112125 // If setting the description decided our SSL role, allocate any necessary
2126 // SCTP sids.
2127 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172128 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112129 AllocateSctpSids(role);
2130 }
2131
Steve Antond3679212018-01-18 01:41:022132 if (IsUnifiedPlan()) {
2133 for (auto transceiver : transceivers_) {
2134 const ContentInfo* content =
2135 FindMediaSectionForTransceiver(transceiver, local_description());
2136 if (!content) {
2137 continue;
2138 }
Steve Anton74255ff2018-01-25 02:32:572139 const auto& streams = content->media_description()->streams();
2140 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022141 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102142 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022143 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572144 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272145 } else {
2146 // 0 is a special value meaning "this sender has no associated send
2147 // stream". Need to call this so the sender won't attempt to configure
2148 // a no longer existing stream and run into DCHECKs in the lower
2149 // layers.
2150 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-18 01:41:022151 }
2152 }
2153 } else {
2154 // Plan B semantics.
2155
Steve Antondcc3c022017-12-23 00:02:542156 // Update state and SSRC of local MediaStreams and DataChannels based on the
2157 // local session description.
2158 const cricket::ContentInfo* audio_content =
2159 GetFirstAudioContent(local_description()->description());
2160 if (audio_content) {
2161 if (audio_content->rejected) {
2162 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2163 } else {
2164 const cricket::AudioContentDescription* audio_desc =
2165 audio_content->media_description()->as_audio();
2166 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2167 }
deadbeeffaac4972015-11-12 23:33:072168 }
deadbeefab9b2d12015-10-14 18:33:112169
Steve Antondcc3c022017-12-23 00:02:542170 const cricket::ContentInfo* video_content =
2171 GetFirstVideoContent(local_description()->description());
2172 if (video_content) {
2173 if (video_content->rejected) {
2174 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2175 } else {
2176 const cricket::VideoContentDescription* video_desc =
2177 video_content->media_description()->as_video();
2178 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2179 }
deadbeeffaac4972015-11-12 23:33:072180 }
deadbeefab9b2d12015-10-14 18:33:112181 }
2182
2183 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442184 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112185 if (data_content) {
2186 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302187 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112188 if (rtc::starts_with(data_desc->protocol().data(),
2189 cricket::kMediaProtocolRtpPrefix)) {
2190 UpdateLocalRtpDataChannels(data_desc->streams());
2191 }
2192 }
2193
Steve Anton8a006912017-12-04 23:25:562194 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362195}
2196
2197void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072198 SetSessionDescriptionObserver* observer,
2199 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322200 SetRemoteDescription(
2201 std::unique_ptr<SessionDescriptionInterface>(desc),
2202 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2203 new SetRemoteDescriptionObserverAdapter(this, observer)));
2204}
2205
2206void PeerConnection::SetRemoteDescription(
2207 std::unique_ptr<SessionDescriptionInterface> desc,
2208 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172209 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562210
nisse7ce109a2017-01-31 08:57:562211 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252212 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362213 return;
2214 }
Steve Anton8a006912017-12-04 23:25:562215
henrike@webrtc.org28e20752013-07-10 00:45:362216 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322217 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562218 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362219 return;
2220 }
Steve Anton8d3444d2017-10-20 22:30:512221
Steve Anton80dd7b52018-02-17 01:08:422222 // If a session error has occurred the PeerConnection is in a possibly
2223 // inconsistent state so fail right away.
2224 if (session_error() != SessionError::kNone) {
2225 std::string error_message = GetSessionErrorMsg();
2226 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2227 observer->OnSetRemoteDescriptionComplete(
2228 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2229 return;
2230 }
Steve Anton71439a62018-02-15 19:53:062231
Steve Antonba42e992018-04-09 21:10:012232 if (desc->GetType() == SdpType::kOffer) {
2233 // Report to UMA the format of the received offer.
2234 ReportSdpFormatReceived(*desc);
2235 }
2236
Steve Anton80dd7b52018-02-17 01:08:422237 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062238 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422239 std::string error_message = GetSetDescriptionErrorMessage(
2240 cricket::CS_REMOTE, desc->GetType(), error);
2241 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062242 observer->OnSetRemoteDescriptionComplete(
2243 RTCError(error.type(), std::move(error_message)));
2244 return;
2245 }
Steve Anton71439a62018-02-15 19:53:062246
Steve Anton80dd7b52018-02-17 01:08:422247 // Grab the description type before moving ownership to
2248 // ApplyRemoteDescription, which may destroy it before returning.
2249 const SdpType type = desc->GetType();
2250
2251 error = ApplyRemoteDescription(std::move(desc));
2252 // |desc| may be destroyed at this point.
2253
2254 if (!error.ok()) {
2255 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2256 // inconsistent state, so act conservatively here and set the session error
2257 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2258 SetSessionError(SessionError::kContent, error.message());
2259 std::string error_message =
2260 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2261 RTC_LOG(LS_ERROR) << error_message;
2262 observer->OnSetRemoteDescriptionComplete(
2263 RTCError(error.type(), std::move(error_message)));
2264 return;
2265 }
2266 RTC_DCHECK(remote_description());
2267
2268 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562269 // TODO(deadbeef): We already had to hop to the network thread for
2270 // MaybeStartGathering...
2271 network_thread()->Invoke<void>(
2272 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2273 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002274 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302275 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562276 }
2277
2278 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342279 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562280}
2281
2282RTCError PeerConnection::ApplyRemoteDescription(
2283 std::unique_ptr<SessionDescriptionInterface> desc) {
2284 RTC_DCHECK_RUN_ON(signaling_thread());
2285 RTC_DCHECK(desc);
2286
henrike@webrtc.org28e20752013-07-10 00:45:362287 // Update stats here so that we have the most recent stats for tracks and
2288 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262289 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562290
Steve Antondcc3c022017-12-23 00:02:542291 // Take a reference to the old remote description since it's used below to
2292 // compare against the new remote description. When setting the new remote
2293 // description, grab ownership of the replaced session description in case it
2294 // is the same as |old_remote_description|, to keep it alive for the duration
2295 // of the method.
Steve Anton8a006912017-12-04 23:25:562296 const SessionDescriptionInterface* old_remote_description =
2297 remote_description();
Steve Anton8a006912017-12-04 23:25:562298 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512299 SdpType type = desc->GetType();
2300 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562301 replaced_remote_description = pending_remote_description_
2302 ? std::move(pending_remote_description_)
2303 : std::move(current_remote_description_);
2304 current_remote_description_ = std::move(desc);
2305 pending_remote_description_ = nullptr;
2306 current_local_description_ = std::move(pending_local_description_);
2307 } else {
2308 replaced_remote_description = std::move(pending_remote_description_);
2309 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362310 }
Steve Anton8a006912017-12-04 23:25:562311 // The session description to apply now must be accessed by
2312 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442313 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362314
Zhi Huange830e682018-03-30 17:48:352315 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2316 if (!error.ok()) {
2317 return error;
2318 }
Steve Anton8a006912017-12-04 23:25:562319 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542320 if (IsUnifiedPlan()) {
2321 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482322 cricket::CS_REMOTE, *remote_description(), local_description(),
2323 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562324 if (!error.ok()) {
2325 return error;
2326 }
Steve Antondcc3c022017-12-23 00:02:542327 } else {
Zhi Huange830e682018-03-30 17:48:352328 // Media channels will be created only when offer is set. These may use new
2329 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542330 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352331 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542332 // description is applied. Restore back to old description.
2333 RTCError error = CreateChannels(*remote_description()->description());
2334 if (!error.ok()) {
2335 return error;
2336 }
2337 }
Steve Antondcc3c022017-12-23 00:02:542338 // Remove unused channels if MediaContentDescription is rejected.
2339 RemoveUnusedChannels(remote_description()->description());
2340 }
Steve Anton8a006912017-12-04 23:25:562341
Zhi Huange830e682018-03-30 17:48:352342 // NOTE: Candidates allocation will be initiated only when
2343 // SetLocalDescription is called.
2344 error = UpdateSessionState(type, cricket::CS_REMOTE,
2345 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562346 if (!error.ok()) {
2347 return error;
2348 }
2349
2350 if (local_description() &&
2351 !UseCandidatesInSessionDescription(remote_description())) {
2352 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2353 }
2354
2355 if (old_remote_description) {
2356 for (const cricket::ContentInfo& content :
2357 old_remote_description->description()->contents()) {
2358 // Check if this new SessionDescription contains new ICE ufrag and
2359 // password that indicates the remote peer requests an ICE restart.
2360 // TODO(deadbeef): When we start storing both the current and pending
2361 // remote description, this should reset pending_ice_restarts and compare
2362 // against the current description.
2363 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2364 content.name)) {
Steve Anton3828c062017-12-06 18:34:512365 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562366 pending_ice_restarts_.insert(content.name);
2367 }
2368 } else {
2369 // We retain all received candidates only if ICE is not restarted.
2370 // When ICE is restarted, all previous candidates belong to an old
2371 // generation and should not be kept.
2372 // TODO(deadbeef): This goes against the W3C spec which says the remote
2373 // description should only contain candidates from the last set remote
2374 // description plus any candidates added since then. We should remove
2375 // this once we're sure it won't break anything.
2376 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2377 old_remote_description, content.name, mutable_remote_description());
2378 }
2379 }
2380 }
2381
2382 if (session_error() != SessionError::kNone) {
2383 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2384 }
2385
2386 // Set the the ICE connection state to connecting since the connection may
2387 // become writable with peer reflexive candidates before any remote candidate
2388 // is signaled.
2389 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2390 // is to have a new signal the indicates a change in checking state from the
2391 // transport and expose a new checking() member from transport that can be
2392 // read to determine the current checking state. The existing SignalConnecting
2393 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412394 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172395 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562396 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2397 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2398 }
2399
deadbeefab9b2d12015-10-14 18:33:112400 // If setting the description decided our SSL role, allocate any necessary
2401 // SCTP sids.
2402 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172403 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112404 AllocateSctpSids(role);
2405 }
2406
Steve Antondcc3c022017-12-23 00:02:542407 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422408 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182409 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362410 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132411 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182412 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542413 for (auto transceiver : transceivers_) {
2414 const ContentInfo* content =
2415 FindMediaSectionForTransceiver(transceiver, remote_description());
2416 if (!content) {
2417 continue;
2418 }
2419 const MediaContentDescription* media_desc = content->media_description();
2420 RtpTransceiverDirection local_direction =
2421 RtpTransceiverDirectionReversed(media_desc->direction());
2422 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2423 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2424 // transceiver's current direction is neither sendrecv nor recvonly,
2425 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362426 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422427 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332428 // The remote description has signaled the stream IDs.
2429 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422430 }
Steve Antondcc3c022017-12-23 00:02:542431 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362432 (!transceiver->fired_direction() ||
2433 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232434 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362435 << content->name << " (added to "
2436 << GetStreamIdsString(stream_ids) << ").";
2437
2438 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2439 for (const std::string& stream_id : stream_ids) {
2440 rtc::scoped_refptr<MediaStreamInterface> stream =
2441 remote_streams_->find(stream_id);
2442 if (!stream) {
2443 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2444 MediaStream::Create(stream_id));
2445 remote_streams_->AddStream(stream);
2446 added_streams.push_back(stream);
2447 }
2448 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202449 }
Steve Anton3172c032018-05-03 22:30:182450 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 18:51:532451 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2452 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 23:31:362453 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 22:30:182454 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542455 }
Steve Anton0f5400a2018-07-17 21:25:362456 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2457 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2458 // removal of a remote track for the media description, given transceiver,
2459 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:542460 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362461 (transceiver->fired_direction() &&
2462 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2463 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2464 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542465 }
Steve Anton0f5400a2018-07-17 21:25:362466 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2467 transceiver->internal()->set_fired_direction(local_direction);
2468 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2469 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542470 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362471 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2472 // direction.
Steve Antondcc3c022017-12-23 00:02:542473 transceiver->internal()->set_current_direction(local_direction);
2474 }
Steve Anton0f5400a2018-07-17 21:25:362475 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2476 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:542477 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232478 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2479 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542480 transceiver->Stop();
2481 }
Seth Hampson2f0d7022018-02-20 19:54:422482 if (!content->rejected &&
2483 RtpTransceiverDirectionHasRecv(local_direction)) {
2484 // Set ssrc to 0 in the case of an unsignalled ssrc.
2485 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332486 if (!media_desc->streams().empty() &&
2487 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422488 ssrc = media_desc->streams()[0].first_ssrc();
2489 }
2490 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022491 }
Steve Antondcc3c022017-12-23 00:02:542492 }
Steve Antonc49bcd92018-02-14 22:28:132493 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162494 auto observer = Observer();
Steve Anton3172c032018-05-03 22:30:182495 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162496 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162497 observer->OnTrack(transceiver);
2498 observer->OnAddTrack(transceiver->receiver(),
2499 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202500 }
Steve Antonc49bcd92018-02-14 22:28:132501 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162502 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132503 }
Steve Anton0f5400a2018-07-17 21:25:362504 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162505 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182506 }
2507 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162508 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182509 }
Steve Antondcc3c022017-12-23 00:02:542510 }
2511
Henrik Boströmfdb92012017-11-09 18:55:442512 const cricket::ContentInfo* audio_content =
2513 GetFirstAudioContent(remote_description()->description());
2514 const cricket::ContentInfo* video_content =
2515 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402516 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442517 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402518 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442519 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402520 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442521 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402522
2523 // Check if the descriptions include streams, just in case the peer supports
2524 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442525 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402526 (audio_desc && !audio_desc->streams().empty()) ||
2527 (video_desc && !video_desc->streams().empty())) {
2528 remote_peer_supports_msid_ = true;
2529 }
deadbeefab9b2d12015-10-14 18:33:112530
2531 // We wait to signal new streams until we finish processing the description,
2532 // since only at that point will new streams have all their tracks.
2533 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2534
Steve Antondcc3c022017-12-23 00:02:542535 if (!IsUnifiedPlan()) {
2536 // TODO(steveanton): When removing RTP senders/receivers in response to a
2537 // rejected media section, there is some cleanup logic that expects the
2538 // voice/ video channel to still be set. But in this method the voice/video
2539 // channel would have been destroyed by the SetRemoteDescription caller
2540 // above so the cleanup that relies on them fails to run. The RemoveSenders
2541 // calls should be moved to right before the DestroyChannel calls to fix
2542 // this.
Steve Anton8d3444d2017-10-20 22:30:512543
Steve Antondcc3c022017-12-23 00:02:542544 // Find all audio rtp streams and create corresponding remote AudioTracks
2545 // and MediaStreams.
2546 if (audio_content) {
2547 if (audio_content->rejected) {
2548 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2549 } else {
2550 bool default_audio_track_needed =
2551 !remote_peer_supports_msid_ &&
2552 RtpTransceiverDirectionHasSend(audio_desc->direction());
2553 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2554 default_audio_track_needed, audio_desc->type(),
2555 new_streams);
2556 }
deadbeeffaac4972015-11-12 23:33:072557 }
deadbeefab9b2d12015-10-14 18:33:112558
Steve Antondcc3c022017-12-23 00:02:542559 // Find all video rtp streams and create corresponding remote VideoTracks
2560 // and MediaStreams.
2561 if (video_content) {
2562 if (video_content->rejected) {
2563 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2564 } else {
2565 bool default_video_track_needed =
2566 !remote_peer_supports_msid_ &&
2567 RtpTransceiverDirectionHasSend(video_desc->direction());
2568 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2569 default_video_track_needed, video_desc->type(),
2570 new_streams);
2571 }
deadbeeffaac4972015-11-12 23:33:072572 }
deadbeefab9b2d12015-10-14 18:33:112573
Steve Antondcc3c022017-12-23 00:02:542574 // Update the DataChannels with the information from the remote peer.
2575 if (data_desc) {
2576 if (rtc::starts_with(data_desc->protocol().data(),
2577 cricket::kMediaProtocolRtpPrefix)) {
2578 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2579 }
deadbeefab9b2d12015-10-14 18:33:112580 }
deadbeefab9b2d12015-10-14 18:33:112581
Steve Antondcc3c022017-12-23 00:02:542582 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162583 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542584 for (size_t i = 0; i < new_streams->count(); ++i) {
2585 MediaStreamInterface* new_stream = new_streams->at(i);
2586 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:162587 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542588 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2589 }
deadbeefab9b2d12015-10-14 18:33:112590
Steve Antondcc3c022017-12-23 00:02:542591 UpdateEndedRemoteMediaStreams();
2592 }
deadbeefab9b2d12015-10-14 18:33:112593
Steve Anton8a006912017-12-04 23:25:562594 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332595}
2596
Steve Anton0f5400a2018-07-17 21:25:362597void PeerConnection::ProcessRemovalOfRemoteTrack(
2598 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2599 transceiver,
2600 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2601 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2602 RTC_DCHECK(transceiver->mid());
2603 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2604 << *transceiver->mid();
2605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2606 transceiver->internal()->receiver_internal()->streams();
2607 // This will remove the remote track from the streams.
2608 transceiver->internal()->receiver_internal()->set_stream_ids({});
2609 remove_list->push_back(transceiver);
2610 // Remove any streams that no longer have tracks.
2611 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2612 // of streams, see if the stream was removed by checking if this was the
2613 // last receiver with that stream ID.
2614 for (auto stream : media_streams) {
2615 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2616 remote_streams_->RemoveStream(stream);
2617 removed_streams->push_back(stream);
2618 }
2619 }
2620}
2621
Steve Antondcc3c022017-12-23 00:02:542622RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2623 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482624 const SessionDescriptionInterface& new_session,
2625 const SessionDescriptionInterface* old_local_description,
2626 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542627 RTC_DCHECK(IsUnifiedPlan());
2628
Steve Anton7464fca2018-01-19 19:10:372629 const cricket::ContentGroup* bundle_group = nullptr;
2630 if (new_session.GetType() == SdpType::kOffer) {
2631 auto bundle_group_or_error =
2632 GetEarlyBundleGroup(*new_session.description());
2633 if (!bundle_group_or_error.ok()) {
2634 return bundle_group_or_error.MoveError();
2635 }
2636 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542637 }
Steve Antondcc3c022017-12-23 00:02:542638
Steve Antondcc3c022017-12-23 00:02:542639 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542640 for (size_t i = 0; i < new_contents.size(); ++i) {
2641 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542642 cricket::MediaType media_type = new_content.media_description()->type();
2643 seen_mids_.insert(new_content.name);
2644 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2645 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482646 const cricket::ContentInfo* old_local_content = nullptr;
2647 if (old_local_description &&
2648 i < old_local_description->description()->contents().size()) {
2649 old_local_content =
2650 &old_local_description->description()->contents()[i];
2651 }
2652 const cricket::ContentInfo* old_remote_content = nullptr;
2653 if (old_remote_description &&
2654 i < old_remote_description->description()->contents().size()) {
2655 old_remote_content =
2656 &old_remote_description->description()->contents()[i];
2657 }
Steve Antondcc3c022017-12-23 00:02:542658 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482659 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2660 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542661 if (!transceiver_or_error.ok()) {
2662 return transceiver_or_error.MoveError();
2663 }
2664 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542665 RTCError error =
2666 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2667 if (!error.ok()) {
2668 return error;
2669 }
2670 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232671 if (GetDataMid() && new_content.name != *GetDataMid()) {
2672 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232673 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2674 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232675 continue;
2676 }
2677 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2678 if (!error.ok()) {
2679 return error;
2680 }
Steve Antondcc3c022017-12-23 00:02:542681 } else {
2682 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2683 "Unknown section type.");
2684 }
2685 }
2686
2687 return RTCError::OK();
2688}
2689
2690RTCError PeerConnection::UpdateTransceiverChannel(
2691 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2692 transceiver,
2693 const cricket::ContentInfo& content,
2694 const cricket::ContentGroup* bundle_group) {
2695 RTC_DCHECK(IsUnifiedPlan());
2696 RTC_DCHECK(transceiver);
2697 cricket::BaseChannel* channel = transceiver->internal()->channel();
2698 if (content.rejected) {
2699 if (channel) {
2700 transceiver->internal()->SetChannel(nullptr);
2701 DestroyBaseChannel(channel);
2702 }
2703 } else {
2704 if (!channel) {
Steve Anton69470252018-02-09 19:43:082705 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352706 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542707 } else {
Steve Anton69470252018-02-09 19:43:082708 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352709 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542710 }
2711 if (!channel) {
2712 LOG_AND_RETURN_ERROR(
2713 RTCErrorType::INTERNAL_ERROR,
2714 "Failed to create channel for mid=" + content.name);
2715 }
2716 transceiver->internal()->SetChannel(channel);
2717 }
2718 }
2719 return RTCError::OK();
2720}
2721
Steve Antonfa2260d2017-12-29 00:38:232722RTCError PeerConnection::UpdateDataChannel(
2723 cricket::ContentSource source,
2724 const cricket::ContentInfo& content,
2725 const cricket::ContentGroup* bundle_group) {
2726 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402727 // If data channels are disabled, ignore this media section. CreateAnswer
2728 // will take care of rejecting it.
2729 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232730 }
2731 if (content.rejected) {
2732 DestroyDataChannel();
2733 } else {
2734 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:352735 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232736 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2737 "Failed to create data channel.");
2738 }
2739 }
2740 if (source == cricket::CS_REMOTE) {
2741 const MediaContentDescription* data_desc = content.media_description();
2742 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2743 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2744 }
2745 }
2746 }
2747 return RTCError::OK();
2748}
2749
Steve Antondcc3c022017-12-23 00:02:542750RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2751PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482752 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542753 size_t mline_index,
2754 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482755 const ContentInfo* old_local_content,
2756 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542757 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482758 // If this is an offer then the m= section might be recycled. If the m=
2759 // section is being recycled (defined as: rejected in the current local or
2760 // remote description and not rejected in new description), dissociate the
2761 // currently associated RtpTransceiver by setting its mid property to null,
2762 // and discard the mapping between the transceiver and its m= section index.
2763 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2764 old_remote_content)) {
2765 // We want to dissociate the transceiver that has the rejected mid.
2766 const std::string& old_mid =
2767 (old_local_content && old_local_content->rejected)
2768 ? old_local_content->name
2769 : old_remote_content->name;
2770 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542771 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232772 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2773 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:432774 old_transceiver->internal()->set_mid(absl::nullopt);
2775 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:542776 }
2777 }
2778 const MediaContentDescription* media_desc = content.media_description();
2779 auto transceiver = GetAssociatedTransceiver(content.name);
2780 if (source == cricket::CS_LOCAL) {
2781 // Find the RtpTransceiver that corresponds to this m= section, using the
2782 // mapping between transceivers and m= section indices established when
2783 // creating the offer.
2784 if (!transceiver) {
2785 transceiver = GetTransceiverByMLineIndex(mline_index);
2786 }
2787 if (!transceiver) {
2788 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2789 "Unknown transceiver");
2790 }
2791 } else {
2792 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2793 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2794 // of the same type...
2795 if (!transceiver &&
2796 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2797 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2798 }
2799 // If no RtpTransceiver was found in the previous step, create one with a
2800 // recvonly direction.
2801 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232802 RTC_LOG(LS_INFO) << "Adding "
2803 << cricket::MediaTypeToString(media_desc->type())
2804 << " transceiver for MID=" << content.name
2805 << " at i=" << mline_index
2806 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:362807 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 21:04:012808 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 18:58:302809 std::string receiver_id;
2810 if (!media_desc->streams().empty()) {
2811 receiver_id = media_desc->streams()[0].id;
2812 } else {
2813 receiver_id = rtc::CreateRandomUuid();
2814 }
2815 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062816 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542817 transceiver->internal()->set_direction(
2818 RtpTransceiverDirection::kRecvOnly);
2819 }
2820 }
2821 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082822 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542823 LOG_AND_RETURN_ERROR(
2824 RTCErrorType::INVALID_PARAMETER,
2825 "Transceiver type does not match media description type.");
2826 }
2827 // Associate the found or created RtpTransceiver with the m= section by
2828 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2829 // section, and establish a mapping between the transceiver and the index of
2830 // the m= section.
2831 transceiver->internal()->set_mid(content.name);
2832 transceiver->internal()->set_mline_index(mline_index);
2833 return std::move(transceiver);
2834}
2835
2836rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2837PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2838 RTC_DCHECK(IsUnifiedPlan());
2839 for (auto transceiver : transceivers_) {
2840 if (transceiver->mid() == mid) {
2841 return transceiver;
2842 }
2843 }
2844 return nullptr;
2845}
2846
2847rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2848PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2849 RTC_DCHECK(IsUnifiedPlan());
2850 for (auto transceiver : transceivers_) {
2851 if (transceiver->internal()->mline_index() == mline_index) {
2852 return transceiver;
2853 }
2854 }
2855 return nullptr;
2856}
2857
2858rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2859PeerConnection::FindAvailableTransceiverToReceive(
2860 cricket::MediaType media_type) const {
2861 RTC_DCHECK(IsUnifiedPlan());
2862 // From JSEP section 5.10 (Applying a Remote Description):
2863 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2864 // the same type that were added to the PeerConnection by addTrack and are not
2865 // associated with any m= section and are not stopped, find the first such
2866 // RtpTransceiver.
2867 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082868 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542869 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2870 !transceiver->stopped()) {
2871 return transceiver;
2872 }
2873 }
2874 return nullptr;
2875}
2876
Steve Antoned10bd92017-12-05 18:52:592877const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2878 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2879 transceiver,
2880 const SessionDescriptionInterface* sdesc) const {
2881 RTC_DCHECK(transceiver);
2882 RTC_DCHECK(sdesc);
2883 if (IsUnifiedPlan()) {
2884 if (!transceiver->internal()->mid()) {
2885 // This transceiver is not associated with a media section yet.
2886 return nullptr;
2887 }
2888 return sdesc->description()->GetContentByName(
2889 *transceiver->internal()->mid());
2890 } else {
2891 // Plan B only allows at most one audio and one video section, so use the
2892 // first media section of that type.
2893 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082894 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592895 }
2896}
2897
deadbeef46c73892016-11-17 03:42:042898PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2899 return configuration_;
2900}
2901
deadbeef293e9262017-01-11 20:28:302902bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2903 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172904 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:102905 if (IsClosed()) {
2906 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2907 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2908 }
2909
Qingsi Wanga2d60672018-04-11 23:57:452910 // According to JSEP, after setLocalDescription, changing the candidate pool
2911 // size is not allowed, and changing the set of ICE servers will not result
2912 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:172913 if (local_description() && configuration.ice_candidate_pool_size !=
2914 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252915 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2916 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302917 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452918 }
Taylor Brandstettera1c30352016-05-13 15:15:112919
deadbeef293e9262017-01-11 20:28:302920 // The simplest (and most future-compatible) way to tell if the config was
2921 // modified in an invalid way is to copy each property we do support
2922 // modifying, then use operator==. There are far more properties we don't
2923 // support modifying than those we do, and more could be added.
2924 RTCConfiguration modified_config = configuration_;
2925 modified_config.servers = configuration.servers;
2926 modified_config.type = configuration.type;
2927 modified_config.ice_candidate_pool_size =
2928 configuration.ice_candidate_pool_size;
2929 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052930 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142931 modified_config.ice_check_interval_strong_connectivity =
2932 configuration.ice_check_interval_strong_connectivity;
2933 modified_config.ice_check_interval_weak_connectivity =
2934 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:572935 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2936 modified_config.ice_unwritable_min_checks =
2937 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:492938 modified_config.stun_candidate_keepalive_interval =
2939 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:402940 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:402941 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:112942 modified_config.active_reset_srtp_params =
2943 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:302944 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252945 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302946 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2947 }
2948
Steve Anton038834f2017-07-14 22:59:592949 // Validate the modified configuration.
2950 RTCError validate_error = ValidateConfiguration(modified_config);
2951 if (!validate_error.ok()) {
2952 return SafeSetError(std::move(validate_error), error);
2953 }
2954
deadbeef293e9262017-01-11 20:28:302955 // Note that this isn't possible through chromium, since it's an unsigned
2956 // short in WebIDL.
2957 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:172958 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:302959 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2960 }
2961
2962 // Parse ICE servers before hopping to network thread.
2963 cricket::ServerAddresses stun_servers;
2964 std::vector<cricket::RelayServerConfig> turn_servers;
2965 RTCErrorType parse_error =
2966 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2967 if (parse_error != RTCErrorType::NONE) {
2968 return SafeSetError(parse_error, error);
2969 }
Harald Alvestrand8ebba742018-05-31 12:00:342970 // Note if STUN or TURN servers were supplied.
2971 if (!stun_servers.empty()) {
2972 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2973 }
2974 if (!turn_servers.empty()) {
2975 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2976 }
deadbeef293e9262017-01-11 20:28:302977
2978 // In theory this shouldn't fail.
2979 if (!network_thread()->Invoke<bool>(
2980 RTC_FROM_HERE,
2981 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2982 stun_servers, turn_servers, modified_config.type,
2983 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402984 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:492985 modified_config.turn_customizer,
2986 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:252987 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302988 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2989 }
Honghai Zhang4cedf2b2016-08-31 15:18:112990
deadbeefd1a38b52016-12-10 21:15:332991 // As described in JSEP, calling setConfiguration with new ICE servers or
2992 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2993 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302994 if (modified_config.servers != configuration_.servers ||
2995 modified_config.type != configuration_.type ||
2996 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292997 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332998 }
skvladd1f5fda2017-02-04 00:54:052999
Qingsi Wang9c98f0c2018-02-15 23:10:593000 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:053001
Zhi Huangb57e1692018-06-12 18:41:113002 if (configuration_.active_reset_srtp_params !=
3003 modified_config.active_reset_srtp_params) {
3004 transport_controller_->SetActiveResetSrtpParams(
3005 modified_config.active_reset_srtp_params);
3006 }
3007
deadbeef293e9262017-01-11 20:28:303008 configuration_ = modified_config;
3009 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453010}
3011
henrike@webrtc.org28e20752013-07-10 00:45:363012bool PeerConnection::AddIceCandidate(
3013 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:173014 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:253015 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:103016 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:363017 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:253018 return false;
3019 }
Steve Antond25da372017-11-06 22:50:293020
3021 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103022 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:073023 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:363024 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:293025 return false;
3026 }
3027
3028 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:103029 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:363030 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:293031 return false;
3032 }
3033
3034 bool valid = false;
3035 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3036 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:363037 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:293038 return false;
3039 }
3040
3041 // Add this candidate to the remote session description.
3042 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:103043 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:363044 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:293045 return false;
3046 }
3047
3048 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:363049 bool result = UseCandidate(ice_candidate);
3050 if (result) {
3051 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3052 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3053 } else {
3054 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3055 }
3056 return result;
Steve Antond25da372017-11-06 22:50:293057 } else {
Steve Antonc79268f2018-04-24 16:54:103058 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:363059 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:293060 return true;
3061 }
henrike@webrtc.org28e20752013-07-10 00:45:363062}
3063
Honghai Zhang7fb69db2016-03-14 18:59:183064bool PeerConnection::RemoveIceCandidates(
3065 const std::vector<cricket::Candidate>& candidates) {
3066 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:103067 if (IsClosed()) {
3068 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3069 return false;
3070 }
3071
Steve Antond25da372017-11-06 22:50:293072 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103073 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3074 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293075 return false;
3076 }
3077
3078 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103079 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293080 return false;
3081 }
3082
3083 size_t number_removed =
3084 mutable_remote_description()->RemoveCandidates(candidates);
3085 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253086 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103087 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073088 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253089 << " are removed.";
Steve Antond25da372017-11-06 22:50:293090 }
3091
3092 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353093 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3094 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103095 RTC_LOG(LS_ERROR)
3096 << "RemoveIceCandidates: Error when removing remote candidates: "
3097 << error.message();
Steve Antond25da372017-11-06 22:50:293098 }
3099 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183100}
3101
Niels Möller0c4f7be2018-05-07 12:01:373102RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023103 if (!worker_thread()->IsCurrent()) {
3104 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053105 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373106 }
3107
Niels Möller0c4f7be2018-05-07 12:01:373108 const bool has_min = bitrate.min_bitrate_bps.has_value();
3109 const bool has_start = bitrate.start_bitrate_bps.has_value();
3110 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373111 if (has_min && *bitrate.min_bitrate_bps < 0) {
3112 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3113 "min_bitrate_bps <= 0");
3114 }
Niels Möller0c4f7be2018-05-07 12:01:373115 if (has_start) {
3116 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373117 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373118 "start_bitrate_bps < min_bitrate_bps");
3119 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373120 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3121 "curent_bitrate_bps < 0");
3122 }
3123 }
3124 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053125 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373126 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373127 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373128 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3130 "max_bitrate_bps < min_bitrate_bps");
3131 } else if (*bitrate.max_bitrate_bps < 0) {
3132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3133 "max_bitrate_bps < 0");
3134 }
3135 }
3136
zstein4b979802017-06-02 21:37:373137 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373138 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373139
3140 return RTCError::OK();
3141}
3142
Alex Narest78609d52017-10-20 08:37:473143void PeerConnection::SetBitrateAllocationStrategy(
3144 std::unique_ptr<rtc::BitrateAllocationStrategy>
3145 bitrate_allocation_strategy) {
3146 rtc::Thread* worker_thread = factory_->worker_thread();
3147 if (!worker_thread->IsCurrent()) {
3148 rtc::BitrateAllocationStrategy* strategy_raw =
3149 bitrate_allocation_strategy.release();
3150 auto functor = [this, strategy_raw]() {
3151 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 09:40:333152 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 08:37:473153 };
3154 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3155 return;
3156 }
3157 RTC_DCHECK(call_.get());
3158 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3159}
3160
henrika5f6bf242017-11-01 10:06:563161void PeerConnection::SetAudioPlayout(bool playout) {
3162 if (!worker_thread()->IsCurrent()) {
3163 worker_thread()->Invoke<void>(
3164 RTC_FROM_HERE,
3165 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3166 return;
3167 }
3168 auto audio_state =
3169 factory_->channel_manager()->media_engine()->GetAudioState();
3170 audio_state->SetPlayout(playout);
3171}
3172
3173void PeerConnection::SetAudioRecording(bool recording) {
3174 if (!worker_thread()->IsCurrent()) {
3175 worker_thread()->Invoke<void>(
3176 RTC_FROM_HERE,
3177 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3178 return;
3179 }
3180 auto audio_state =
3181 factory_->channel_manager()->media_engine()->GetAudioState();
3182 audio_state->SetRecording(recording);
3183}
3184
Steve Anton8c0f7a72017-10-03 17:03:103185std::unique_ptr<rtc::SSLCertificate>
3186PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513187 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3188 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103189 return nullptr;
3190 }
Taylor Brandstetterc3928662018-02-23 21:04:513191 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 17:03:103192}
3193
Zhi Huang70b820f2018-01-27 22:16:153194std::unique_ptr<rtc::SSLCertChain>
3195PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373196 auto audio_transceiver = GetFirstAudioTransceiver();
3197 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153198 return nullptr;
3199 }
Zhi Huang70b820f2018-01-27 22:16:153200 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373201 audio_transceiver->internal()->channel()->transport_name());
3202}
3203
3204rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3205PeerConnection::GetFirstAudioTransceiver() const {
3206 for (auto transceiver : transceivers_) {
3207 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3208 return transceiver;
3209 }
3210 }
3211 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153212}
3213
ivoc14d5dbe2016-07-04 14:06:553214bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3215 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403216 // TODO(eladalon): It would be better to not allow negative values into PC.
3217 const size_t max_size = (max_size_bytes < 0)
3218 ? RtcEventLog::kUnlimitedOutput
3219 : rtc::saturated_cast<size_t>(max_size_bytes);
3220 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333221 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 16:38:143222 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:403223}
3224
Bjorn Tereliusde939432017-11-20 16:38:143225bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3226 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063227 // TODO(eladalon): In C++14, this can be done with a lambda.
3228 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143229 bool operator()() {
3230 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3231 }
Karl Wibergd6b48192017-10-16 21:01:063232 PeerConnection* const pc;
3233 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143234 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403235 };
Bjorn Tereliusde939432017-11-20 16:38:143236 return worker_thread()->Invoke<bool>(
3237 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553238}
3239
3240void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023241 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553242 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3243}
3244
henrike@webrtc.org28e20752013-07-10 00:45:363245const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173246 return pending_local_description_ ? pending_local_description_.get()
3247 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363248}
3249
3250const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173251 return pending_remote_description_ ? pending_remote_description_.get()
3252 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363253}
3254
deadbeeffe4a8a42016-12-21 01:56:173255const SessionDescriptionInterface* PeerConnection::current_local_description()
3256 const {
Steve Anton75737c02017-11-06 18:37:173257 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173258}
3259
3260const SessionDescriptionInterface* PeerConnection::current_remote_description()
3261 const {
Steve Anton75737c02017-11-06 18:37:173262 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173263}
3264
3265const SessionDescriptionInterface* PeerConnection::pending_local_description()
3266 const {
Steve Anton75737c02017-11-06 18:37:173267 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173268}
3269
3270const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3271 const {
Steve Anton75737c02017-11-06 18:37:173272 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173273}
3274
henrike@webrtc.org28e20752013-07-10 00:45:363275void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173276 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363277 // Update stats here so that we have the most recent stats for tracks and
3278 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263279 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363280
Steve Anton75737c02017-11-06 18:37:173281 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343282 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083283
Steve Anton8af21862017-12-15 19:20:133284 for (auto transceiver : transceivers_) {
3285 transceiver->Stop();
3286 }
Steve Anton25cfeb92018-04-26 18:44:003287
3288 // Ensure that all asynchronous stats requests are completed before destroying
3289 // the transport controller below.
3290 if (stats_collector_) {
3291 stats_collector_->WaitForPendingRequest();
3292 }
3293
3294 // Don't destroy BaseChannels until after stats has been cleaned up so that
3295 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133296 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173297
Qingsi Wang93a84392018-01-31 01:13:093298 // The event log is used in the transport controller, which must be outlived
3299 // by the former. CreateOffer by the peer connection is implemented
3300 // asynchronously and if the peer connection is closed without resetting the
3301 // WebRTC session description factory, the session description factory would
3302 // call the transport controller.
3303 webrtc_session_desc_factory_.reset();
3304 transport_controller_.reset();
3305
deadbeef42a42632017-03-10 23:18:003306 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053307 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3308 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023309
Steve Anton978b8762017-09-29 19:15:023310 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153311 call_.reset();
3312 // The event log must outlive call (and any other object that uses it).
3313 event_log_.reset();
3314 });
Harald Alvestrand8ebba742018-05-31 12:00:343315 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163316 // The .h file says that observer can be discarded after close() returns.
3317 // Make sure this is true.
3318 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:363319}
3320
buildbot@webrtc.orgd4e598d2014-07-29 17:36:523321void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:363322 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:363323 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3324 SetSessionDescriptionMsg* param =
3325 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3326 param->observer->OnSuccess();
3327 delete param;
3328 break;
3329 }
3330 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3331 SetSessionDescriptionMsg* param =
3332 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033333 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:363334 delete param;
3335 break;
3336 }
deadbeefab9b2d12015-10-14 18:33:113337 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3338 CreateSessionDescriptionMsg* param =
3339 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033340 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 18:33:113341 delete param;
3342 break;
3343 }
henrike@webrtc.org28e20752013-07-10 00:45:363344 case MSG_GETSTATS: {
3345 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 13:00:343346 StatsReports reports;
3347 stats_->GetStats(param->track, &reports);
3348 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:363349 delete param;
3350 break;
3351 }
deadbeefbd292462015-12-15 02:15:293352 case MSG_FREE_DATACHANNELS: {
3353 sctp_data_channels_to_free_.clear();
3354 break;
3355 }
Harald Alvestrand19793842018-06-25 10:03:503356 case MSG_REPORT_USAGE_PATTERN: {
3357 ReportUsagePattern();
3358 break;
3359 }
henrike@webrtc.org28e20752013-07-10 00:45:363360 default:
nisseeb4ca4e2017-01-12 10:24:273361 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:363362 break;
3363 }
3364}
3365
Steve Antonafb0bb72018-02-20 19:35:373366cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3367 RTC_DCHECK(!IsUnifiedPlan());
3368 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3369 GetAudioTransceiver()->internal()->channel());
3370 if (voice_channel) {
3371 return voice_channel->media_channel();
3372 } else {
3373 return nullptr;
3374 }
3375}
3376
3377cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3378 RTC_DCHECK(!IsUnifiedPlan());
3379 auto* video_channel = static_cast<cricket::VideoChannel*>(
3380 GetVideoTransceiver()->internal()->channel());
3381 if (video_channel) {
3382 return video_channel->media_channel();
3383 } else {
3384 return nullptr;
3385 }
3386}
3387
Steve Anton4171afb2017-11-20 18:20:223388void PeerConnection::CreateAudioReceiver(
3389 MediaStreamInterface* stream,
3390 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513391 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3392 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533393 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3394 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023395 auto* audio_receiver = new AudioRtpReceiver(
3396 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503397 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023398 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3399 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3400 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223401 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163402 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343403 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363404}
3405
Steve Anton4171afb2017-11-20 18:20:223406void PeerConnection::CreateVideoReceiver(
3407 MediaStreamInterface* stream,
3408 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513409 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3410 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533411 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3412 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023413 auto* video_receiver = new VideoRtpReceiver(
3414 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503415 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023416 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3417 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3418 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223419 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163420 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343421 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363422}
3423
deadbeef70ab1a12015-09-28 23:53:553424// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3425// description.
Henrik Boström933d8b02017-10-10 17:05:163426rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223427 const RtpSenderInfo& remote_sender_info) {
3428 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3429 if (!receiver) {
3430 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3431 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163432 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553433 }
Steve Anton4171afb2017-11-20 18:20:223434 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3435 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3436 } else {
3437 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3438 }
Henrik Boström933d8b02017-10-10 17:05:163439 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363440}
3441
korniltsev.anatolyec390b52017-07-25 00:00:253442void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3443 MediaStreamInterface* stream) {
3444 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363445 RTC_DCHECK(track);
3446 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253447 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223448 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253449 // We already have a sender for this track, so just change the stream_id
3450 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363451 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253452 return;
3453 }
3454
3455 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363456 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3457 {stream->id()});
Steve Anton57858b32018-02-15 23:19:503458 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223459 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253460 // If the sender has already been configured in SDP, we call SetSsrc,
3461 // which will connect the sender to the underlying transport. This can
3462 // occur if a local session description that contains the ID of the sender
3463 // is set before AddStream is called. It can also occur if the local
3464 // session description is not changed and RemoveStream is called, and
3465 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223466 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183467 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223468 if (sender_info) {
3469 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253470 }
3471}
3472
3473// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3474// indefinitely, when we have unified plan SDP.
3475void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3476 MediaStreamInterface* stream) {
3477 RTC_DCHECK(!IsClosed());
3478 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223479 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253480 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3481 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253482 return;
3483 }
Steve Anton4171afb2017-11-20 18:20:223484 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253485}
3486
3487void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3488 MediaStreamInterface* stream) {
3489 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363490 RTC_DCHECK(track);
3491 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253492 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223493 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253494 // We already have a sender for this track, so just change the stream_id
3495 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363496 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253497 return;
3498 }
3499
3500 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363501 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3502 {stream->id()});
Steve Anton57858b32018-02-15 23:19:503503 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223504 GetVideoTransceiver()->internal()->AddSender(new_sender);
3505 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183506 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223507 if (sender_info) {
3508 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253509 }
3510}
3511
3512void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3513 MediaStreamInterface* stream) {
3514 RTC_DCHECK(!IsClosed());
3515 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223516 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253517 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3518 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253519 return;
3520 }
Steve Anton4171afb2017-11-20 18:20:223521 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253522}
3523
Steve Antonba818672017-11-06 18:21:573524void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283525 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573526 if (ice_connection_state_ == new_state) {
3527 return;
3528 }
3529
deadbeefcbecd352015-09-23 18:50:273530 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573531 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113532 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273533 return;
3534 }
Steve Antonba818672017-11-06 18:21:573535
Mirko Bonadei675513b2017-11-09 10:09:253536 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3537 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573538 RTC_DCHECK(ice_connection_state_ !=
3539 PeerConnectionInterface::kIceConnectionClosed);
3540
henrike@webrtc.org28e20752013-07-10 00:45:363541 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163542 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363543}
3544
3545void PeerConnection::OnIceGatheringChange(
3546 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283547 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363548 if (IsClosed()) {
3549 return;
3550 }
3551 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163552 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363553}
3554
jbauch81bf7b02017-03-25 15:31:123555void PeerConnection::OnIceCandidate(
3556 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283557 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253558 if (IsClosed()) {
3559 return;
3560 }
Harald Alvestrand8ebba742018-05-31 12:00:343561 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:583562 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3563 candidate->candidate().address().IsPrivateIP()) {
3564 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3565 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163566 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363567}
3568
Honghai Zhang7fb69db2016-03-14 18:59:183569void PeerConnection::OnIceCandidatesRemoved(
3570 const std::vector<cricket::Candidate>& candidates) {
3571 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253572 if (IsClosed()) {
3573 return;
3574 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163575 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:183576}
3577
henrike@webrtc.org28e20752013-07-10 00:45:363578void PeerConnection::ChangeSignalingState(
3579 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573580 RTC_DCHECK(signaling_thread()->IsCurrent());
3581 if (signaling_state_ == signaling_state) {
3582 return;
3583 }
Mirko Bonadei675513b2017-11-09 10:09:253584 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3585 << GetSignalingStateString(signaling_state_)
3586 << " New state: "
3587 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363588 signaling_state_ = signaling_state;
3589 if (signaling_state == kClosed) {
3590 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:163591 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363592 if (ice_gathering_state_ != kIceGatheringComplete) {
3593 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:163594 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363595 }
3596 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163597 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363598}
3599
deadbeefeb459812015-12-16 03:24:433600void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3601 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253602 if (IsClosed()) {
3603 return;
3604 }
korniltsev.anatolyec390b52017-07-25 00:00:253605 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163606 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433607}
3608
deadbeefeb459812015-12-16 03:24:433609void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3610 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253611 if (IsClosed()) {
3612 return;
3613 }
korniltsev.anatolyec390b52017-07-25 00:00:253614 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163615 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433616}
3617
3618void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3619 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253620 if (IsClosed()) {
3621 return;
3622 }
korniltsev.anatolyec390b52017-07-25 00:00:253623 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163624 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433625}
3626
3627void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3628 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253629 if (IsClosed()) {
3630 return;
3631 }
korniltsev.anatolyec390b52017-07-25 00:00:253632 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163633 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433634}
3635
Henrik Boström31638672017-11-23 16:48:323636void PeerConnection::PostSetSessionDescriptionSuccess(
3637 SetSessionDescriptionObserver* observer) {
3638 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3639 signaling_thread()->Post(RTC_FROM_HERE, this,
3640 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3641}
3642
deadbeefab9b2d12015-10-14 18:33:113643void PeerConnection::PostSetSessionDescriptionFailure(
3644 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033645 RTCError&& error) {
3646 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113647 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033648 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273649 signaling_thread()->Post(RTC_FROM_HERE, this,
3650 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113651}
3652
3653void PeerConnection::PostCreateSessionDescriptionFailure(
3654 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033655 RTCError error) {
3656 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113657 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033658 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273659 signaling_thread()->Post(RTC_FROM_HERE, this,
3660 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113661}
3662
zhihuang1c378ed2017-08-17 21:10:503663void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543664 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113665 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543666 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503667
Steve Antondcc3c022017-12-23 00:02:543668 if (IsUnifiedPlan()) {
3669 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3670 } else {
3671 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3672 }
3673
Steve Antonfa2260d2017-12-29 00:38:233674 // Intentionally unset the data channel type for RTP data channel with the
3675 // second condition. Otherwise the RTP data channels would be successfully
3676 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3677 // when building with chromium. We want to leave RTP data channels broken, so
3678 // people won't try to use them.
3679 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3680 session_options->data_channel_type = data_channel_type();
3681 }
3682
Steve Antondcc3c022017-12-23 00:02:543683 // Apply ICE restart flag and renomination flag.
3684 for (auto& options : session_options->media_description_options) {
3685 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3686 options.transport_options.enable_ice_renomination =
3687 configuration_.enable_ice_renomination;
3688 }
3689
3690 session_options->rtcp_cname = rtcp_cname_;
3691 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163692 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-23 00:02:543693}
3694
3695void PeerConnection::GetOptionsForPlanBOffer(
3696 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3697 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503698 // Figure out transceiver directional preferences.
3699 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3700 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3701
3702 // By default, generate sendrecv/recvonly m= sections.
3703 bool recv_audio = true;
3704 bool recv_video = true;
3705
3706 // By default, only offer a new m= section if we have media to send with it.
3707 bool offer_new_audio_description = send_audio;
3708 bool offer_new_video_description = send_video;
3709 bool offer_new_data_description = HasDataChannels();
3710
3711 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543712 if (offer_answer_options.offer_to_receive_audio !=
3713 RTCOfferAnswerOptions::kUndefined) {
3714 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503715 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543716 offer_new_audio_description ||
3717 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503718 }
Steve Antondcc3c022017-12-23 00:02:543719 if (offer_answer_options.offer_to_receive_video !=
3720 RTCOfferAnswerOptions::kUndefined) {
3721 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503722 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543723 offer_new_video_description ||
3724 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503725 }
3726
Danil Chapovalov66cadcc2018-06-19 14:47:433727 absl::optional<size_t> audio_index;
3728 absl::optional<size_t> video_index;
3729 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:503730 // If a current description exists, generate m= sections in the same order,
3731 // using the first audio/video/data section that appears and rejecting
3732 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173733 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503734 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173735 local_description(),
Steve Anton1d03a752017-11-27 22:30:093736 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3737 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3738 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113739 }
3740
zhihuang1c378ed2017-08-17 21:10:503741 // Add audio/video/data m= sections to the end if needed.
3742 if (!audio_index && offer_new_audio_description) {
3743 session_options->media_description_options.push_back(
3744 cricket::MediaDescriptionOptions(
3745 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093746 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3747 false));
Oskar Sundbom9b28a032017-11-16 09:53:303748 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453749 }
zhihuang1c378ed2017-08-17 21:10:503750 if (!video_index && offer_new_video_description) {
3751 session_options->media_description_options.push_back(
3752 cricket::MediaDescriptionOptions(
3753 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093754 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3755 false));
Oskar Sundbom9b28a032017-11-16 09:53:303756 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453757 }
zhihuang1c378ed2017-08-17 21:10:503758 if (!data_index && offer_new_data_description) {
3759 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233760 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303761 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503762 }
3763
3764 cricket::MediaDescriptionOptions* audio_media_description_options =
3765 !audio_index ? nullptr
3766 : &session_options->media_description_options[*audio_index];
3767 cricket::MediaDescriptionOptions* video_media_description_options =
3768 !video_index ? nullptr
3769 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503770
Steve Anton4171afb2017-11-20 18:20:223771 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503772 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543773}
3774
3775// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3776// and return a reference to it.
3777// Generated MIDs should be no more than 3 bytes long to take up less space in
3778// the RTP packet.
3779static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3780 RTC_DCHECK(used_mids);
3781 // We're boring: just generate MIDs 0, 1, 2, ...
3782 size_t i = 0;
3783 std::set<std::string>::iterator it;
3784 bool inserted;
3785 do {
3786 std::string mid = rtc::ToString(i++);
3787 auto insert_result = used_mids->insert(mid);
3788 it = insert_result.first;
3789 inserted = insert_result.second;
3790 } while (!inserted);
3791 return *it;
3792}
3793
3794static cricket::MediaDescriptionOptions
3795GetMediaDescriptionOptionsForTransceiver(
3796 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3797 transceiver,
3798 const std::string& mid) {
3799 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083800 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543801 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303802 // This behavior is specified in JSEP. The gist is that:
3803 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3804 // sendrecv.
3805 // 2. If the MSID is included, then it must be included in any subsequent
3806 // offer/answer exactly the same until the RtpTransceiver is stopped.
3807 if (!transceiver->stopped() &&
3808 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3809 transceiver->internal()->has_ever_been_used_to_send())) {
3810 cricket::SenderOptions sender_options;
3811 sender_options.track_id = transceiver->sender()->id();
3812 sender_options.stream_ids = transceiver->sender()->stream_ids();
3813 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3814 // set in the RTP parameters when the transceiver was added.
3815 sender_options.num_sim_layers = 1;
3816 media_description_options.sender_options.push_back(sender_options);
3817 }
Steve Antondcc3c022017-12-23 00:02:543818 return media_description_options;
3819}
3820
3821void PeerConnection::GetOptionsForUnifiedPlanOffer(
3822 const RTCOfferAnswerOptions& offer_answer_options,
3823 cricket::MediaSessionOptions* session_options) {
3824 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3825 // Offers) and 5.2.2 (Subsequent Offers).
3826 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3827 const ContentInfos& local_contents =
3828 (local_description() ? local_description()->description()->contents()
3829 : ContentInfos());
3830 const ContentInfos& remote_contents =
3831 (remote_description() ? remote_description()->description()->contents()
3832 : ContentInfos());
3833 // The mline indices that can be recycled. New transceivers should reuse these
3834 // slots first.
3835 std::queue<size_t> recycleable_mline_indices;
3836 // Track the MIDs used in previous offer/answer exchanges and the current
3837 // offer so that new, unique MIDs are generated.
3838 std::set<std::string> used_mids = seen_mids_;
3839 // First, go through each media section that exists in either the local or
3840 // remote description and generate a media section in this offer for the
3841 // associated transceiver. If a media section can be recycled, generate a
3842 // default, rejected media section here that can be later overwritten.
3843 for (size_t i = 0;
3844 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3845 // Either |local_content| or |remote_content| is non-null.
3846 const ContentInfo* local_content =
3847 (i < local_contents.size() ? &local_contents[i] : nullptr);
3848 const ContentInfo* remote_content =
3849 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3850 bool had_been_rejected = (local_content && local_content->rejected) ||
3851 (remote_content && remote_content->rejected);
3852 const std::string& mid =
3853 (local_content ? local_content->name : remote_content->name);
3854 cricket::MediaType media_type =
3855 (local_content ? local_content->media_description()->type()
3856 : remote_content->media_description()->type());
3857 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3858 media_type == cricket::MEDIA_TYPE_VIDEO) {
3859 auto transceiver = GetAssociatedTransceiver(mid);
3860 RTC_CHECK(transceiver);
3861 // A media section is considered eligible for recycling if it is marked as
3862 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483863 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543864 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083865 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3866 RtpTransceiverDirection::kInactive,
3867 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543868 recycleable_mline_indices.push(i);
3869 } else {
3870 session_options->media_description_options.push_back(
3871 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3872 // CreateOffer shouldn't really cause any state changes in
3873 // PeerConnection, but we need a way to match new transceivers to new
3874 // media sections in SetLocalDescription and JSEP specifies this is done
3875 // by recording the index of the media section generated for the
3876 // transceiver in the offer.
3877 transceiver->internal()->set_mline_index(i);
3878 }
3879 } else {
3880 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233881 RTC_CHECK(GetDataMid());
3882 if (had_been_rejected || mid != *GetDataMid()) {
3883 session_options->media_description_options.push_back(
3884 GetMediaDescriptionOptionsForRejectedData(mid));
3885 } else {
3886 session_options->media_description_options.push_back(
3887 GetMediaDescriptionOptionsForActiveData(mid));
3888 }
Steve Antondcc3c022017-12-23 00:02:543889 }
3890 }
3891 // Next, look for transceivers that are newly added (that is, are not stopped
3892 // and not associated). Reuse media sections marked as recyclable first,
3893 // otherwise append to the end of the offer. New media sections should be
3894 // added in the order they were added to the PeerConnection.
3895 for (auto transceiver : transceivers_) {
3896 if (transceiver->mid() || transceiver->stopped()) {
3897 continue;
3898 }
3899 size_t mline_index;
3900 if (!recycleable_mline_indices.empty()) {
3901 mline_index = recycleable_mline_indices.front();
3902 recycleable_mline_indices.pop();
3903 session_options->media_description_options[mline_index] =
3904 GetMediaDescriptionOptionsForTransceiver(transceiver,
3905 AllocateMid(&used_mids));
3906 } else {
3907 mline_index = session_options->media_description_options.size();
3908 session_options->media_description_options.push_back(
3909 GetMediaDescriptionOptionsForTransceiver(transceiver,
3910 AllocateMid(&used_mids)));
3911 }
3912 // See comment above for why CreateOffer changes the transceiver's state.
3913 transceiver->internal()->set_mline_index(mline_index);
3914 }
Steve Antonfa2260d2017-12-29 00:38:233915 // Lastly, add a m-section if we have local data channels and an m section
3916 // does not already exist.
3917 if (!GetDataMid() && HasDataChannels()) {
3918 session_options->media_description_options.push_back(
3919 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3920 }
Steve Antondcc3c022017-12-23 00:02:543921}
3922
3923void PeerConnection::GetOptionsForAnswer(
3924 const RTCOfferAnswerOptions& offer_answer_options,
3925 cricket::MediaSessionOptions* session_options) {
3926 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3927
3928 if (IsUnifiedPlan()) {
3929 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3930 } else {
3931 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3932 }
3933
Steve Antonfa2260d2017-12-29 00:38:233934 // Intentionally unset the data channel type for RTP data channel. Otherwise
3935 // the RTP data channels would be successfully negotiated by default and the
3936 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3937 // We want to leave RTP data channels broken, so people won't try to use them.
3938 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3939 session_options->data_channel_type = data_channel_type();
3940 }
3941
Steve Antondcc3c022017-12-23 00:02:543942 // Apply ICE renomination flag.
3943 for (auto& options : session_options->media_description_options) {
3944 options.transport_options.enable_ice_renomination =
3945 configuration_.enable_ice_renomination;
3946 }
zhihuang8f65cdf2016-05-07 01:40:303947
3948 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323949 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163950 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 18:33:113951}
3952
Steve Antondcc3c022017-12-23 00:02:543953void PeerConnection::GetOptionsForPlanBAnswer(
3954 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113955 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503956 // Figure out transceiver directional preferences.
3957 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3958 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3959
3960 // By default, generate sendrecv/recvonly m= sections. The direction is also
3961 // restricted by the direction in the offer.
3962 bool recv_audio = true;
3963 bool recv_video = true;
3964
3965 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543966 if (offer_answer_options.offer_to_receive_audio !=
3967 RTCOfferAnswerOptions::kUndefined) {
3968 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523969 }
Steve Antondcc3c022017-12-23 00:02:543970 if (offer_answer_options.offer_to_receive_video !=
3971 RTCOfferAnswerOptions::kUndefined) {
3972 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503973 }
3974
Danil Chapovalov66cadcc2018-06-19 14:47:433975 absl::optional<size_t> audio_index;
3976 absl::optional<size_t> video_index;
3977 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:293978
3979 // Generate m= sections that match those in the offer.
3980 // Note that mediasession.cc will handle intersection our preferred
3981 // direction with the offered direction.
3982 GenerateMediaDescriptionOptions(
3983 remote_description(),
3984 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3985 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3986 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:503987
3988 cricket::MediaDescriptionOptions* audio_media_description_options =
3989 !audio_index ? nullptr
3990 : &session_options->media_description_options[*audio_index];
3991 cricket::MediaDescriptionOptions* video_media_description_options =
3992 !video_index ? nullptr
3993 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503994
Steve Anton4171afb2017-11-20 18:20:223995 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503996 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543997}
zhihuangaf388472016-11-02 23:49:483998
Steve Antondcc3c022017-12-23 00:02:543999void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4000 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4001 cricket::MediaSessionOptions* session_options) {
4002 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4003 // Answers) and 5.3.2 (Subsequent Answers).
4004 RTC_DCHECK(remote_description());
4005 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4006 for (const ContentInfo& content :
4007 remote_description()->description()->contents()) {
4008 cricket::MediaType media_type = content.media_description()->type();
4009 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4010 media_type == cricket::MEDIA_TYPE_VIDEO) {
4011 auto transceiver = GetAssociatedTransceiver(content.name);
4012 RTC_CHECK(transceiver);
4013 session_options->media_description_options.push_back(
4014 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4015 } else {
4016 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:404017 // Reject all data sections if data channels are disabled.
4018 // Reject a data section if it has already been rejected.
4019 // Reject all data sections except for the first one.
4020 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4021 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:234022 session_options->media_description_options.push_back(
4023 GetMediaDescriptionOptionsForRejectedData(content.name));
4024 } else {
4025 session_options->media_description_options.push_back(
4026 GetMediaDescriptionOptionsForActiveData(content.name));
4027 }
Steve Antondcc3c022017-12-23 00:02:544028 }
4029 }
htaa2a49d92016-03-04 10:51:394030}
4031
zhihuang1c378ed2017-08-17 21:10:504032void PeerConnection::GenerateMediaDescriptionOptions(
4033 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:094034 RtpTransceiverDirection audio_direction,
4035 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:434036 absl::optional<size_t>* audio_index,
4037 absl::optional<size_t>* video_index,
4038 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:394039 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504040 for (const cricket::ContentInfo& content :
4041 session_desc->description()->contents()) {
4042 if (IsAudioContent(&content)) {
4043 // If we already have an audio m= section, reject this extra one.
4044 if (*audio_index) {
4045 session_options->media_description_options.push_back(
4046 cricket::MediaDescriptionOptions(
4047 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:094048 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504049 } else {
4050 session_options->media_description_options.push_back(
4051 cricket::MediaDescriptionOptions(
4052 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:094053 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304054 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504055 }
4056 } else if (IsVideoContent(&content)) {
4057 // If we already have an video m= section, reject this extra one.
4058 if (*video_index) {
4059 session_options->media_description_options.push_back(
4060 cricket::MediaDescriptionOptions(
4061 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:094062 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504063 } else {
4064 session_options->media_description_options.push_back(
4065 cricket::MediaDescriptionOptions(
4066 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:094067 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304068 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504069 }
4070 } else {
4071 RTC_DCHECK(IsDataContent(&content));
4072 // If we already have an data m= section, reject this extra one.
4073 if (*data_index) {
4074 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234075 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504076 } else {
4077 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234078 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304079 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504080 }
4081 }
htaa2a49d92016-03-04 10:51:394082 }
deadbeefab9b2d12015-10-14 18:33:114083}
4084
Steve Antonfa2260d2017-12-29 00:38:234085cricket::MediaDescriptionOptions
4086PeerConnection::GetMediaDescriptionOptionsForActiveData(
4087 const std::string& mid) const {
4088 // Direction for data sections is meaningless, but legacy endpoints might
4089 // expect sendrecv.
4090 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4091 RtpTransceiverDirection::kSendRecv,
4092 /*stopped=*/false);
4093 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4094 return options;
4095}
4096
4097cricket::MediaDescriptionOptions
4098PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4099 const std::string& mid) const {
4100 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4101 RtpTransceiverDirection::kInactive,
4102 /*stopped=*/true);
4103 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4104 return options;
4105}
4106
Danil Chapovalov66cadcc2018-06-19 14:47:434107absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234108 switch (data_channel_type_) {
4109 case cricket::DCT_RTP:
4110 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434111 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234112 }
4113 return rtp_data_channel_->content_name();
4114 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354115 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:234116 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434117 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234118 }
4119}
4120
Steve Anton4171afb2017-11-20 18:20:224121void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4122 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4123 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404124 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074125}
4126
Steve Anton4171afb2017-11-20 18:20:224127void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114128 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224129 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114130 cricket::MediaType media_type,
4131 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364132 RTC_DCHECK(!IsUnifiedPlan());
4133
Steve Anton4171afb2017-11-20 18:20:224134 std::vector<RtpSenderInfo>* current_senders =
4135 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114136
Steve Anton4171afb2017-11-20 18:20:224137 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014138 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224139 for (auto sender_it = current_senders->begin();
4140 sender_it != current_senders->end();
4141 /* incremented manually */) {
4142 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114143 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224144 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094145 std::string params_stream_id;
4146 if (params) {
4147 params_stream_id =
4148 (!params->first_stream_id().empty() ? params->first_stream_id()
4149 : kDefaultStreamId);
4150 }
Seth Hampson5b4f0752018-04-02 23:31:364151 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094152 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404153 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104154 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224155 sender_exists) {
4156 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404157 } else {
Steve Anton4171afb2017-11-20 18:20:224158 OnRemoteSenderRemoved(info, media_type);
4159 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114160 }
4161 }
4162
Steve Anton4171afb2017-11-20 18:20:224163 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114164 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334165 if (!params.has_ssrcs()) {
4166 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4167 // sender, this means it is coming from a Unified Plan endpoint,so we just
4168 // create a default.
4169 default_sender_needed = true;
4170 break;
4171 }
4172
Seth Hampson845e8782018-03-02 19:34:104173 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364174 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334175 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4176 // not supported in Plan B, we just take the first here and create the
4177 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104178 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094179 (!params.first_stream_id().empty() ? params.first_stream_id()
4180 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224181 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114182 uint32_t ssrc = params.first_ssrc();
4183
4184 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104185 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114186 if (!stream) {
4187 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194188 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104189 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114190 remote_streams_->AddStream(stream);
4191 new_streams->AddStream(stream);
4192 }
4193
Steve Anton4171afb2017-11-20 18:20:224194 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184195 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224196 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104197 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224198 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114199 }
4200 }
deadbeefbda7e0b2015-12-09 01:13:404201
Steve Anton4171afb2017-11-20 18:20:224202 // Add default sender if necessary.
4203 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404204 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104205 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404206 if (!default_stream) {
4207 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194208 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104209 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404210 remote_streams_->AddStream(default_stream);
4211 new_streams->AddStream(default_stream);
4212 }
Steve Anton4171afb2017-11-20 18:20:224213 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4214 ? kDefaultAudioSenderId
4215 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104216 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184217 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224218 if (!default_sender_info) {
4219 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104220 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224221 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404222 }
4223 }
deadbeefab9b2d12015-10-14 18:33:114224}
4225
Steve Anton4171afb2017-11-20 18:20:224226void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4227 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234228 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4229 << " receiver for track_id=" << sender_info.sender_id
4230 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114231
Steve Anton3d954a62018-04-02 18:27:234232 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114233 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224234 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114235 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224236 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114237 } else {
nisseeb4ca4e2017-01-12 10:24:274238 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114239 }
4240}
4241
Steve Anton4171afb2017-11-20 18:20:224242void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4243 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094244 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4245 << " receiver for track_id=" << sender_info.sender_id
4246 << " and stream_id=" << sender_info.stream_id;
4247
Seth Hampson845e8782018-03-02 19:34:104248 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114249
Henrik Boström933d8b02017-10-10 17:05:164250 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114251 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194252 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4253 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224254 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114255 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224256 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114257 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114258 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114259 }
4260 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194261 // Stopping or destroying a VideoRtpReceiver will end the
4262 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224263 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114264 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224265 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114266 if (video_track) {
perkjd61bf802016-03-24 10:16:194267 // There's no guarantee the track is still available, e.g. the track may
4268 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114269 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114270 }
4271 } else {
nisseede5da42017-01-12 13:15:364272 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114273 }
Henrik Boström933d8b02017-10-10 17:05:164274 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164275 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164276 }
deadbeefab9b2d12015-10-14 18:33:114277}
4278
4279void PeerConnection::UpdateEndedRemoteMediaStreams() {
4280 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4281 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4282 MediaStreamInterface* stream = remote_streams_->at(i);
4283 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4284 streams_to_remove.push_back(stream);
4285 }
4286 }
4287
Taylor Brandstetter98cde262016-05-31 20:02:214288 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114289 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164290 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114291 }
4292}
4293
Steve Anton4171afb2017-11-20 18:20:224294void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114295 const std::vector<cricket::StreamParams>& streams,
4296 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224297 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114298
Seth Hampson845e8782018-03-02 19:34:104299 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114300 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224301 for (auto sender_it = current_senders->begin();
4302 sender_it != current_senders->end();
4303 /* incremented manually */) {
4304 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114305 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224306 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4307 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104308 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224309 OnLocalSenderRemoved(info, media_type);
4310 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114311 } else {
Steve Anton4171afb2017-11-20 18:20:224312 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114313 }
4314 }
4315
Steve Anton4171afb2017-11-20 18:20:224316 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114317 for (const cricket::StreamParams& params : streams) {
4318 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224319 // sender id.
Seth Hampson845e8782018-03-02 19:34:104320 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224321 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114322 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224323 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184324 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224325 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104326 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224327 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114328 }
4329 }
4330}
4331
Steve Anton4171afb2017-11-20 18:20:224332void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4333 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364334 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224335 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014336 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224337 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4338 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254339 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114340 return;
4341 }
4342
deadbeeffac06552015-11-25 19:26:014343 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254344 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074345 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014346 return;
deadbeefab9b2d12015-10-14 18:33:114347 }
deadbeeffac06552015-11-25 19:26:014348
Seth Hampson5b4f0752018-04-02 23:31:364349 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224350 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114351}
4352
Steve Anton4171afb2017-11-20 18:20:224353void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4354 cricket::MediaType media_type) {
4355 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014356 if (!sender) {
4357 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114358 // SessionDescriptions has been renegotiated.
4359 return;
4360 }
deadbeeffac06552015-11-25 19:26:014361
4362 // A sender has been removed from the SessionDescription but it's still
4363 // associated with the PeerConnection. This only occurs if the SDP doesn't
4364 // match with the calls to CreateSender, AddStream and RemoveStream.
4365 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254366 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074367 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014368 return;
deadbeefab9b2d12015-10-14 18:33:114369 }
deadbeeffac06552015-11-25 19:26:014370
Steve Anton4171afb2017-11-20 18:20:224371 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114372}
4373
4374void PeerConnection::UpdateLocalRtpDataChannels(
4375 const cricket::StreamParamsVec& streams) {
4376 std::vector<std::string> existing_channels;
4377
4378 // Find new and active data channels.
4379 for (const cricket::StreamParams& params : streams) {
4380 // |it->sync_label| is actually the data channel label. The reason is that
4381 // we use the same naming of data channels as we do for
4382 // MediaStreams and Tracks.
4383 // For MediaStreams, the sync_label is the MediaStream label and the
4384 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104385 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114386 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564387 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254388 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114389 continue;
4390 }
4391 // Set the SSRC the data channel should use for sending.
4392 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4393 existing_channels.push_back(data_channel_it->first);
4394 }
4395
4396 UpdateClosingRtpDataChannels(existing_channels, true);
4397}
4398
4399void PeerConnection::UpdateRemoteRtpDataChannels(
4400 const cricket::StreamParamsVec& streams) {
4401 std::vector<std::string> existing_channels;
4402
4403 // Find new and active data channels.
4404 for (const cricket::StreamParams& params : streams) {
4405 // The data channel label is either the mslabel or the SSRC if the mslabel
4406 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104407 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114408 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104409 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114410 auto data_channel_it = rtp_data_channels_.find(label);
4411 if (data_channel_it == rtp_data_channels_.end()) {
4412 // This is a new data channel.
4413 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4414 } else {
4415 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4416 }
4417 existing_channels.push_back(label);
4418 }
4419
4420 UpdateClosingRtpDataChannels(existing_channels, false);
4421}
4422
4423void PeerConnection::UpdateClosingRtpDataChannels(
4424 const std::vector<std::string>& active_channels,
4425 bool is_local_update) {
4426 auto it = rtp_data_channels_.begin();
4427 while (it != rtp_data_channels_.end()) {
4428 DataChannel* data_channel = it->second;
4429 if (std::find(active_channels.begin(), active_channels.end(),
4430 data_channel->label()) != active_channels.end()) {
4431 ++it;
4432 continue;
4433 }
4434
4435 if (is_local_update) {
4436 data_channel->SetSendSsrc(0);
4437 } else {
4438 data_channel->RemotePeerRequestClose();
4439 }
4440
4441 if (data_channel->state() == DataChannel::kClosed) {
4442 rtp_data_channels_.erase(it);
4443 it = rtp_data_channels_.begin();
4444 } else {
4445 ++it;
4446 }
4447 }
4448}
4449
4450void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4451 uint32_t remote_ssrc) {
4452 rtc::scoped_refptr<DataChannel> channel(
4453 InternalCreateDataChannel(label, nullptr));
4454 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254455 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074456 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114457 return;
4458 }
4459 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394460 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4461 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164462 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114463}
4464
4465rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4466 const std::string& label,
4467 const InternalDataChannelInit* config) {
4468 if (IsClosed()) {
4469 return nullptr;
4470 }
Steve Anton75737c02017-11-06 18:37:174471 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254472 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114473 << "InternalCreateDataChannel: Data is not supported in this call.";
4474 return nullptr;
4475 }
4476 InternalDataChannelInit new_config =
4477 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:174478 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:114479 if (new_config.id < 0) {
4480 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174481 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114482 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254483 RTC_LOG(LS_ERROR)
4484 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114485 return nullptr;
4486 }
4487 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254488 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074489 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114490 return nullptr;
4491 }
4492 }
4493
Steve Anton75737c02017-11-06 18:37:174494 rtc::scoped_refptr<DataChannel> channel(
4495 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114496 if (!channel) {
4497 sid_allocator_.ReleaseSid(new_config.id);
4498 return nullptr;
4499 }
4500
4501 if (channel->data_channel_type() == cricket::DCT_RTP) {
4502 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254503 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4504 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114505 return nullptr;
4506 }
4507 rtp_data_channels_[channel->label()] = channel;
4508 } else {
4509 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4510 sctp_data_channels_.push_back(channel);
4511 channel->SignalClosed.connect(this,
4512 &PeerConnection::OnSctpDataChannelClosed);
4513 }
4514
Steve Anton2d8609c2018-01-24 00:38:464515 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114516 return channel;
4517}
4518
4519bool PeerConnection::HasDataChannels() const {
4520 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4521}
4522
4523void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4524 for (const auto& channel : sctp_data_channels_) {
4525 if (channel->id() < 0) {
4526 int sid;
4527 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254528 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114529 continue;
4530 }
4531 channel->SetSctpSid(sid);
4532 }
4533 }
4534}
4535
4536void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294537 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114538 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4539 ++it) {
4540 if (it->get() == channel) {
4541 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:324542 // After the closing procedure is done, it's safe to use this ID for
4543 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114544 sid_allocator_.ReleaseSid(channel->id());
4545 }
deadbeefbd292462015-12-15 02:15:294546 // Since this method is triggered by a signal from the DataChannel,
4547 // we can't free it directly here; we need to free it asynchronously.
4548 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114549 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 21:17:274550 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4551 nullptr);
deadbeefab9b2d12015-10-14 18:33:114552 return;
4553 }
4554 }
4555}
4556
deadbeefab9b2d12015-10-14 18:33:114557void PeerConnection::OnDataChannelDestroyed() {
4558 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4559 // DataChannel may callback to us and try to modify the list.
4560 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4561 temp_rtp_dcs.swap(rtp_data_channels_);
4562 for (const auto& kv : temp_rtp_dcs) {
4563 kv.second->OnTransportChannelDestroyed();
4564 }
4565
4566 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4567 temp_sctp_dcs.swap(sctp_data_channels_);
4568 for (const auto& channel : temp_sctp_dcs) {
4569 channel->OnTransportChannelDestroyed();
4570 }
4571}
4572
4573void PeerConnection::OnDataChannelOpenMessage(
4574 const std::string& label,
4575 const InternalDataChannelInit& config) {
4576 rtc::scoped_refptr<DataChannel> channel(
4577 InternalCreateDataChannel(label, &config));
4578 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254579 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114580 return;
4581 }
4582
deadbeefa601f5c2016-06-06 21:27:394583 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4584 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164585 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:414586 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:114587}
4588
Steve Anton4171afb2017-11-20 18:20:224589rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4590PeerConnection::GetAudioTransceiver() const {
4591 // This method only works with Plan B SDP, where there is a single
4592 // audio/video transceiver.
4593 RTC_DCHECK(!IsUnifiedPlan());
4594 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084595 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224596 return transceiver;
4597 }
4598 }
4599 RTC_NOTREACHED();
4600 return nullptr;
4601}
4602
4603rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4604PeerConnection::GetVideoTransceiver() const {
4605 // This method only works with Plan B SDP, where there is a single
4606 // audio/video transceiver.
4607 RTC_DCHECK(!IsUnifiedPlan());
4608 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084609 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224610 return transceiver;
4611 }
4612 }
4613 RTC_NOTREACHED();
4614 return nullptr;
4615}
4616
4617// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4618// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504619bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224620 switch (type) {
4621 case cricket::MEDIA_TYPE_AUDIO:
4622 return !GetAudioTransceiver()->internal()->senders().empty();
4623 case cricket::MEDIA_TYPE_VIDEO:
4624 return !GetVideoTransceiver()->internal()->senders().empty();
4625 case cricket::MEDIA_TYPE_DATA:
4626 return false;
4627 }
4628 RTC_NOTREACHED();
4629 return false;
zhihuang1c378ed2017-08-17 21:10:504630}
4631
Steve Anton4171afb2017-11-20 18:20:224632rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4633PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4634 for (auto transceiver : transceivers_) {
4635 for (auto sender : transceiver->internal()->senders()) {
4636 if (sender->track() == track) {
4637 return sender;
4638 }
4639 }
4640 }
4641 return nullptr;
deadbeeffac06552015-11-25 19:26:014642}
4643
Steve Anton4171afb2017-11-20 18:20:224644rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4645PeerConnection::FindSenderById(const std::string& sender_id) const {
4646 for (auto transceiver : transceivers_) {
4647 for (auto sender : transceiver->internal()->senders()) {
4648 if (sender->id() == sender_id) {
4649 return sender;
4650 }
4651 }
4652 }
4653 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554654}
4655
Steve Anton4171afb2017-11-20 18:20:224656rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4657PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4658 for (auto transceiver : transceivers_) {
4659 for (auto receiver : transceiver->internal()->receivers()) {
4660 if (receiver->id() == receiver_id) {
4661 return receiver;
4662 }
4663 }
4664 }
4665 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554666}
4667
Steve Anton4171afb2017-11-20 18:20:224668std::vector<PeerConnection::RtpSenderInfo>*
4669PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4670 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4671 media_type == cricket::MEDIA_TYPE_VIDEO);
4672 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4673 ? &remote_audio_sender_infos_
4674 : &remote_video_sender_infos_;
4675}
4676
4677std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114678 cricket::MediaType media_type) {
4679 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4680 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224681 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4682 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114683}
4684
Steve Anton4171afb2017-11-20 18:20:224685const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4686 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184687 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224688 const std::string sender_id) const {
4689 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184690 if (sender_info.stream_id == stream_id &&
4691 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224692 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114693 }
4694 }
4695 return nullptr;
4696}
4697
4698DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4699 for (const auto& channel : sctp_data_channels_) {
4700 if (channel->id() == sid) {
4701 return channel;
4702 }
4703 }
4704 return nullptr;
4705}
4706
deadbeef91dd5672016-05-18 23:55:304707bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:074708 const cricket::ServerAddresses& stun_servers,
4709 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:114710 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-28 00:20:154711 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114712 // To handle both internal and externally created port allocator, we will
4713 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454714 port_allocator_flags_ = port_allocator_->flags();
4715 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4716 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4717 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114718 // If the disable-IPv6 flag was specified, we'll not override it
4719 // by experiment.
4720 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454721 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474722 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4723 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454724 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114725 }
4726
zhihuangb09b3f92017-03-07 22:40:514727 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:454728 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254729 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514730 }
4731
Taylor Brandstettera1c30352016-05-13 15:15:114732 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:454733 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254734 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114735 }
4736
honghaiz60347052016-06-01 01:29:124737 if (configuration.candidate_network_policy ==
4738 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:454739 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254740 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124741 }
4742
Daniel Lazarenko2870b0a2018-01-25 09:30:224743 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:454744 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224745 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4746 }
4747
Qingsi Wanga2d60672018-04-11 23:57:454748 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:114749 // No step delay is used while allocating ports.
4750 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4751 port_allocator_->set_candidate_filter(
4752 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114753 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114754
Harald Alvestrandb2a74782018-06-28 11:54:074755 auto turn_servers_copy = turn_servers;
Benjamin Wrightd6f86e82018-05-08 20:12:254756 if (tls_cert_verifier_ != nullptr) {
Harald Alvestrandb2a74782018-06-28 11:54:074757 for (auto& turn_server : turn_servers_copy) {
Benjamin Wrightd6f86e82018-05-08 20:12:254758 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4759 }
4760 }
Taylor Brandstettera1c30352016-05-13 15:15:114761 // Call this last since it may create pooled allocator sessions using the
4762 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494763 port_allocator_->SetConfiguration(
Harald Alvestrandb2a74782018-06-28 11:54:074764 stun_servers, turn_servers_copy, configuration.ice_candidate_pool_size,
Qingsi Wangdb53f8e2018-02-20 22:45:494765 configuration.prune_turn_ports, configuration.turn_customizer,
4766 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114767 return true;
4768}
4769
deadbeef91dd5672016-05-18 23:55:304770bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304771 const cricket::ServerAddresses& stun_servers,
4772 const std::vector<cricket::RelayServerConfig>& turn_servers,
4773 IceTransportsType type,
4774 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404775 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494776 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 14:47:434777 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114778 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304779 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:454780 // According to JSEP, after setLocalDescription, changing the candidate pool
4781 // size is not allowed, and changing the set of ICE servers will not result
4782 // in new candidates being gathered.
4783 if (local_description()) {
4784 port_allocator_->FreezeCandidatePool();
4785 }
Taylor Brandstettera1c30352016-05-13 15:15:114786 // Call this last since it may create pooled allocator sessions using the
4787 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324788 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 12:01:404789 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494790 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114791}
4792
Steve Antonba818672017-11-06 18:21:574793cricket::ChannelManager* PeerConnection::channel_manager() const {
4794 return factory_->channel_manager();
4795}
4796
Elad Alon99c3fe52017-10-13 14:29:404797bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144798 std::unique_ptr<RtcEventLogOutput> output,
4799 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164800 if (!event_log_) {
4801 return false;
4802 }
Bjorn Tereliusde939432017-11-20 16:38:144803 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554804}
4805
4806void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164807 if (event_log_) {
4808 event_log_->StopLogging();
4809 }
ivoc14d5dbe2016-07-04 14:06:554810}
nisseeaabdf62017-05-05 09:23:024811
Steve Anton75737c02017-11-06 18:37:174812cricket::BaseChannel* PeerConnection::GetChannel(
4813 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544814 for (auto transceiver : transceivers_) {
4815 cricket::BaseChannel* channel = transceiver->internal()->channel();
4816 if (channel && channel->content_name() == content_name) {
4817 return channel;
4818 }
Steve Anton75737c02017-11-06 18:37:174819 }
4820 if (rtp_data_channel() &&
4821 rtp_data_channel()->content_name() == content_name) {
4822 return rtp_data_channel();
4823 }
4824 return nullptr;
4825}
4826
4827bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4828 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254829 RTC_LOG(LS_INFO)
4830 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074831 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174832 return false;
4833 }
4834 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254835 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074836 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174837 return false;
4838 }
4839
Zhi Huange830e682018-03-30 17:48:354840 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4841 if (dtls_role) {
4842 *role = *dtls_role;
4843 return true;
4844 }
4845 return false;
Steve Anton75737c02017-11-06 18:37:174846}
4847
4848bool PeerConnection::GetSslRole(const std::string& content_name,
4849 rtc::SSLRole* role) {
4850 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254851 RTC_LOG(LS_INFO)
4852 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074853 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174854 return false;
4855 }
4856
Zhi Huange830e682018-03-30 17:48:354857 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4858 if (dtls_role) {
4859 *role = *dtls_role;
4860 return true;
4861 }
4862 return false;
Steve Anton75737c02017-11-06 18:37:174863}
4864
Steve Antonf8470812017-12-04 18:46:214865void PeerConnection::SetSessionError(SessionError error,
4866 const std::string& error_desc) {
4867 RTC_DCHECK_RUN_ON(signaling_thread());
4868 if (error != session_error_) {
4869 session_error_ = error;
4870 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174871 }
4872}
4873
Zhi Huange830e682018-03-30 17:48:354874RTCError PeerConnection::UpdateSessionState(
4875 SdpType type,
4876 cricket::ContentSource source,
4877 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:564878 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174879
4880 // If there's already a pending error then no state transition should happen.
4881 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214882 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474883
Steve Anton6d6a2ae2017-12-05 01:19:474884 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514885 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594886 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474887 }
4888
4889 // Update the signaling state according to the specified state machine (see
4890 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514891 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474892 ChangeSignalingState(source == cricket::CS_LOCAL
4893 ? PeerConnectionInterface::kHaveLocalOffer
4894 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514895 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474896 ChangeSignalingState(source == cricket::CS_LOCAL
4897 ? PeerConnectionInterface::kHaveLocalPrAnswer
4898 : PeerConnectionInterface::kHaveRemotePrAnswer);
4899 } else {
Steve Anton3828c062017-12-06 18:34:514900 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474901 ChangeSignalingState(PeerConnectionInterface::kStable);
4902 }
4903
4904 // Update internal objects according to the session description's media
4905 // descriptions.
Zhi Huange830e682018-03-30 17:48:354906 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474907 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:424908 return error;
Steve Anton6d6a2ae2017-12-05 01:19:474909 }
4910
Steve Anton8a006912017-12-04 23:25:564911 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174912}
4913
Steve Anton8a006912017-12-04 23:25:564914RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514915 SdpType type,
Steve Anton8a006912017-12-04 23:25:564916 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594917 const SessionDescriptionInterface* sdesc =
4918 (source == cricket::CS_LOCAL ? local_description()
4919 : remote_description());
Steve Anton75737c02017-11-06 18:37:174920 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594921
4922 // Push down the new SDP media section for each audio/video transceiver.
4923 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174924 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594925 FindMediaSectionForTransceiver(transceiver, sdesc);
4926 cricket::BaseChannel* channel = transceiver->internal()->channel();
4927 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174928 continue;
4929 }
4930 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304931 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594932 if (!content_desc) {
4933 continue;
4934 }
4935 std::string error;
Yves Gerey665174f2018-06-19 13:03:054936 bool success = (source == cricket::CS_LOCAL)
4937 ? channel->SetLocalContent(content_desc, type, &error)
4938 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594939 if (!success) {
4940 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4941 }
4942 }
4943
4944 // If using the RtpDataChannel, push down the new SDP section for it too.
4945 if (rtp_data_channel_) {
4946 const ContentInfo* data_content =
4947 cricket::GetFirstDataContent(sdesc->description());
4948 if (data_content && !data_content->rejected) {
4949 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304950 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594951 if (data_desc) {
4952 std::string error;
4953 bool success =
4954 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514955 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:054956 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594957 if (!success) {
4958 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4959 std::move(error));
4960 }
Steve Anton75737c02017-11-06 18:37:174961 }
4962 }
4963 }
Steve Antoned10bd92017-12-05 18:52:594964
Steve Anton75737c02017-11-06 18:37:174965 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4966 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4967 if (sctp_transport_ && local_description() && remote_description() &&
4968 cricket::GetFirstDataContent(local_description()->description()) &&
4969 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564970 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174971 RTC_FROM_HERE,
4972 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564973 if (!success) {
4974 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4975 "Failed to push down SCTP parameters.");
4976 }
Steve Anton75737c02017-11-06 18:37:174977 }
Steve Antoned10bd92017-12-05 18:52:594978
Steve Anton8a006912017-12-04 23:25:564979 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174980}
4981
4982bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4983 RTC_DCHECK(network_thread()->IsCurrent());
4984 RTC_DCHECK(local_description());
4985 RTC_DCHECK(remote_description());
4986 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4987 // When we support "max-message-size", that would also be pushed down here.
4988 return sctp_transport_->Start(
4989 GetSctpPort(local_description()->description()),
4990 GetSctpPort(remote_description()->description()));
4991}
4992
Steve Anton8a006912017-12-04 23:25:564993RTCError PeerConnection::PushdownTransportDescription(
4994 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514995 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564996 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174997
Zhi Huange830e682018-03-30 17:48:354998 if (source == cricket::CS_LOCAL) {
4999 const SessionDescriptionInterface* sdesc = local_description();
5000 RTC_DCHECK(sdesc);
5001 return transport_controller_->SetLocalDescription(type,
5002 sdesc->description());
5003 } else {
5004 const SessionDescriptionInterface* sdesc = remote_description();
5005 RTC_DCHECK(sdesc);
5006 return transport_controller_->SetRemoteDescription(type,
5007 sdesc->description());
Steve Anton75737c02017-11-06 18:37:175008 }
Steve Anton75737c02017-11-06 18:37:175009}
5010
5011bool PeerConnection::GetTransportDescription(
5012 const SessionDescription* description,
5013 const std::string& content_name,
5014 cricket::TransportDescription* tdesc) {
5015 if (!description || !tdesc) {
5016 return false;
5017 }
5018 const TransportInfo* transport_info =
5019 description->GetTransportInfoByName(content_name);
5020 if (!transport_info) {
5021 return false;
5022 }
5023 *tdesc = transport_info->description;
5024 return true;
5025}
5026
Steve Anton75737c02017-11-06 18:37:175027cricket::IceConfig PeerConnection::ParseIceConfig(
5028 const PeerConnectionInterface::RTCConfiguration& config) const {
5029 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:175030 switch (config.continual_gathering_policy) {
5031 case PeerConnectionInterface::GATHER_ONCE:
5032 gathering_policy = cricket::GATHER_ONCE;
5033 break;
5034 case PeerConnectionInterface::GATHER_CONTINUALLY:
5035 gathering_policy = cricket::GATHER_CONTINUALLY;
5036 break;
5037 default:
5038 RTC_NOTREACHED();
5039 gathering_policy = cricket::GATHER_ONCE;
5040 }
Qingsi Wang9a5c6f82018-02-01 18:38:405041
Steve Anton75737c02017-11-06 18:37:175042 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235043 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5044 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175045 ice_config.prioritize_most_likely_candidate_pairs =
5046 config.prioritize_most_likely_ice_candidate_pairs;
5047 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:235048 RTCConfigurationToIceConfigOptionalInt(
5049 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175050 ice_config.continual_gathering_policy = gathering_policy;
5051 ice_config.presume_writable_when_fully_relayed =
5052 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:145053 ice_config.ice_check_interval_strong_connectivity =
5054 config.ice_check_interval_strong_connectivity;
5055 ice_config.ice_check_interval_weak_connectivity =
5056 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:175057 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:495058 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175059 ice_config.regather_all_networks_interval_range =
5060 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405061 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175062 return ice_config;
5063}
5064
Steve Anton75737c02017-11-06 18:37:175065bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5066 std::string* track_id) {
5067 if (!local_description()) {
5068 return false;
5069 }
5070 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5071 track_id);
5072}
5073
5074bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5075 std::string* track_id) {
5076 if (!remote_description()) {
5077 return false;
5078 }
5079 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5080 track_id);
5081}
5082
5083bool PeerConnection::SendData(const cricket::SendDataParams& params,
5084 const rtc::CopyOnWriteBuffer& payload,
5085 cricket::SendDataResult* result) {
5086 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255087 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 09:37:075088 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175089 return false;
5090 }
5091 return rtp_data_channel_
5092 ? rtp_data_channel_->SendData(params, payload, result)
5093 : network_thread()->Invoke<bool>(
5094 RTC_FROM_HERE,
5095 Bind(&cricket::SctpTransportInternal::SendData,
5096 sctp_transport_.get(), params, payload, result));
5097}
5098
5099bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5100 if (!rtp_data_channel_ && !sctp_transport_) {
5101 // Don't log an error here, because DataChannels are expected to call
5102 // ConnectDataChannel in this state. It's the only way to initially tell
5103 // whether or not the underlying transport is ready.
5104 return false;
5105 }
5106 if (rtp_data_channel_) {
5107 rtp_data_channel_->SignalReadyToSendData.connect(
5108 webrtc_data_channel, &DataChannel::OnChannelReady);
5109 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5110 &DataChannel::OnDataReceived);
5111 } else {
5112 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5113 &DataChannel::OnChannelReady);
5114 SignalSctpDataReceived.connect(webrtc_data_channel,
5115 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325116 SignalSctpClosingProcedureStartedRemotely.connect(
5117 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5118 SignalSctpClosingProcedureComplete.connect(
5119 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175120 }
5121 return true;
5122}
5123
5124void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5125 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255126 RTC_LOG(LS_ERROR)
5127 << "DisconnectDataChannel called when rtp_data_channel_ and "
5128 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175129 return;
5130 }
5131 if (rtp_data_channel_) {
5132 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5133 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5134 } else {
5135 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5136 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325137 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5138 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175139 }
5140}
5141
5142void PeerConnection::AddSctpDataStream(int sid) {
5143 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255144 RTC_LOG(LS_ERROR)
5145 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175146 return;
5147 }
5148 network_thread()->Invoke<void>(
5149 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5150 sctp_transport_.get(), sid));
5151}
5152
5153void PeerConnection::RemoveSctpDataStream(int sid) {
5154 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255155 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075156 "NULL.";
Steve Anton75737c02017-11-06 18:37:175157 return;
5158 }
5159 network_thread()->Invoke<void>(
5160 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5161 sctp_transport_.get(), sid));
5162}
5163
5164bool PeerConnection::ReadyToSendData() const {
5165 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5166 sctp_ready_to_send_data_;
5167}
5168
Danil Chapovalov66cadcc2018-06-19 14:47:435169absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 17:48:355170 if (sctp_mid_ && transport_controller_) {
5171 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5172 if (dtls_transport) {
5173 return dtls_transport->transport_name();
5174 }
Danil Chapovalov66cadcc2018-06-19 14:47:435175 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355176 }
Danil Chapovalov66cadcc2018-06-19 14:47:435177 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355178}
5179
Qingsi Wang72a43a12018-02-21 00:03:185180cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5181 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455182 network_thread()->Invoke<void>(
5183 RTC_FROM_HERE,
5184 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5185 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185186 return candidate_states_list;
5187}
5188
Steve Anton5dfde182018-02-06 18:34:405189std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5190 const {
5191 std::map<std::string, std::string> transport_names_by_mid;
5192 for (auto transceiver : transceivers_) {
5193 cricket::BaseChannel* channel = transceiver->internal()->channel();
5194 if (channel) {
5195 transport_names_by_mid[channel->content_name()] =
5196 channel->transport_name();
5197 }
Steve Anton75737c02017-11-06 18:37:175198 }
Steve Anton5dfde182018-02-06 18:34:405199 if (rtp_data_channel_) {
5200 transport_names_by_mid[rtp_data_channel_->content_name()] =
5201 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175202 }
5203 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435204 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355205 RTC_DCHECK(transport_name);
5206 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175207 }
Steve Anton5dfde182018-02-06 18:34:405208 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175209}
5210
Steve Anton5dfde182018-02-06 18:34:405211std::map<std::string, cricket::TransportStats>
5212PeerConnection::GetTransportStatsByNames(
5213 const std::set<std::string>& transport_names) {
5214 if (!network_thread()->IsCurrent()) {
5215 return network_thread()
5216 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5217 RTC_FROM_HERE,
5218 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175219 }
Steve Anton5dfde182018-02-06 18:34:405220 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5221 for (const std::string& transport_name : transport_names) {
5222 cricket::TransportStats transport_stats;
5223 bool success =
5224 transport_controller_->GetStats(transport_name, &transport_stats);
5225 if (success) {
5226 transport_stats_by_name[transport_name] = std::move(transport_stats);
5227 } else {
5228 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5229 << transport_name;
5230 }
5231 }
5232 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175233}
5234
5235bool PeerConnection::GetLocalCertificate(
5236 const std::string& transport_name,
5237 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355238 if (!certificate) {
5239 return false;
5240 }
5241 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5242 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175243}
5244
Taylor Brandstetterc3928662018-02-23 21:04:515245std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175246 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515247 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175248}
5249
5250cricket::DataChannelType PeerConnection::data_channel_type() const {
5251 return data_channel_type_;
5252}
5253
5254bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5255 return pending_ice_restarts_.find(content_name) !=
5256 pending_ice_restarts_.end();
5257}
5258
Steve Anton75737c02017-11-06 18:37:175259bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5260 return transport_controller_->NeedsIceRestart(content_name);
5261}
5262
5263void PeerConnection::OnCertificateReady(
5264 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5265 transport_controller_->SetLocalCertificate(certificate);
5266}
5267
5268void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215269 SetSessionError(SessionError::kTransport,
5270 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175271}
5272
5273void PeerConnection::OnTransportControllerConnectionState(
5274 cricket::IceConnectionState state) {
5275 switch (state) {
5276 case cricket::kIceConnectionConnecting:
5277 // If the current state is Connected or Completed, then there were
5278 // writable channels but now there are not, so the next state must
5279 // be Disconnected.
5280 // kIceConnectionConnecting is currently used as the default,
5281 // un-connected state by the TransportController, so its only use is
5282 // detecting disconnections.
5283 if (ice_connection_state_ ==
5284 PeerConnectionInterface::kIceConnectionConnected ||
5285 ice_connection_state_ ==
5286 PeerConnectionInterface::kIceConnectionCompleted) {
5287 SetIceConnectionState(
5288 PeerConnectionInterface::kIceConnectionDisconnected);
5289 }
5290 break;
5291 case cricket::kIceConnectionFailed:
5292 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5293 break;
5294 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:255295 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 09:37:075296 "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:175297 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 12:00:345298 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 18:37:175299 break;
5300 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:255301 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 09:37:075302 "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:175303 if (ice_connection_state_ !=
5304 PeerConnectionInterface::kIceConnectionConnected) {
5305 // If jumping directly from "checking" to "connected",
5306 // signal "connected" first.
5307 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5308 }
5309 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 12:00:345310 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 19:54:535311 ReportTransportStats();
Steve Anton75737c02017-11-06 18:37:175312 break;
5313 default:
5314 RTC_NOTREACHED();
5315 }
5316}
5317
5318void PeerConnection::OnTransportControllerCandidatesGathered(
5319 const std::string& transport_name,
5320 const cricket::Candidates& candidates) {
5321 RTC_DCHECK(signaling_thread()->IsCurrent());
5322 int sdp_mline_index;
5323 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255324 RTC_LOG(LS_ERROR)
5325 << "OnTransportControllerCandidatesGathered: content name "
5326 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175327 return;
5328 }
5329
5330 for (cricket::Candidates::const_iterator citer = candidates.begin();
5331 citer != candidates.end(); ++citer) {
5332 // Use transport_name as the candidate media id.
5333 std::unique_ptr<JsepIceCandidate> candidate(
5334 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5335 if (local_description()) {
5336 mutable_local_description()->AddCandidate(candidate.get());
5337 }
5338 OnIceCandidate(std::move(candidate));
5339 }
5340}
5341
5342void PeerConnection::OnTransportControllerCandidatesRemoved(
5343 const std::vector<cricket::Candidate>& candidates) {
5344 RTC_DCHECK(signaling_thread()->IsCurrent());
5345 // Sanity check.
5346 for (const cricket::Candidate& candidate : candidates) {
5347 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255348 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075349 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255350 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175351 return;
5352 }
5353 }
5354
5355 if (local_description()) {
5356 mutable_local_description()->RemoveCandidates(candidates);
5357 }
5358 OnIceCandidatesRemoved(candidates);
5359}
5360
5361void PeerConnection::OnTransportControllerDtlsHandshakeError(
5362 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:535363 RTC_HISTOGRAM_ENUMERATION(
5364 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5365 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:175366}
5367
Steve Antoned10bd92017-12-05 18:52:595368void PeerConnection::EnableSending() {
5369 for (auto transceiver : transceivers_) {
5370 cricket::BaseChannel* channel = transceiver->internal()->channel();
5371 if (channel && !channel->enabled()) {
5372 channel->Enable(true);
5373 }
Steve Anton75737c02017-11-06 18:37:175374 }
5375
Steve Anton4171afb2017-11-20 18:20:225376 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175377 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225378 }
Steve Anton75737c02017-11-06 18:37:175379}
5380
5381// Returns the media index for a local ice candidate given the content name.
5382bool PeerConnection::GetLocalCandidateMediaIndex(
5383 const std::string& content_name,
5384 int* sdp_mline_index) {
5385 if (!local_description() || !sdp_mline_index) {
5386 return false;
5387 }
5388
5389 bool content_found = false;
5390 const ContentInfos& contents = local_description()->description()->contents();
5391 for (size_t index = 0; index < contents.size(); ++index) {
5392 if (contents[index].name == content_name) {
5393 *sdp_mline_index = static_cast<int>(index);
5394 content_found = true;
5395 break;
5396 }
5397 }
5398 return content_found;
5399}
5400
5401bool PeerConnection::UseCandidatesInSessionDescription(
5402 const SessionDescriptionInterface* remote_desc) {
5403 if (!remote_desc) {
5404 return true;
5405 }
5406 bool ret = true;
5407
5408 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5409 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5410 for (size_t n = 0; n < candidates->count(); ++n) {
5411 const IceCandidateInterface* candidate = candidates->at(n);
5412 bool valid = false;
5413 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5414 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255415 RTC_LOG(LS_INFO)
5416 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075417 "candidate.";
Steve Anton75737c02017-11-06 18:37:175418 }
5419 continue;
5420 }
5421 ret = UseCandidate(candidate);
5422 if (!ret) {
5423 break;
5424 }
5425 }
5426 }
5427 return ret;
5428}
5429
5430bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5431 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5432 size_t remote_content_size =
5433 remote_description()->description()->contents().size();
5434 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255435 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175436 return false;
5437 }
5438
5439 cricket::ContentInfo content =
5440 remote_description()->description()->contents()[mediacontent_index];
5441 std::vector<cricket::Candidate> candidates;
5442 candidates.push_back(candidate->candidate());
5443 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355444 RTCError error =
5445 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505446 if (error.ok()) {
5447 // Candidates successfully submitted for checking.
5448 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5449 ice_connection_state_ ==
5450 PeerConnectionInterface::kIceConnectionDisconnected) {
5451 // If state is New, then the session has just gotten its first remote ICE
5452 // candidates, so go to Checking.
5453 // If state is Disconnected, the session is re-using old candidates or
5454 // receiving additional ones, so go to Checking.
5455 // If state is Connected, stay Connected.
5456 // TODO(bemasc): If state is Connected, and the new candidates are for a
5457 // newly added transport, then the state actually _should_ move to
5458 // checking. Add a way to distinguish that case.
5459 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5460 }
5461 // TODO(bemasc): If state is Completed, go back to Connected.
5462 } else if (error.message()) {
Zhi Huange830e682018-03-30 17:48:355463 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175464 }
5465 return true;
5466}
5467
5468void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175469 // Destroy video channel first since it may have a pointer to the
5470 // voice channel.
5471 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295472 if (!video_info || video_info->rejected) {
5473 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175474 }
5475
Steve Anton6fec8802017-12-04 18:37:295476 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5477 if (!audio_info || audio_info->rejected) {
5478 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175479 }
5480
5481 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5482 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295483 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175484 }
5485}
5486
Steve Antondcc3c022017-12-23 00:02:545487RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5488 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175489 const cricket::ContentGroup* bundle_group = nullptr;
5490 if (configuration_.bundle_policy ==
5491 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545492 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175493 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565494 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5495 "max-bundle configured but session description "
5496 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175497 }
5498 }
Steve Antondcc3c022017-12-23 00:02:545499 return std::move(bundle_group);
5500}
5501
5502RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355503 // Creating the media channels. Transports should already have been created
5504 // at this point.
Steve Antondcc3c022017-12-23 00:02:545505 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555506 if (voice && !voice->rejected &&
5507 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355508 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555509 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565510 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5511 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555512 }
5513 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5514 }
5515
Steve Antondcc3c022017-12-23 00:02:545516 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555517 if (video && !video->rejected &&
5518 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355519 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555520 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565521 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5522 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175523 }
Steve Antoneda6ccd2017-12-04 18:21:555524 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175525 }
5526
Steve Antondcc3c022017-12-23 00:02:545527 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175528 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5529 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355530 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565531 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5532 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175533 }
5534 }
5535
Steve Anton8a006912017-12-04 23:25:565536 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175537}
5538
Steve Anton4171afb2017-11-20 18:20:225539// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555540cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355541 const std::string& mid) {
5542 RtpTransportInternal* rtp_transport =
5543 transport_controller_->GetRtpTransport(mid);
5544 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175545 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355546 call_.get(), configuration_.media_config, rtp_transport,
5547 signaling_thread(), mid, SrtpRequired(),
5548 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 18:37:175549 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555550 return nullptr;
Steve Anton75737c02017-11-06 18:37:175551 }
Steve Anton75737c02017-11-06 18:37:175552 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5553 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175554 voice_channel->SignalSentPacket.connect(this,
5555 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355556 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225557
Steve Antoneda6ccd2017-12-04 18:21:555558 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175559}
5560
Steve Anton4171afb2017-11-20 18:20:225561// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555562cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355563 const std::string& mid) {
5564 RtpTransportInternal* rtp_transport =
5565 transport_controller_->GetRtpTransport(mid);
5566 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175567 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355568 call_.get(), configuration_.media_config, rtp_transport,
5569 signaling_thread(), mid, SrtpRequired(),
5570 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 18:37:175571 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555572 return nullptr;
Steve Anton75737c02017-11-06 18:37:175573 }
Steve Anton75737c02017-11-06 18:37:175574 video_channel->SignalDtlsSrtpSetupFailure.connect(
5575 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175576 video_channel->SignalSentPacket.connect(this,
5577 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355578 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225579
Steve Antoneda6ccd2017-12-04 18:21:555580 return video_channel;
Steve Anton75737c02017-11-06 18:37:175581}
5582
Zhi Huange830e682018-03-30 17:48:355583bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175584 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5585 if (sctp) {
5586 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255587 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175588 << "Trying to create SCTP transport, but didn't compile with "
5589 "SCTP support (HAVE_SCTP)";
5590 return false;
5591 }
5592 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 17:48:355593 RTC_FROM_HERE,
5594 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 18:37:175595 return false;
5596 }
Steve Antoneda6ccd2017-12-04 18:21:555597 for (const auto& channel : sctp_data_channels_) {
5598 channel->OnTransportChannelCreated();
5599 }
Steve Anton75737c02017-11-06 18:37:175600 } else {
Zhi Huange830e682018-03-30 17:48:355601 RtpTransportInternal* rtp_transport =
5602 transport_controller_->GetRtpTransport(mid);
5603 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175604 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 17:48:355605 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5606 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 18:37:175607 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175608 return false;
5609 }
Steve Anton75737c02017-11-06 18:37:175610 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5611 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5612 rtp_data_channel_->SignalSentPacket.connect(
5613 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355614 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175615 }
5616
Steve Anton75737c02017-11-06 18:37:175617 return true;
5618}
5619
5620Call::Stats PeerConnection::GetCallStats() {
5621 if (!worker_thread()->IsCurrent()) {
5622 return worker_thread()->Invoke<Call::Stats>(
5623 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5624 }
5625 if (call_) {
5626 return call_->GetStats();
5627 } else {
5628 return Call::Stats();
5629 }
5630}
5631
Zhi Huange830e682018-03-30 17:48:355632bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175633 RTC_DCHECK(network_thread()->IsCurrent());
5634 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265635 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355636 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265637 RTC_DCHECK(dtls_transport);
5638 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175639 RTC_DCHECK(sctp_transport_);
5640 sctp_invoker_.reset(new rtc::AsyncInvoker());
5641 sctp_transport_->SignalReadyToSendData.connect(
5642 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5643 sctp_transport_->SignalDataReceived.connect(
5644 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:325645 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5646 // another thread. Would be nice if there was a helper class similar to
5647 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5648 // code.
5649 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5650 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5651 sctp_transport_->SignalClosingProcedureComplete.connect(
5652 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:355653 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265654 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355655 return true;
Steve Anton75737c02017-11-06 18:37:175656}
5657
5658void PeerConnection::DestroySctpTransport_n() {
5659 RTC_DCHECK(network_thread()->IsCurrent());
5660 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355661 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175662 sctp_invoker_.reset(nullptr);
5663 sctp_ready_to_send_data_ = false;
5664}
5665
5666void PeerConnection::OnSctpTransportReadyToSendData_n() {
5667 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5668 RTC_DCHECK(network_thread()->IsCurrent());
5669 // Note: Cannot use rtc::Bind here because it will grab a reference to
5670 // PeerConnection and potentially cause PeerConnection to live longer than
5671 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5672 // be destroyed before PeerConnection is destroyed, and at that point all
5673 // pending tasks will be cleared.
5674 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5675 OnSctpTransportReadyToSendData_s(true);
5676 });
5677}
5678
5679void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5680 RTC_DCHECK(signaling_thread()->IsCurrent());
5681 sctp_ready_to_send_data_ = ready;
5682 SignalSctpReadyToSendData(ready);
5683}
5684
5685void PeerConnection::OnSctpTransportDataReceived_n(
5686 const cricket::ReceiveDataParams& params,
5687 const rtc::CopyOnWriteBuffer& payload) {
5688 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5689 RTC_DCHECK(network_thread()->IsCurrent());
5690 // Note: Cannot use rtc::Bind here because it will grab a reference to
5691 // PeerConnection and potentially cause PeerConnection to live longer than
5692 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5693 // be destroyed before PeerConnection is destroyed, and at that point all
5694 // pending tasks will be cleared.
5695 sctp_invoker_->AsyncInvoke<void>(
5696 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5697 OnSctpTransportDataReceived_s(params, payload);
5698 });
5699}
5700
5701void PeerConnection::OnSctpTransportDataReceived_s(
5702 const cricket::ReceiveDataParams& params,
5703 const rtc::CopyOnWriteBuffer& payload) {
5704 RTC_DCHECK(signaling_thread()->IsCurrent());
5705 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5706 // Received OPEN message; parse and signal that a new data channel should
5707 // be created.
5708 std::string label;
5709 InternalDataChannelInit config;
5710 config.id = params.ssrc;
5711 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255712 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5713 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175714 return;
5715 }
5716 config.open_handshake_role = InternalDataChannelInit::kAcker;
5717 OnDataChannelOpenMessage(label, config);
5718 } else {
5719 // Otherwise just forward the signal.
5720 SignalSctpDataReceived(params, payload);
5721 }
5722}
5723
Taylor Brandstettercdd05f02018-05-31 20:23:325724void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:175725 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5726 RTC_DCHECK(network_thread()->IsCurrent());
5727 sctp_invoker_->AsyncInvoke<void>(
5728 RTC_FROM_HERE, signaling_thread(),
5729 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:325730 &SignalSctpClosingProcedureStartedRemotely, sid));
5731}
5732
5733void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5734 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5735 RTC_DCHECK(network_thread()->IsCurrent());
5736 sctp_invoker_->AsyncInvoke<void>(
5737 RTC_FROM_HERE, signaling_thread(),
5738 rtc::Bind(&sigslot::signal1<int>::operator(),
5739 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:175740}
5741
5742// Returns false if bundle is enabled and rtcp_mux is disabled.
5743bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5744 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5745 if (!bundle_enabled)
5746 return true;
5747
5748 const cricket::ContentGroup* bundle_group =
5749 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5750 RTC_DCHECK(bundle_group != NULL);
5751
5752 const cricket::ContentInfos& contents = desc->contents();
5753 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5754 citer != contents.end(); ++citer) {
5755 const cricket::ContentInfo* content = (&*citer);
5756 RTC_DCHECK(content != NULL);
5757 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005758 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175759 if (!HasRtcpMuxEnabled(content))
5760 return false;
5761 }
5762 }
5763 // RTCP-MUX is enabled in all the contents.
5764 return true;
5765}
5766
5767bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305768 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175769}
5770
Steve Anton8a006912017-12-04 23:25:565771RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175772 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565773 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215774 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565775 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175776 }
5777
5778 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565779 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175780 }
5781
Steve Anton3828c062017-12-06 18:34:515782 SdpType type = sdesc->GetType();
5783 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5784 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565785 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:035786 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:565787 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175788 }
5789
5790 // Verify crypto settings.
5791 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565792 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5793 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:535794 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:565795 if (!crypto_error.ok()) {
5796 return crypto_error;
5797 }
Steve Anton75737c02017-11-06 18:37:175798 }
5799
5800 // Verify ice-ufrag and ice-pwd.
5801 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565802 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5803 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175804 }
5805
5806 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565807 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5808 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175809 }
5810
5811 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5812 // m-lines that do not rtcp-mux enabled.
5813
5814 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515815 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:485816 // With an answer we want to compare the new answer session description with
5817 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:175818 const cricket::SessionDescription* offer_desc =
5819 (source == cricket::CS_LOCAL) ? remote_description()->description()
5820 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:485821 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5822 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5823 type)) {
Steve Anton8a006912017-12-04 23:25:565824 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5825 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175826 }
5827 } else {
Steve Anton75737c02017-11-06 18:37:175828 // The re-offers should respect the order of m= sections in current
5829 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:485830 // With a re-offer, either the current local or current remote descriptions
5831 // could be the most up to date, so we would like to check against both of
5832 // them if they exist. It could be the case that one of them has a 0 port
5833 // for a media section, but the other does not. This is important to check
5834 // against in the case that we are recycling an m= section.
5835 const cricket::SessionDescription* current_desc = nullptr;
5836 const cricket::SessionDescription* secondary_current_desc = nullptr;
5837 if (local_description()) {
5838 current_desc = local_description()->description();
5839 if (remote_description()) {
5840 secondary_current_desc = remote_description()->description();
5841 }
5842 } else if (remote_description()) {
5843 current_desc = remote_description()->description();
5844 }
Steve Anton75737c02017-11-06 18:37:175845 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:485846 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5847 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:565848 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5849 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175850 }
5851 }
5852
Steve Antonba42e992018-04-09 21:10:015853 if (IsUnifiedPlan()) {
5854 // Ensure that each audio and video media section has at most one
5855 // "StreamParams". This will return an error if receiving a session
5856 // description from a "Plan B" endpoint which adds multiple tracks of the
5857 // same type. With Unified Plan, there can only be at most one track per
5858 // media section.
5859 for (const ContentInfo& content : sdesc->description()->contents()) {
5860 const MediaContentDescription& desc = *content.description;
5861 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5862 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5863 desc.streams().size() > 1u) {
5864 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5865 "Media section has more than one track specified "
5866 "with a=ssrc lines which is not supported with "
5867 "Unified Plan.");
5868 }
5869 }
5870 }
5871
Steve Anton8a006912017-12-04 23:25:565872 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175873}
5874
Steve Anton3828c062017-12-06 18:34:515875bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175876 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515877 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175878 return (state == PeerConnectionInterface::kStable) ||
5879 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525880 } else {
Steve Anton3828c062017-12-06 18:34:515881 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175882 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5883 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5884 }
5885}
5886
Steve Anton3828c062017-12-06 18:34:515887bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175888 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515889 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175890 return (state == PeerConnectionInterface::kStable) ||
5891 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525892 } else {
Steve Anton3828c062017-12-06 18:34:515893 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175894 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5895 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5896 }
5897}
5898
Steve Antonf8470812017-12-04 18:46:215899const char* PeerConnection::SessionErrorToString(SessionError error) const {
5900 switch (error) {
5901 case SessionError::kNone:
5902 return "ERROR_NONE";
5903 case SessionError::kContent:
5904 return "ERROR_CONTENT";
5905 case SessionError::kTransport:
5906 return "ERROR_TRANSPORT";
5907 }
5908 RTC_NOTREACHED();
5909 return "";
5910}
5911
Steve Anton75737c02017-11-06 18:37:175912std::string PeerConnection::GetSessionErrorMsg() {
5913 std::ostringstream desc;
Steve Antonf8470812017-12-04 18:46:215914 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5915 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 18:37:175916 return desc.str();
5917}
5918
Steve Anton8e20f172018-03-06 18:55:045919void PeerConnection::ReportSdpFormatReceived(
5920 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:045921 int num_audio_mlines = 0;
5922 int num_video_mlines = 0;
5923 int num_audio_tracks = 0;
5924 int num_video_tracks = 0;
5925 for (const ContentInfo& content : remote_offer.description()->contents()) {
5926 cricket::MediaType media_type = content.media_description()->type();
5927 int num_tracks = std::max(
5928 1, static_cast<int>(content.media_description()->streams().size()));
5929 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5930 num_audio_mlines += 1;
5931 num_audio_tracks += num_tracks;
5932 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5933 num_video_mlines += 1;
5934 num_video_tracks += num_tracks;
5935 }
5936 }
5937 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5938 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5939 format = kSdpFormatReceivedComplexUnifiedPlan;
5940 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5941 format = kSdpFormatReceivedComplexPlanB;
5942 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5943 format = kSdpFormatReceivedSimple;
5944 }
Qingsi Wang7fc821d2018-07-12 19:54:535945 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5946 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:045947}
5948
Harald Alvestrand8ebba742018-05-31 12:00:345949void PeerConnection::NoteUsageEvent(UsageEvent event) {
5950 RTC_DCHECK_RUN_ON(signaling_thread());
5951 usage_event_accumulator_ |= static_cast<int>(event);
5952}
5953
5954void PeerConnection::ReportUsagePattern() const {
5955 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:535956 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5957 usage_event_accumulator_,
5958 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:555959 const int bad_bits =
5960 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5961 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5962 const int good_bits =
5963 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5964 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5965 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5966 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5967 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:165968 // If called after close(), we can't report, because observer may have
5969 // been deallocated, and therefore pointer is null. Write to log instead.
5970 if (observer_) {
5971 Observer()->OnInterestingUsage(usage_event_accumulator_);
5972 } else {
5973 RTC_LOG(LS_INFO) << "Interesting usage signature "
5974 << usage_event_accumulator_
5975 << " observed after observer shutdown";
5976 }
Harald Alvestrandc0e97252018-07-26 08:39:555977 }
Harald Alvestrand8ebba742018-05-31 12:00:345978}
5979
Steve Anton0ffaaa22018-02-23 18:31:305980void PeerConnection::ReportNegotiatedSdpSemantics(
5981 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:535982 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:305983 switch (answer.description()->msid_signaling()) {
5984 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:535985 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:305986 break;
5987 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:535988 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:305989 break;
5990 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:535991 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:305992 break;
5993 case cricket::kMsidSignalingMediaSection |
5994 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:535995 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:305996 break;
5997 default:
5998 RTC_NOTREACHED();
5999 }
Qingsi Wang7fc821d2018-07-12 19:54:536000 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6001 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:306002}
6003
Steve Anton75737c02017-11-06 18:37:176004// We need to check the local/remote description for the Transport instead of
6005// the session, because a new Transport added during renegotiation may have
6006// them unset while the session has them set from the previous negotiation.
6007// Not doing so may trigger the auto generation of transport description and
6008// mess up DTLS identity information, ICE credential, etc.
6009bool PeerConnection::ReadyToUseRemoteCandidate(
6010 const IceCandidateInterface* candidate,
6011 const SessionDescriptionInterface* remote_desc,
6012 bool* valid) {
6013 *valid = true;
6014
6015 const SessionDescriptionInterface* current_remote_desc =
6016 remote_desc ? remote_desc : remote_description();
6017
6018 if (!current_remote_desc) {
6019 return false;
6020 }
6021
6022 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6023 size_t remote_content_size =
6024 current_remote_desc->description()->contents().size();
6025 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:256026 RTC_LOG(LS_ERROR)
6027 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6028 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176029
6030 *valid = false;
6031 return false;
6032 }
6033
6034 cricket::ContentInfo content =
6035 current_remote_desc->description()->contents()[mediacontent_index];
6036
6037 const std::string transport_name = GetTransportName(content.name);
6038 if (transport_name.empty()) {
6039 return false;
6040 }
Zhi Huange830e682018-03-30 17:48:356041 return true;
Steve Anton75737c02017-11-06 18:37:176042}
6043
6044bool PeerConnection::SrtpRequired() const {
6045 return dtls_enabled_ ||
6046 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6047}
6048
6049void PeerConnection::OnTransportControllerGatheringState(
6050 cricket::IceGatheringState state) {
6051 RTC_DCHECK(signaling_thread()->IsCurrent());
6052 if (state == cricket::kIceGatheringGathering) {
6053 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6054 } else if (state == cricket::kIceGatheringComplete) {
6055 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6056 }
6057}
6058
6059void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:456060 std::map<std::string, std::set<cricket::MediaType>>
6061 media_types_by_transport_name;
6062 for (auto transceiver : transceivers_) {
6063 if (transceiver->internal()->channel()) {
6064 const std::string& transport_name =
6065 transceiver->internal()->channel()->transport_name();
6066 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086067 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456068 }
Steve Anton75737c02017-11-06 18:37:176069 }
6070 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456071 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6072 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176073 }
Zhi Huange830e682018-03-30 17:48:356074
Danil Chapovalov66cadcc2018-06-19 14:47:436075 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356076 if (transport_name) {
6077 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456078 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176079 }
Zhi Huange830e682018-03-30 17:48:356080
Steve Antonc7b964c2018-02-01 22:39:456081 for (const auto& entry : media_types_by_transport_name) {
6082 const std::string& transport_name = entry.first;
6083 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176084 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456085 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176086 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456087 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176088 }
6089 }
6090}
6091// Walk through the ConnectionInfos to gather best connection usage
6092// for IPv4 and IPv6.
6093void PeerConnection::ReportBestConnectionState(
6094 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:456095 for (const cricket::TransportChannelStats& channel_stats :
6096 stats.channel_stats) {
6097 for (const cricket::ConnectionInfo& connection_info :
6098 channel_stats.connection_infos) {
6099 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176100 continue;
6101 }
6102
Steve Antonc7b964c2018-02-01 22:39:456103 const cricket::Candidate& local = connection_info.local_candidate;
6104 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176105
6106 // Increment the counter for IceCandidatePairType.
6107 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6108 (local.type() == RELAY_PORT_TYPE &&
6109 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:536110 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6111 GetIceCandidatePairCounter(local, remote),
6112 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176113 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536114 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6115 GetIceCandidatePairCounter(local, remote),
6116 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176117 } else {
6118 RTC_CHECK(0);
6119 }
Steve Anton75737c02017-11-06 18:37:176120
6121 // Increment the counter for IP type.
6122 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536123 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6124 kBestConnections_IPv4,
6125 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176126 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536127 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6128 kBestConnections_IPv6,
6129 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176130 } else {
6131 RTC_CHECK(0);
6132 }
6133
6134 return;
6135 }
6136 }
6137}
6138
6139void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456140 const cricket::TransportStats& stats,
6141 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176142 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6143 return;
6144 }
6145
6146 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6147 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6148 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6149 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6150 return;
6151 }
6152
Qingsi Wang7fc821d2018-07-12 19:54:536153 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6154 for (cricket::MediaType media_type : media_types) {
6155 switch (media_type) {
6156 case cricket::MEDIA_TYPE_AUDIO:
6157 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6158 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6159 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6160 break;
6161 case cricket::MEDIA_TYPE_VIDEO:
6162 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6163 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6164 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6165 break;
6166 case cricket::MEDIA_TYPE_DATA:
6167 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6168 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6169 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6170 break;
6171 default:
6172 RTC_NOTREACHED();
6173 continue;
6174 }
Steve Antonc7b964c2018-02-01 22:39:456175 }
Qingsi Wang7fc821d2018-07-12 19:54:536176 }
6177
6178 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6179 for (cricket::MediaType media_type : media_types) {
6180 switch (media_type) {
6181 case cricket::MEDIA_TYPE_AUDIO:
6182 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6183 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6184 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6185 break;
6186 case cricket::MEDIA_TYPE_VIDEO:
6187 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6188 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6189 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6190 break;
6191 case cricket::MEDIA_TYPE_DATA:
6192 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6193 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6194 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6195 break;
6196 default:
6197 RTC_NOTREACHED();
6198 continue;
6199 }
Steve Antonc7b964c2018-02-01 22:39:456200 }
Steve Anton75737c02017-11-06 18:37:176201 }
6202}
6203
6204void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6205 RTC_DCHECK(worker_thread()->IsCurrent());
6206 RTC_DCHECK(call_);
6207 call_->OnSentPacket(sent_packet);
6208}
6209
6210const std::string PeerConnection::GetTransportName(
6211 const std::string& content_name) {
6212 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296213 if (channel) {
6214 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176215 }
Steve Anton6fec8802017-12-04 18:37:296216 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356217 RTC_DCHECK(sctp_mid_);
6218 if (content_name == *sctp_mid_) {
6219 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296220 }
6221 }
6222 // Return an empty string if failed to retrieve the transport name.
6223 return "";
Steve Anton75737c02017-11-06 18:37:176224}
6225
Steve Anton6fec8802017-12-04 18:37:296226void PeerConnection::DestroyTransceiverChannel(
6227 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6228 transceiver) {
6229 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176230
Steve Anton6fec8802017-12-04 18:37:296231 cricket::BaseChannel* channel = transceiver->internal()->channel();
6232 if (channel) {
6233 transceiver->internal()->SetChannel(nullptr);
6234 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:176235 }
6236}
6237
6238void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296239 if (rtp_data_channel_) {
6240 OnDataChannelDestroyed();
6241 DestroyBaseChannel(rtp_data_channel_);
6242 rtp_data_channel_ = nullptr;
6243 }
6244
6245 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6246 // grab a reference to this PeerConnection. If this is called from the
6247 // PeerConnection destructor, the RefCountedObject vtable will have already
6248 // been destroyed (since it is a subclass of PeerConnection) and using
6249 // rtc::Bind will cause "Pure virtual function called" error to appear.
6250
6251 if (sctp_transport_) {
6252 OnDataChannelDestroyed();
6253 network_thread()->Invoke<void>(RTC_FROM_HERE,
6254 [this] { DestroySctpTransport_n(); });
6255 }
6256}
6257
6258void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6259 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296260 switch (channel->media_type()) {
6261 case cricket::MEDIA_TYPE_AUDIO:
6262 channel_manager()->DestroyVoiceChannel(
6263 static_cast<cricket::VoiceChannel*>(channel));
6264 break;
6265 case cricket::MEDIA_TYPE_VIDEO:
6266 channel_manager()->DestroyVideoChannel(
6267 static_cast<cricket::VideoChannel*>(channel));
6268 break;
6269 case cricket::MEDIA_TYPE_DATA:
6270 channel_manager()->DestroyRtpDataChannel(
6271 static_cast<cricket::RtpDataChannel*>(channel));
6272 break;
6273 default:
6274 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6275 break;
6276 }
Zhi Huange830e682018-03-30 17:48:356277}
Steve Anton6fec8802017-12-04 18:37:296278
Taylor Brandstettercbaa2542018-04-16 23:42:146279bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356280 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146281 RtpTransportInternal* rtp_transport,
6282 cricket::DtlsTransportInternal* dtls_transport) {
6283 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356284 auto base_channel = GetChannel(mid);
6285 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146286 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356287 }
Taylor Brandstettercbaa2542018-04-16 23:42:146288 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266289 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176290 }
Taylor Brandstettercbaa2542018-04-16 23:42:146291 return ret;
Steve Anton75737c02017-11-06 18:37:176292}
6293
Harald Alvestrand7a1c7f72018-08-01 08:50:166294PeerConnectionObserver* PeerConnection::Observer() const {
6295 // In earlier production code, the pointer was not cleared on close,
6296 // which might have led to undefined behavior if the observer was not
6297 // deallocated, or strange crashes if it was.
6298 // We use CHECK in order to catch such behavior if it exists.
6299 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6300 RTC_CHECK(observer_);
6301 return observer_;
6302}
6303
Harald Alvestrand89061872018-01-02 13:08:346304void PeerConnection::ClearStatsCache() {
6305 if (stats_collector_) {
6306 stats_collector_->ClearCachedStatsReport();
6307 }
6308}
6309
Harald Alvestrand7a1c7f72018-08-01 08:50:166310void PeerConnection::RequestUsagePatternReportForTesting() {
6311 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6312 nullptr);
6313}
6314
henrike@webrtc.org28e20752013-07-10 00:45:366315} // namespace webrtc