blob: 9549c428303d3b3f87258dd9d568b6708e3ace13 [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"
Mirko Bonadei92ea95e2017-09-15 04:47:3123#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 13:39:2425#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3126#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"
Jonas Olsson366a50c2018-09-06 11:41:3051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3152#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 19:54:5356#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3657
Steve Anton75737c02017-11-06 18:37:1758using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1763using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 18:21:5770namespace webrtc {
71
Steve Anton75737c02017-11-06 18:37:1772// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1776const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1784const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:3695
Steve Anton75737c02017-11-06 18:37:1796namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3697
Seth Hampson845e8782018-03-02 19:34:1098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2299static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11101
zhihuang8f65cdf2016-05-07 01:40:30102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 10:03:50114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 18:33:11142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 23:05:28148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25150 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 19:49:08156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 18:33:11166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 21:10:50172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 13:50:32179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 08:58:37189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50191 }
192 }
zhihuanga77e6bb2017-08-15 01:17:48193 }
zhihuang1c378ed2017-08-17 21:10:50194}
olka3c747662017-08-17 13:50:32195
zhihuang1c378ed2017-08-17 21:10:50196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 18:33:11204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 18:33:11213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 15:15:11217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 13:56:46229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 20:28:30234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 22:59:59242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 17:22:52243 bool ok = error.ok();
Steve Anton038834f2017-07-14 22:59:59244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 17:22:52247 return ok;
Steve Anton038834f2017-07-14 22:59:59248}
249
Steve Antonba818672017-11-06 18:21:57250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 18:38:28269
Steve Anton75737c02017-11-06 18:37:17270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 23:33:48327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 18:37:17342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 18:37:17356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 23:33:48359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-23 00:02:54370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 23:33:48372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 18:37:17380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 23:33:48386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17389}
390
Qingsi Wang7fc821d2018-07-12 19:54:53391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 19:54:53415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26417
Mirko Bonadeiab499822018-09-11 08:43:20418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 13:15:26424 }
425}
426
Harald Alvestrand76829d72018-07-18 21:24:36427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 18:37:17432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 19:54:53438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17443 continue;
444 }
Harald Alvestrand2e180612018-03-07 09:56:14445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 19:54:53448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17479 }
480 }
481 }
Steve Anton8a006912017-12-04 23:25:56482 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17493 continue;
494 }
Steve Anton8a006912017-12-04 23:25:56495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 23:14:30526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 23:14:30536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17555 return -1;
556 }
Steve Anton75737c02017-11-06 18:37:17557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 18:37:17571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 18:37:17598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-17 01:08:42603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 11:41:30608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32611 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42612}
613
Seth Hampson5b4f0752018-04-02 23:31:36614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 14:47:43625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43629 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 19:23:22634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Steve Anton75737c02017-11-06 18:37:17663} // namespace
664
Henrik Boström31638672017-11-23 16:48:32665// Upon completion, posts a task to execute the callback of the
666// SetSessionDescriptionObserver asynchronously on the same thread. At this
667// point, the state of the peer connection might no longer reflect the effects
668// of the SetRemoteDescription operation, as the peer connection could have been
669// modified during the post.
670// TODO(hbos): Remove this class once we remove the version of
671// PeerConnectionInterface::SetRemoteDescription() that takes a
672// SetSessionDescriptionObserver as an argument.
673class PeerConnection::SetRemoteDescriptionObserverAdapter
674 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
675 public:
676 SetRemoteDescriptionObserverAdapter(
677 rtc::scoped_refptr<PeerConnection> pc,
678 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
679 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
680
681 // SetRemoteDescriptionObserverInterface implementation.
682 void OnSetRemoteDescriptionComplete(RTCError error) override {
683 if (error.ok())
684 pc_->PostSetSessionDescriptionSuccess(wrapper_);
685 else
Harald Alvestrand5081c0c2018-03-09 14:18:03686 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32687 }
688
689 private:
690 rtc::scoped_refptr<PeerConnection> pc_;
691 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
692};
693
deadbeef293e9262017-01-11 20:28:30694bool PeerConnectionInterface::RTCConfiguration::operator==(
695 const PeerConnectionInterface::RTCConfiguration& o) const {
696 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10697 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30698 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56699 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10700 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30701 BundlePolicy bundle_policy;
702 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10703 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
704 int ice_candidate_pool_size;
705 bool disable_ipv6;
706 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11707 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22708 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10709 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43710 absl::optional<int> screencast_min_bitrate;
711 absl::optional<bool> combined_audio_video_bwe;
712 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30713 TcpCandidatePolicy tcp_candidate_policy;
714 CandidateNetworkPolicy candidate_network_policy;
715 int audio_jitter_buffer_max_packets;
716 bool audio_jitter_buffer_fast_accelerate;
717 int ice_connection_receiving_timeout;
718 int ice_backup_candidate_pair_ping_interval;
719 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30720 bool prioritize_most_likely_ice_candidate_pairs;
721 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30722 bool prune_turn_ports;
723 bool presume_writable_when_fully_relayed;
724 bool enable_ice_renomination;
725 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 14:47:43726 absl::optional<int> ice_check_interval_strong_connectivity;
727 absl::optional<int> ice_check_interval_weak_connectivity;
728 absl::optional<int> ice_check_min_interval;
729 absl::optional<int> ice_unwritable_timeout;
730 absl::optional<int> ice_unwritable_min_checks;
731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 17:16:44739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
753 ice_connection_receiving_timeout ==
754 o.ice_connection_receiving_timeout &&
755 ice_backup_candidate_pair_ping_interval ==
756 o.ice_backup_candidate_pair_ping_interval &&
757 continual_gathering_policy == o.continual_gathering_policy &&
758 certificates == o.certificates &&
759 prioritize_most_likely_ice_candidate_pairs ==
760 o.prioritize_most_likely_ice_candidate_pairs &&
761 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51762 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11763 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22764 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30765 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30766 screencast_min_bitrate == o.screencast_min_bitrate &&
767 combined_audio_video_bwe == o.combined_audio_video_bwe &&
768 enable_dtls_srtp == o.enable_dtls_srtp &&
769 ice_candidate_pool_size == o.ice_candidate_pool_size &&
770 prune_turn_ports == o.prune_turn_ports &&
771 presume_writable_when_fully_relayed ==
772 o.presume_writable_when_fully_relayed &&
773 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14774 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14775 ice_check_interval_strong_connectivity ==
776 o.ice_check_interval_strong_connectivity &&
777 ice_check_interval_weak_connectivity ==
778 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10779 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57780 ice_unwritable_timeout == o.ice_unwritable_timeout &&
781 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49782 stun_candidate_keepalive_interval ==
783 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40784 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56785 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40786 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11787 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21788 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44789 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48790 use_media_transport_for_data_channels ==
791 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 09:25:48792 crypto_options == o.crypto_options &&
793 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30794}
795
796bool PeerConnectionInterface::RTCConfiguration::operator!=(
797 const PeerConnectionInterface::RTCConfiguration& o) const {
798 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26799}
800
zhihuang8f65cdf2016-05-07 01:40:30801// Generate a RTCP CNAME when a PeerConnection is created.
802std::string GenerateRtcpCname() {
803 std::string cname;
804 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25805 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27806 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30807 }
808 return cname;
809}
810
zhihuang1c378ed2017-08-17 21:10:50811bool ValidateOfferAnswerOptions(
812 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
813 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
814 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32815}
816
zhihuang1c378ed2017-08-17 21:10:50817// From |rtc_options|, fill parts of |session_options| shared by all generated
818// m= sections (in other words, nothing that involves a map/array).
819void ExtractSharedMediaSessionOptions(
820 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
821 cricket::MediaSessionOptions* session_options) {
822 session_options->vad_enabled = rtc_options.voice_activity_detection;
823 session_options->bundle_enabled = rtc_options.use_rtp_mux;
824}
zhihuanga77e6bb2017-08-15 01:17:48825
zhihuang38ede132017-06-15 19:52:32826PeerConnection::PeerConnection(PeerConnectionFactory* factory,
827 std::unique_ptr<RtcEventLog> event_log,
828 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36829 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32830 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30831 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11832 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32833 remote_streams_(StreamCollection::Create()),
834 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36835
836PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17837 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22838 RTC_DCHECK_RUN_ON(signaling_thread());
839
Steve Anton8af21862017-12-15 19:20:13840 // Need to stop transceivers before destroying the stats collector because
841 // AudioRtpSender has a reference to the StatsCollector it will update when
842 // stopping.
843 for (auto transceiver : transceivers_) {
844 transceiver->Stop();
845 }
Steve Anton4171afb2017-11-20 18:20:22846
Taylor Brandstettera1c30352016-05-13 15:15:11847 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57848 if (stats_collector_) {
849 stats_collector_->WaitForPendingRequest();
850 stats_collector_ = nullptr;
851 }
Steve Anton75737c02017-11-06 18:37:17852
Steve Anton8af21862017-12-15 19:20:13853 // Don't destroy BaseChannels until after stats has been cleaned up so that
854 // the last stats request can still read from the channels.
855 DestroyAllChannels();
856
Mirko Bonadei675513b2017-11-09 10:09:25857 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17858
859 webrtc_session_desc_factory_.reset();
860 sctp_invoker_.reset();
861 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 19:23:22862 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 18:37:17863 transport_controller_.reset();
864
deadbeef91dd5672016-05-18 23:55:30865 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27866 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02867 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15868 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02869 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15870 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09871 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15872 event_log_.reset();
873 });
henrike@webrtc.org28e20752013-07-10 00:45:36874}
875
Steve Anton8af21862017-12-15 19:20:13876void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08877 // Destroy video channels first since they may have a pointer to a voice
878 // channel.
879 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08880 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08881 DestroyTransceiverChannel(transceiver);
882 }
883 }
884 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08885 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08886 DestroyTransceiverChannel(transceiver);
887 }
888 }
889 DestroyDataChannel();
890}
891
henrike@webrtc.org28e20752013-07-10 00:45:36892bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45893 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47894 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17895 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59896
897 RTCError config_error = ValidateConfiguration(configuration);
898 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25899 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59900 return false;
901 }
902
Benjamin Wrightcab588882018-05-02 22:12:47903 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25904 RTC_LOG(LS_ERROR)
905 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07906 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30907 return false;
908 }
Jonas Orelandbdcee282017-10-10 12:01:40909
Benjamin Wrightcab588882018-05-02 22:12:47910 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30911 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25912 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07913 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10914 return false;
915 }
Benjamin Wrightd6f86e82018-05-08 20:12:25916
Benjamin Wrightcab588882018-05-02 22:12:47917 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15918 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47919 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25920 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10921
Harald Alvestrandb2a74782018-06-28 11:54:07922 cricket::ServerAddresses stun_servers;
923 std::vector<cricket::RelayServerConfig> turn_servers;
924
925 RTCErrorType parse_error =
926 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
927 if (parse_error != RTCErrorType::NONE) {
928 return false;
929 }
930
deadbeef91dd5672016-05-18 23:55:30931 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11932 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27933 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 11:54:07934 RTC_FROM_HERE,
935 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
936 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36937 return false;
938 }
Harald Alvestrandb2a74782018-06-28 11:54:07939 // If initialization was successful, note if STUN or TURN servers
940 // were supplied.
941 if (!stun_servers.empty()) {
942 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
943 }
944 if (!turn_servers.empty()) {
945 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
946 }
henrike@webrtc.org28e20752013-07-10 00:45:36947
Qingsi Wang7fc821d2018-07-12 19:54:53948 // Send information about IPv4/IPv6 status.
949 PeerConnectionAddressFamilyCounter address_family;
950 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
951 address_family = kPeerConnection_IPv6;
952 } else {
953 address_family = kPeerConnection_IPv4;
954 }
955 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
956 kPeerConnectionAddressFamilyCounter_Max);
957
Zhi Huange830e682018-03-30 17:48:35958 const PeerConnectionFactoryInterface::Options& options = factory_->options();
959
Steve Anton75737c02017-11-06 18:37:17960 // RFC 3264: The numeric value of the session id and version in the
961 // o line MUST be representable with a "64 bit signed integer".
962 // Due to this constraint session id |session_id_| is max limited to
963 // LLONG_MAX.
964 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35965 JsepTransportController::Config config;
966 config.redetermine_role_on_ice_restart =
967 configuration.redetermine_role_on_ice_restart;
968 config.ssl_max_version = factory_->options().ssl_max_version;
969 config.disable_encryption = options.disable_encryption;
970 config.bundle_policy = configuration.bundle_policy;
971 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 17:16:44972 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
973 // stub.
974 config.crypto_options = configuration.crypto_options.has_value()
975 ? *configuration.crypto_options
976 : options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:34977 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46978 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35979#if defined(ENABLE_EXTERNAL_AUTH)
980 config.enable_external_auth = true;
981#endif
Zhi Huangb57e1692018-06-12 18:41:11982 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:42983
Bjorn Mellema9bbd862018-11-02 16:07:48984 if (configuration.use_media_transport ||
985 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 20:15:42986 if (!factory_->media_transport_factory()) {
987 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 16:07:48988 << "PeerConnecton is initialized with use_media_transport = true or "
989 << "use_media_transport_for_data_channels = true "
990 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 20:15:42991 return false;
992 }
993
994 config.media_transport_factory = factory_->media_transport_factory();
995 }
996
Zhi Huange830e682018-03-30 17:48:35997 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:15998 signaling_thread(), network_thread(), port_allocator_.get(),
999 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:351000 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:591001 this, &PeerConnection::OnTransportControllerConnectionState);
1002 transport_controller_->SignalStandardizedIceConnectionState.connect(
1003 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:171004 transport_controller_->SignalConnectionState.connect(
1005 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:351006 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:171007 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:351008 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:171009 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:351010 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:171011 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1012 transport_controller_->SignalDtlsHandshakeError.connect(
1013 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1014
1015 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:251016
deadbeefab9b2d12015-10-14 18:33:111017 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:011018 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:361019
Steve Antonba818672017-11-06 18:21:571020 configuration_ = configuration;
1021
Steve Anton75737c02017-11-06 18:37:171022 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1023 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1024 if (!configuration.certificates.empty()) {
1025 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1026 // just picking the first one. The decision should be made based on the DTLS
1027 // handshake. The DTLS negotiations need to know about all certificates.
1028 certificate = configuration.certificates[0];
1029 }
1030
Steve Antond25da372017-11-06 22:50:291031 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171032
1033 if (options.disable_encryption) {
1034 dtls_enabled_ = false;
1035 } else {
1036 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:471037 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:171038 // |configuration| can override the default |dtls_enabled_| value.
1039 if (configuration.enable_dtls_srtp) {
1040 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1041 }
1042 }
1043
Bjorn Mellem175aa2e2018-11-08 19:23:221044 if (configuration.use_media_transport_for_data_channels) {
1045 if (configuration.enable_rtp_data_channel) {
1046 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1047 "use_media_transport_for_data_channels are "
1048 "incompatible and cannot both be set to true";
1049 return false;
1050 }
1051 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1052 } else if (configuration.enable_rtp_data_channel) {
1053 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1054 // set. It takes precendence over the disable_sctp_data_channels
1055 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 18:37:171056 data_channel_type_ = cricket::DCT_RTP;
1057 } else {
1058 // DTLS has to be enabled to use SCTP.
1059 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1060 data_channel_type_ = cricket::DCT_SCTP;
1061 }
1062 }
1063
1064 video_options_.screencast_min_bitrate_kbps =
1065 configuration.screencast_min_bitrate;
1066 audio_options_.combined_audio_video_bwe =
1067 configuration.combined_audio_video_bwe;
1068
1069 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301070 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171071
1072 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301073 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171074
1075 // Whether the certificate generator/certificate is null or not determines
1076 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1077 // the right instructions by clearing the variables if needed.
1078 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471079 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171080 certificate = nullptr;
1081 } else if (certificate) {
1082 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471083 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171084 }
1085
1086 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1087 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471088 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171089 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1090 this, &PeerConnection::OnCertificateReady);
1091
1092 if (options.disable_encryption) {
1093 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1094 }
1095
1096 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 17:16:441097 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361098
Steve Anton4171afb2017-11-20 18:20:221099 // Add default audio/video transceivers for Plan B SDP.
1100 if (!IsUnifiedPlan()) {
1101 transceivers_.push_back(
1102 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1103 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1104 transceivers_.push_back(
1105 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1106 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1107 }
Harald Alvestrand183e09d2018-06-28 10:04:411108 int delay_ms =
1109 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401110 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1111 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:361112 return true;
1113}
1114
Steve Anton038834f2017-07-14 22:59:591115RTCError PeerConnection::ValidateConfiguration(
1116 const RTCConfiguration& config) const {
1117 if (config.ice_regather_interval_range &&
1118 config.continual_gathering_policy == GATHER_ONCE) {
1119 return RTCError(RTCErrorType::INVALID_PARAMETER,
1120 "ice_regather_interval_range specified but continual "
1121 "gathering policy is GATHER_ONCE");
1122 }
Qingsi Wangdea68892018-03-27 17:55:211123 auto result =
1124 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1125 return result;
Steve Anton038834f2017-07-14 22:59:591126}
1127
Yves Gerey665174f2018-06-19 13:03:051128rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581129 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1130 "Plan SdpSemantics. Please use GetSenders "
1131 "instead.";
deadbeefab9b2d12015-10-14 18:33:111132 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361133}
1134
Yves Gerey665174f2018-06-19 13:03:051135rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581136 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1137 "Plan SdpSemantics. Please use GetReceivers "
1138 "instead.";
deadbeefab9b2d12015-10-14 18:33:111139 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361140}
1141
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291142bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581143 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1144 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171145 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361146 if (IsClosed()) {
1147 return false;
1148 }
deadbeefab9b2d12015-10-14 18:33:111149 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361150 return false;
1151 }
deadbeefab9b2d12015-10-14 18:33:111152
1153 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431154 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1155 observer->SignalAudioTrackAdded.connect(this,
1156 &PeerConnection::OnAudioTrackAdded);
1157 observer->SignalAudioTrackRemoved.connect(
1158 this, &PeerConnection::OnAudioTrackRemoved);
1159 observer->SignalVideoTrackAdded.connect(this,
1160 &PeerConnection::OnVideoTrackAdded);
1161 observer->SignalVideoTrackRemoved.connect(
1162 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291163 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111164
deadbeefab9b2d12015-10-14 18:33:111165 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251166 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111167 }
1168 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251169 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111170 }
1171
tommi@webrtc.org03505bc2014-07-14 20:15:261172 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:161173 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361174 return true;
1175}
1176
1177void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581178 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1179 "Plan SdpSemantics. Please use RemoveTrack "
1180 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171181 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251182 if (!IsClosed()) {
1183 for (const auto& track : local_stream->GetAudioTracks()) {
1184 RemoveAudioTrack(track.get(), local_stream);
1185 }
1186 for (const auto& track : local_stream->GetVideoTracks()) {
1187 RemoveVideoTrack(track.get(), local_stream);
1188 }
deadbeefab9b2d12015-10-14 18:33:111189 }
deadbeefab9b2d12015-10-14 18:33:111190 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431191 stream_observers_.erase(
1192 std::remove_if(
1193 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291194 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281195 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431196 }),
1197 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111198
henrike@webrtc.org28e20752013-07-10 00:45:361199 if (IsClosed()) {
1200 return;
1201 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161202 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361203}
1204
Steve Anton2d6c76a2018-01-06 01:10:521205RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571206 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101207 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521208 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571209 if (!track) {
1210 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1211 }
1212 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1213 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1215 "Track has invalid kind: " + track->kind());
1216 }
Steve Antonf9381f02017-12-14 18:23:571217 if (IsClosed()) {
1218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1219 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421220 }
Steve Anton4171afb2017-11-20 18:20:221221 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571222 LOG_AND_RETURN_ERROR(
1223 RTCErrorType::INVALID_PARAMETER,
1224 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421225 }
Steve Antonf9381f02017-12-14 18:23:571226 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361227 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1228 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571229 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161230 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171231 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571232 }
1233 return sender_or_error;
1234}
deadbeefe1f9d832016-01-14 23:35:421235
Steve Antonf9381f02017-12-14 18:23:571236RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1237PeerConnection::AddTrackPlanB(
1238 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101239 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361240 if (stream_ids.size() > 1u) {
1241 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1242 "AddTrack with more than one stream is not "
1243 "supported with Plan B semantics.");
1244 }
1245 std::vector<std::string> adjusted_stream_ids = stream_ids;
1246 if (adjusted_stream_ids.empty()) {
1247 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1248 }
Steve Anton02ee47c2018-01-11 00:26:061249 cricket::MediaType media_type =
1250 (track->kind() == MediaStreamTrackInterface::kAudioKind
1251 ? cricket::MEDIA_TYPE_AUDIO
1252 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361253 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201254 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421255 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051256 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221257 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221258 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181259 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361260 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221261 if (sender_info) {
1262 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421263 }
Steve Antonf9381f02017-12-14 18:23:571264 } else {
1265 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051266 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221267 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221268 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181269 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361270 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221271 if (sender_info) {
1272 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421273 }
deadbeefe1f9d832016-01-14 23:35:421274 }
Steve Anton02ee47c2018-01-11 00:26:061275 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571276}
deadbeefe1f9d832016-01-14 23:35:421277
Steve Antonf9381f02017-12-14 18:23:571278RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1279PeerConnection::AddTrackUnifiedPlan(
1280 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101281 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571282 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1283 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231284 RTC_LOG(LS_INFO) << "Reusing an existing "
1285 << cricket::MediaTypeToString(transceiver->media_type())
1286 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571287 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121288 transceiver->internal()->set_direction(
1289 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571290 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121291 transceiver->internal()->set_direction(
1292 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571293 }
Steve Anton02ee47c2018-01-11 00:26:061294 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101295 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571296 } else {
1297 cricket::MediaType media_type =
1298 (track->kind() == MediaStreamTrackInterface::kAudioKind
1299 ? cricket::MEDIA_TYPE_AUDIO
1300 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231301 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1302 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501303 std::string sender_id = track->id();
1304 // Avoid creating a sender with an existing ID by generating a random ID.
1305 // This can happen if this is the second time AddTrack has created a sender
1306 // for this track.
1307 if (FindSenderById(sender_id)) {
1308 sender_id = rtc::CreateRandomUuid();
1309 }
Florent Castelli892acf02018-10-01 20:47:201310 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061311 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1312 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571313 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121314 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571315 }
Steve Antonf9381f02017-12-14 18:23:571316 return transceiver->sender();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindFirstTransceiverForAddedTrack(
1321 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1322 RTC_DCHECK(track);
1323 for (auto transceiver : transceivers_) {
1324 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081325 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571326 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421327 !transceiver->internal()->has_ever_been_used_to_send() &&
1328 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571329 return transceiver;
1330 }
1331 }
1332 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421333}
1334
1335bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1336 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331337 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571338}
1339
Steve Anton24db5732018-07-23 17:27:331340RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571341 rtc::scoped_refptr<RtpSenderInterface> sender) {
1342 if (!sender) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1344 }
deadbeefe1f9d832016-01-14 23:35:421345 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1347 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421348 }
Steve Antonf9381f02017-12-14 18:23:571349 if (IsUnifiedPlan()) {
1350 auto transceiver = FindTransceiverBySender(sender);
1351 if (!transceiver || !sender->track()) {
1352 return RTCError::OK();
1353 }
1354 sender->SetTrack(nullptr);
1355 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121356 transceiver->internal()->set_direction(
1357 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571358 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121359 transceiver->internal()->set_direction(
1360 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571361 }
Steve Anton4171afb2017-11-20 18:20:221362 } else {
Steve Antonf9381f02017-12-14 18:23:571363 bool removed;
1364 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1365 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1366 } else {
1367 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1368 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1369 }
1370 if (!removed) {
1371 LOG_AND_RETURN_ERROR(
1372 RTCErrorType::INVALID_PARAMETER,
1373 "Couldn't find sender " + sender->id() + " to remove.");
1374 }
Steve Anton4171afb2017-11-20 18:20:221375 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161376 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571377 return RTCError::OK();
1378}
1379
1380rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1381PeerConnection::FindTransceiverBySender(
1382 rtc::scoped_refptr<RtpSenderInterface> sender) {
1383 for (auto transceiver : transceivers_) {
1384 if (transceiver->sender() == sender) {
1385 return transceiver;
1386 }
1387 }
1388 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421389}
1390
Steve Anton9158ef62017-11-27 21:01:521391RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1392PeerConnection::AddTransceiver(
1393 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1394 return AddTransceiver(track, RtpTransceiverInit());
1395}
1396
1397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1400 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581401 RTC_CHECK(IsUnifiedPlan())
1402 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521403 if (!track) {
1404 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1405 }
1406 cricket::MediaType media_type;
1407 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1408 media_type = cricket::MEDIA_TYPE_AUDIO;
1409 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1410 media_type = cricket::MEDIA_TYPE_VIDEO;
1411 } else {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1413 "Track kind is not audio or video");
1414 }
1415 return AddTransceiver(media_type, track, init);
1416}
1417
1418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1420 return AddTransceiver(media_type, RtpTransceiverInit());
1421}
1422
1423RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1424PeerConnection::AddTransceiver(cricket::MediaType media_type,
1425 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581426 RTC_CHECK(IsUnifiedPlan())
1427 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521428 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1429 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1431 "media type is not audio or video");
1432 }
1433 return AddTransceiver(media_type, nullptr, init);
1434}
1435
1436RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1437PeerConnection::AddTransceiver(
1438 cricket::MediaType media_type,
1439 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071440 const RtpTransceiverInit& init,
1441 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521442 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1443 media_type == cricket::MEDIA_TYPE_VIDEO));
1444 if (track) {
1445 RTC_DCHECK_EQ(media_type,
1446 (track->kind() == MediaStreamTrackInterface::kAudioKind
1447 ? cricket::MEDIA_TYPE_AUDIO
1448 : cricket::MEDIA_TYPE_VIDEO));
1449 }
1450
1451 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 20:47:201452 if (init.send_encodings.size() > 1) {
1453 LOG_AND_RETURN_ERROR(
1454 RTCErrorType::UNSUPPORTED_PARAMETER,
1455 "Attempted to create an encoder with more than 1 encoding parameter.");
1456 }
1457
1458 for (const auto& encoding : init.send_encodings) {
1459 if (encoding.ssrc.has_value()) {
1460 LOG_AND_RETURN_ERROR(
1461 RTCErrorType::UNSUPPORTED_PARAMETER,
1462 "Attempted to set an unimplemented parameter of RtpParameters.");
1463 }
1464 }
1465
1466 RtpParameters parameters;
1467 parameters.encodings = init.send_encodings;
1468 if (UnimplementedRtpParameterHasValue(parameters)) {
1469 LOG_AND_RETURN_ERROR(
1470 RTCErrorType::UNSUPPORTED_PARAMETER,
1471 "Attempted to set an unimplemented parameter of RtpParameters.");
1472 }
Steve Anton9158ef62017-11-27 21:01:521473
Steve Anton3d954a62018-04-02 18:27:231474 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1475 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501476 // Set the sender ID equal to the track ID if the track is specified unless
1477 // that sender ID is already in use.
1478 std::string sender_id =
1479 (track && !FindSenderById(track->id()) ? track->id()
1480 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 20:47:201481 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1482 init.send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061483 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1484 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1485 transceiver->internal()->set_direction(init.direction);
1486
Steve Anton22da89f2018-01-25 21:58:071487 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161488 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071489 }
Steve Antonf9381f02017-12-14 18:23:571490
1491 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1492}
1493
Steve Anton02ee47c2018-01-11 00:26:061494rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1495PeerConnection::CreateSender(
1496 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361497 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061498 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201499 const std::vector<std::string>& stream_ids,
1500 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 21:01:521501 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061502 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1503 RTC_DCHECK(!track ||
1504 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1505 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1506 signaling_thread(),
Steve Anton111fdfd2018-06-25 20:03:361507 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341508 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061509 } else {
1510 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1511 RTC_DCHECK(!track ||
1512 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1513 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 20:03:361514 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341515 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061516 }
Steve Anton111fdfd2018-06-25 20:03:361517 bool set_track_succeeded = sender->SetTrack(track);
1518 RTC_DCHECK(set_track_succeeded);
1519 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 20:47:201520 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061521 return sender;
1522}
1523
1524rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1525PeerConnection::CreateReceiver(cricket::MediaType media_type,
1526 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521527 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1528 receiver;
Steve Anton9158ef62017-11-27 21:01:521529 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521530 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531531 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1532 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341533 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521534 } else {
Steve Anton02ee47c2018-01-11 00:26:061535 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521536 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531537 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1538 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341539 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521540 }
Steve Anton02ee47c2018-01-11 00:26:061541 return receiver;
1542}
1543
1544rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1545PeerConnection::CreateAndAddTransceiver(
1546 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1547 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1548 receiver) {
Steve Anton07563732018-06-26 18:13:501549 // Ensure that the new sender does not have an ID that is already in use by
1550 // another sender.
1551 // Allow receiver IDs to conflict since those come from remote SDP (which
1552 // could be invalid, but should not cause a crash).
1553 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061554 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1555 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521556 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121557 transceiver->internal()->SignalNegotiationNeeded.connect(
1558 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571559 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521560}
1561
Steve Anton52d86772018-02-20 23:48:121562void PeerConnection::OnNegotiationNeeded() {
1563 RTC_DCHECK_RUN_ON(signaling_thread());
1564 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 08:50:161565 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121566}
1567
deadbeeffac06552015-11-25 19:26:011568rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441569 const std::string& kind,
1570 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581571 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1572 "Plan SdpSemantics. Please use AddTransceiver "
1573 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171574 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251575 if (IsClosed()) {
1576 return nullptr;
1577 }
Steve Anton4171afb2017-11-20 18:20:221578
Seth Hampson5b4f0752018-04-02 23:31:361579 // Internally we need to have one stream with Plan B semantics, so we
1580 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101581 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361582 if (stream_id.empty()) {
1583 stream_ids.push_back(rtc::CreateRandomUuid());
1584 RTC_LOG(LS_INFO)
1585 << "No stream_id specified for sender. Generated stream ID: "
1586 << stream_ids[0];
1587 } else {
Seth Hampson845e8782018-03-02 19:34:101588 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061589 }
1590
Steve Anton4171afb2017-11-20 18:20:221591 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391592 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011593 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 20:03:361594 auto* audio_sender = new AudioRtpSender(
1595 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-14 00:26:051596 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391597 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061598 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221599 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011600 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351601 auto* video_sender =
Steve Anton111fdfd2018-06-25 20:03:361602 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-14 00:26:051603 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391604 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061605 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221606 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011607 } else {
Mirko Bonadei675513b2017-11-09 10:09:251608 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221609 return nullptr;
deadbeeffac06552015-11-25 19:26:011610 }
Steve Anton111fdfd2018-06-25 20:03:361611 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221612
deadbeefe1f9d832016-01-14 23:35:421613 return new_sender;
deadbeeffac06552015-11-25 19:26:011614}
1615
deadbeef70ab1a12015-09-28 23:53:551616std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1617 const {
deadbeefa601f5c2016-06-06 21:27:391618 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221619 for (auto sender : GetSendersInternal()) {
1620 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391621 }
1622 return ret;
deadbeef70ab1a12015-09-28 23:53:551623}
1624
Steve Anton4171afb2017-11-20 18:20:221625std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626PeerConnection::GetSendersInternal() const {
1627 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1628 all_senders;
1629 for (auto transceiver : transceivers_) {
1630 auto senders = transceiver->internal()->senders();
1631 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1632 }
1633 return all_senders;
1634}
1635
deadbeef70ab1a12015-09-28 23:53:551636std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1637PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391638 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221639 for (const auto& receiver : GetReceiversInternal()) {
1640 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391641 }
1642 return ret;
deadbeef70ab1a12015-09-28 23:53:551643}
1644
Steve Anton4171afb2017-11-20 18:20:221645std::vector<
1646 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1647PeerConnection::GetReceiversInternal() const {
1648 std::vector<
1649 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1650 all_receivers;
1651 for (auto transceiver : transceivers_) {
1652 auto receivers = transceiver->internal()->receivers();
1653 all_receivers.insert(all_receivers.end(), receivers.begin(),
1654 receivers.end());
1655 }
1656 return all_receivers;
1657}
1658
Steve Anton9158ef62017-11-27 21:01:521659std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1660PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581661 RTC_CHECK(IsUnifiedPlan())
1662 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521663 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1664 for (auto transceiver : transceivers_) {
1665 all_transceivers.push_back(transceiver);
1666 }
1667 return all_transceivers;
1668}
1669
henrike@webrtc.org28e20752013-07-10 00:45:361670bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491671 MediaStreamTrackInterface* track,
1672 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171673 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281674 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561675 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251676 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361677 return false;
1678 }
1679
tommi@webrtc.org03505bc2014-07-14 20:15:261680 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151681 // The StatsCollector is used to tell if a track is valid because it may
1682 // remember tracks that the PeerConnection previously removed.
1683 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251684 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1685 << track->id();
zhihuange9e94c32016-11-04 18:38:151686 return false;
1687 }
Steve Antonad182762018-09-05 20:22:401688 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1689 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361690 return true;
1691}
1692
hbos74e1a4f2016-09-16 06:33:011693void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201694 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011695 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201696 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011697 stats_collector_->GetStatsReport(callback);
1698}
1699
Henrik Boström1df1bf82018-03-20 12:24:201700void PeerConnection::GetStats(
1701 rtc::scoped_refptr<RtpSenderInterface> selector,
1702 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1703 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1704 RTC_DCHECK(callback);
1705 RTC_DCHECK(stats_collector_);
1706 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1707 if (selector) {
1708 for (const auto& proxy_transceiver : transceivers_) {
1709 for (const auto& proxy_sender :
1710 proxy_transceiver->internal()->senders()) {
1711 if (proxy_sender == selector) {
1712 internal_sender = proxy_sender->internal();
1713 break;
1714 }
1715 }
1716 if (internal_sender)
1717 break;
1718 }
1719 }
Sebastian Jansson6eb8a162018-11-16 10:29:551720 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:201721 // belong to the PeerConnection (in Plan B, senders can be removed from the
1722 // PeerConnection). This means that "all the stats objects representing the
1723 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1724 // produces an empty stats report.
1725 stats_collector_->GetStatsReport(internal_sender, callback);
1726}
1727
1728void PeerConnection::GetStats(
1729 rtc::scoped_refptr<RtpReceiverInterface> selector,
1730 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1731 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1732 RTC_DCHECK(callback);
1733 RTC_DCHECK(stats_collector_);
1734 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1735 if (selector) {
1736 for (const auto& proxy_transceiver : transceivers_) {
1737 for (const auto& proxy_receiver :
1738 proxy_transceiver->internal()->receivers()) {
1739 if (proxy_receiver == selector) {
1740 internal_receiver = proxy_receiver->internal();
1741 break;
1742 }
1743 }
1744 if (internal_receiver)
1745 break;
1746 }
1747 }
Sebastian Jansson6eb8a162018-11-16 10:29:551748 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:201749 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1750 // the PeerConnection). This means that "all the stats objects representing
1751 // the selector" is an empty set. Invoking GetStatsReport() with a null
1752 // selector produces an empty stats report.
1753 stats_collector_->GetStatsReport(internal_receiver, callback);
1754}
1755
henrike@webrtc.org28e20752013-07-10 00:45:361756PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1757 return signaling_state_;
1758}
1759
henrike@webrtc.org28e20752013-07-10 00:45:361760PeerConnectionInterface::IceConnectionState
1761PeerConnection::ice_connection_state() {
1762 return ice_connection_state_;
1763}
1764
Alex Loiko9289eda2018-11-23 16:18:591765PeerConnectionInterface::IceConnectionState
1766PeerConnection::standardized_ice_connection_state() {
1767 return standardized_ice_connection_state_;
1768}
1769
Jonas Olsson635474e2018-10-18 13:58:171770PeerConnectionInterface::PeerConnectionState
1771PeerConnection::peer_connection_state() {
1772 return connection_state_;
1773}
1774
henrike@webrtc.org28e20752013-07-10 00:45:361775PeerConnectionInterface::IceGatheringState
1776PeerConnection::ice_gathering_state() {
1777 return ice_gathering_state_;
1778}
1779
Yves Gerey665174f2018-06-19 13:03:051780rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361781 const std::string& label,
1782 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171783 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501784
deadbeefab9b2d12015-10-14 18:33:111785 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111786
kwibergd1fe2812016-04-27 13:47:291787 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581788 if (config) {
1789 internal_config.reset(new InternalDataChannelInit(*config));
1790 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521791 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111792 InternalCreateDataChannel(label, internal_config.get()));
1793 if (!channel.get()) {
1794 return nullptr;
1795 }
henrike@webrtc.org28e20752013-07-10 00:45:361796
jiayl@webrtc.org001fd2d2014-05-29 15:31:111797 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1798 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171799 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161800 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111801 }
Harald Alvestrand8ebba742018-05-31 12:00:341802 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361803 return DataChannelProxy::Create(signaling_thread(), channel.get());
1804}
1805
1806void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161807 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171808 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511809
nisse7ce109a2017-01-31 08:57:561810 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251811 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161812 return;
1813 }
deadbeefab9b2d12015-10-14 18:33:111814
Steve Anton8d3444d2017-10-20 22:30:511815 if (IsClosed()) {
1816 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251817 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031818 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101819 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511820 return;
1821 }
1822
zhihuang1c378ed2017-08-17 21:10:501823 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111824 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251825 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031826 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101827 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111828 return;
1829 }
1830
Steve Anton22da89f2018-01-25 21:58:071831 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1832 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1833 if (IsUnifiedPlan()) {
1834 RTCError error = HandleLegacyOfferOptions(options);
1835 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031836 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071837 return;
1838 }
1839 }
1840
zhihuang1c378ed2017-08-17 21:10:501841 cricket::MediaSessionOptions session_options;
1842 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291843 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361844}
1845
Steve Anton22da89f2018-01-25 21:58:071846RTCError PeerConnection::HandleLegacyOfferOptions(
1847 const RTCOfferAnswerOptions& options) {
1848 RTC_DCHECK(IsUnifiedPlan());
1849
1850 if (options.offer_to_receive_audio == 0) {
1851 RemoveRecvDirectionFromReceivingTransceiversOfType(
1852 cricket::MEDIA_TYPE_AUDIO);
1853 } else if (options.offer_to_receive_audio == 1) {
1854 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1855 } else if (options.offer_to_receive_audio > 1) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1857 "offer_to_receive_audio > 1 is not supported.");
1858 }
1859
1860 if (options.offer_to_receive_video == 0) {
1861 RemoveRecvDirectionFromReceivingTransceiversOfType(
1862 cricket::MEDIA_TYPE_VIDEO);
1863 } else if (options.offer_to_receive_video == 1) {
1864 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1865 } else if (options.offer_to_receive_video > 1) {
1866 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1867 "offer_to_receive_video > 1 is not supported.");
1868 }
1869
1870 return RTCError::OK();
1871}
1872
1873void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1874 cricket::MediaType media_type) {
1875 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231876 RtpTransceiverDirection new_direction =
1877 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1878 if (new_direction != transceiver->direction()) {
1879 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1880 << " transceiver (MID="
1881 << transceiver->mid().value_or("<not set>") << ") from "
1882 << RtpTransceiverDirectionToString(
1883 transceiver->direction())
1884 << " to "
1885 << RtpTransceiverDirectionToString(new_direction)
1886 << " since CreateOffer specified offer_to_receive=0";
1887 transceiver->internal()->set_direction(new_direction);
1888 }
Steve Anton22da89f2018-01-25 21:58:071889 }
1890}
1891
1892void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1893 cricket::MediaType media_type) {
1894 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231895 RTC_LOG(LS_INFO)
1896 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1897 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071898 RtpTransceiverInit init;
1899 init.direction = RtpTransceiverDirection::kRecvOnly;
1900 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1901 }
1902}
1903
1904std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1905PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1906 std::vector<
1907 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1908 receiving_transceivers;
1909 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081910 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071911 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1912 receiving_transceivers.push_back(transceiver);
1913 }
1914 }
1915 return receiving_transceivers;
1916}
1917
htaa2a49d92016-03-04 10:51:391918void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1919 const RTCOfferAnswerOptions& options) {
1920 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561921 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251922 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391923 return;
1924 }
1925
Steve Antondffead82018-02-06 18:31:291926 if (!(signaling_state_ == kHaveRemoteOffer ||
1927 signaling_state_ == kHaveLocalPrAnswer)) {
1928 std::string error =
1929 "PeerConnection cannot create an answer in a state other than "
1930 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251931 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031932 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101933 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511934 return;
1935 }
1936
Steve Antondffead82018-02-06 18:31:291937 // The remote description should be set if we're in the right state.
1938 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511939
Steve Anton22da89f2018-01-25 21:58:071940 if (IsUnifiedPlan()) {
1941 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1942 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1943 "supported with Unified Plan semantics. Use the "
1944 "RtpTransceiver API instead.";
1945 }
1946 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1947 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1948 "supported with Unified Plan semantics. Use the "
1949 "RtpTransceiver API instead.";
1950 }
1951 }
1952
htaa2a49d92016-03-04 10:51:391953 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501954 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391955
Steve Antond25da372017-11-06 22:50:291956 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361957}
1958
1959void PeerConnection::SetLocalDescription(
1960 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421961 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171962 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561963
Steve Anton80dd7b52018-02-17 01:08:421964 // The SetLocalDescription contract is that we take ownership of the session
1965 // description regardless of the outcome, so wrap it in a unique_ptr right
1966 // away. Ideally, SetLocalDescription's signature will be changed to take the
1967 // description as a unique_ptr argument to formalize this agreement.
1968 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1969
nisse7ce109a2017-01-31 08:57:561970 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251971 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361972 return;
1973 }
Steve Anton8a006912017-12-04 23:25:561974
henrike@webrtc.org28e20752013-07-10 00:45:361975 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031976 PostSetSessionDescriptionFailure(
1977 observer,
1978 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361979 return;
1980 }
Steve Anton8d3444d2017-10-20 22:30:511981
Steve Anton80dd7b52018-02-17 01:08:421982 // If a session error has occurred the PeerConnection is in a possibly
1983 // inconsistent state so fail right away.
1984 if (session_error() != SessionError::kNone) {
1985 std::string error_message = GetSessionErrorMsg();
1986 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031987 PostSetSessionDescriptionFailure(
1988 observer,
1989 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421990 return;
1991 }
Steve Anton8d3444d2017-10-20 22:30:511992
Steve Anton80dd7b52018-02-17 01:08:421993 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1994 if (!error.ok()) {
1995 std::string error_message = GetSetDescriptionErrorMessage(
1996 cricket::CS_LOCAL, desc->GetType(), error);
1997 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031998 PostSetSessionDescriptionFailure(
1999 observer,
2000 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422001 return;
2002 }
2003
2004 // Grab the description type before moving ownership to ApplyLocalDescription,
2005 // which may destroy it before returning.
2006 const SdpType type = desc->GetType();
2007
2008 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:562009 // |desc| may be destroyed at this point.
2010
2011 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422012 // If ApplyLocalDescription fails, the PeerConnection could be in an
2013 // inconsistent state, so act conservatively here and set the session error
2014 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2015 SetSessionError(SessionError::kContent, error.message());
2016 std::string error_message =
2017 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2018 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:032019 PostSetSessionDescriptionFailure(
2020 observer,
2021 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:512022 return;
2023 }
Steve Anton8a006912017-12-04 23:25:562024 RTC_DCHECK(local_description());
2025
2026 PostSetSessionDescriptionSuccess(observer);
2027
Steve Antonad182762018-09-05 20:22:402028 // MaybeStartGathering needs to be called after posting
2029 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2030 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:562031 transport_controller_->MaybeStartGathering();
2032
Steve Antona3a92c22017-12-07 18:27:412033 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562034 // TODO(deadbeef): We already had to hop to the network thread for
2035 // MaybeStartGathering...
2036 network_thread()->Invoke<void>(
2037 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2038 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302039 // Make UMA notes about what was agreed to.
2040 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562041 }
Harald Alvestrand8ebba742018-05-31 12:00:342042 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562043}
2044
2045RTCError PeerConnection::ApplyLocalDescription(
2046 std::unique_ptr<SessionDescriptionInterface> desc) {
2047 RTC_DCHECK_RUN_ON(signaling_thread());
2048 RTC_DCHECK(desc);
2049
henrike@webrtc.org28e20752013-07-10 00:45:362050 // Update stats here so that we have the most recent stats for tracks and
2051 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262052 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562053
Steve Antondcc3c022017-12-23 00:02:542054 // Take a reference to the old local description since it's used below to
2055 // compare against the new local description. When setting the new local
2056 // description, grab ownership of the replaced session description in case it
2057 // is the same as |old_local_description|, to keep it alive for the duration
2058 // of the method.
2059 const SessionDescriptionInterface* old_local_description =
2060 local_description();
2061 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352062 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512063 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542064 replaced_local_description = pending_local_description_
2065 ? std::move(pending_local_description_)
2066 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562067 current_local_description_ = std::move(desc);
2068 pending_local_description_ = nullptr;
2069 current_remote_description_ = std::move(pending_remote_description_);
2070 } else {
Steve Antondcc3c022017-12-23 00:02:542071 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562072 pending_local_description_ = std::move(desc);
2073 }
2074 // The session description to apply now must be accessed by
2075 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442076 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112077
Bjorn Mellem175aa2e2018-11-08 19:23:222078 if (!is_caller_) {
2079 if (remote_description()) {
2080 // Remote description was applied first, so this PC is the callee.
2081 is_caller_ = false;
2082 } else {
2083 // Local description is applied first, so this PC is the caller.
2084 is_caller_ = true;
2085 }
2086 }
2087
Zhi Huange830e682018-03-30 17:48:352088 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2089 if (!error.ok()) {
2090 return error;
2091 }
2092
Steve Antondcc3c022017-12-23 00:02:542093 if (IsUnifiedPlan()) {
2094 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482095 cricket::CS_LOCAL, *local_description(), old_local_description,
2096 remote_description());
Steve Anton8a006912017-12-04 23:25:562097 if (!error.ok()) {
2098 return error;
2099 }
Steve Anton0f5400a2018-07-17 21:25:362100 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2101 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542102 for (auto transceiver : transceivers_) {
2103 const ContentInfo* content =
2104 FindMediaSectionForTransceiver(transceiver, local_description());
2105 if (!content) {
2106 continue;
2107 }
2108 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362109 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2110 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542111 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362112 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2113 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2114 // "recvonly", process the removal of a remote track for the media
2115 // description, given transceiver, removeList, and muteTracks.
2116 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2117 (transceiver->internal()->fired_direction() &&
2118 RtpTransceiverDirectionHasRecv(
2119 *transceiver->internal()->fired_direction()))) {
2120 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2121 &removed_streams);
2122 }
2123 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2124 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542125 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362126 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542127 }
Steve Anton0f5400a2018-07-17 21:25:362128 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162129 auto observer = Observer();
Steve Anton0f5400a2018-07-17 21:25:362130 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162131 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362132 }
2133 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162134 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542135 }
2136 } else {
Zhi Huange830e682018-03-30 17:48:352137 // Media channels will be created only when offer is set. These may use new
2138 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542139 if (type == SdpType::kOffer) {
2140 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2141 // description is applied. Restore back to old description.
2142 RTCError error = CreateChannels(*local_description()->description());
2143 if (!error.ok()) {
2144 return error;
2145 }
2146 }
Steve Antondcc3c022017-12-23 00:02:542147 // Remove unused channels if MediaContentDescription is rejected.
2148 RemoveUnusedChannels(local_description()->description());
2149 }
Steve Anton8a006912017-12-04 23:25:562150
Zhi Huange830e682018-03-30 17:48:352151 error = UpdateSessionState(type, cricket::CS_LOCAL,
2152 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562153 if (!error.ok()) {
2154 return error;
2155 }
Steve Antondcc3c022017-12-23 00:02:542156
Steve Anton8a006912017-12-04 23:25:562157 if (remote_description()) {
2158 // Now that we have a local description, we can push down remote candidates.
2159 UseCandidatesInSessionDescription(remote_description());
2160 }
2161
2162 pending_ice_restarts_.clear();
2163 if (session_error() != SessionError::kNone) {
2164 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2165 }
2166
deadbeefab9b2d12015-10-14 18:33:112167 // If setting the description decided our SSL role, allocate any necessary
2168 // SCTP sids.
2169 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222170 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112171 AllocateSctpSids(role);
2172 }
2173
Steve Antond3679212018-01-18 01:41:022174 if (IsUnifiedPlan()) {
2175 for (auto transceiver : transceivers_) {
2176 const ContentInfo* content =
2177 FindMediaSectionForTransceiver(transceiver, local_description());
2178 if (!content) {
2179 continue;
2180 }
Steve Anton74255ff2018-01-25 02:32:572181 const auto& streams = content->media_description()->streams();
2182 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022183 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102184 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022185 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572186 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272187 } else {
2188 // 0 is a special value meaning "this sender has no associated send
2189 // stream". Need to call this so the sender won't attempt to configure
2190 // a no longer existing stream and run into DCHECKs in the lower
2191 // layers.
2192 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-18 01:41:022193 }
2194 }
2195 } else {
2196 // Plan B semantics.
2197
Steve Antondcc3c022017-12-23 00:02:542198 // Update state and SSRC of local MediaStreams and DataChannels based on the
2199 // local session description.
2200 const cricket::ContentInfo* audio_content =
2201 GetFirstAudioContent(local_description()->description());
2202 if (audio_content) {
2203 if (audio_content->rejected) {
2204 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2205 } else {
2206 const cricket::AudioContentDescription* audio_desc =
2207 audio_content->media_description()->as_audio();
2208 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2209 }
deadbeeffaac4972015-11-12 23:33:072210 }
deadbeefab9b2d12015-10-14 18:33:112211
Steve Antondcc3c022017-12-23 00:02:542212 const cricket::ContentInfo* video_content =
2213 GetFirstVideoContent(local_description()->description());
2214 if (video_content) {
2215 if (video_content->rejected) {
2216 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2217 } else {
2218 const cricket::VideoContentDescription* video_desc =
2219 video_content->media_description()->as_video();
2220 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2221 }
deadbeeffaac4972015-11-12 23:33:072222 }
deadbeefab9b2d12015-10-14 18:33:112223 }
2224
2225 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442226 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112227 if (data_content) {
2228 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302229 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112230 if (rtc::starts_with(data_desc->protocol().data(),
2231 cricket::kMediaProtocolRtpPrefix)) {
2232 UpdateLocalRtpDataChannels(data_desc->streams());
2233 }
2234 }
2235
Steve Anton8a006912017-12-04 23:25:562236 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362237}
2238
2239void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072240 SetSessionDescriptionObserver* observer,
2241 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322242 SetRemoteDescription(
2243 std::unique_ptr<SessionDescriptionInterface>(desc),
2244 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2245 new SetRemoteDescriptionObserverAdapter(this, observer)));
2246}
2247
2248void PeerConnection::SetRemoteDescription(
2249 std::unique_ptr<SessionDescriptionInterface> desc,
2250 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172251 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562252
nisse7ce109a2017-01-31 08:57:562253 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252254 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362255 return;
2256 }
Steve Anton8a006912017-12-04 23:25:562257
henrike@webrtc.org28e20752013-07-10 00:45:362258 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322259 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562260 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362261 return;
2262 }
Steve Anton8d3444d2017-10-20 22:30:512263
Steve Anton80dd7b52018-02-17 01:08:422264 // If a session error has occurred the PeerConnection is in a possibly
2265 // inconsistent state so fail right away.
2266 if (session_error() != SessionError::kNone) {
2267 std::string error_message = GetSessionErrorMsg();
2268 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2269 observer->OnSetRemoteDescriptionComplete(
2270 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2271 return;
2272 }
Steve Anton71439a62018-02-15 19:53:062273
Steve Antonba42e992018-04-09 21:10:012274 if (desc->GetType() == SdpType::kOffer) {
2275 // Report to UMA the format of the received offer.
2276 ReportSdpFormatReceived(*desc);
2277 }
2278
Steve Anton80dd7b52018-02-17 01:08:422279 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062280 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422281 std::string error_message = GetSetDescriptionErrorMessage(
2282 cricket::CS_REMOTE, desc->GetType(), error);
2283 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062284 observer->OnSetRemoteDescriptionComplete(
2285 RTCError(error.type(), std::move(error_message)));
2286 return;
2287 }
Steve Anton71439a62018-02-15 19:53:062288
Steve Anton80dd7b52018-02-17 01:08:422289 // Grab the description type before moving ownership to
2290 // ApplyRemoteDescription, which may destroy it before returning.
2291 const SdpType type = desc->GetType();
2292
2293 error = ApplyRemoteDescription(std::move(desc));
2294 // |desc| may be destroyed at this point.
2295
2296 if (!error.ok()) {
2297 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2298 // inconsistent state, so act conservatively here and set the session error
2299 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2300 SetSessionError(SessionError::kContent, error.message());
2301 std::string error_message =
2302 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2303 RTC_LOG(LS_ERROR) << error_message;
2304 observer->OnSetRemoteDescriptionComplete(
2305 RTCError(error.type(), std::move(error_message)));
2306 return;
2307 }
2308 RTC_DCHECK(remote_description());
2309
2310 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562311 // TODO(deadbeef): We already had to hop to the network thread for
2312 // MaybeStartGathering...
2313 network_thread()->Invoke<void>(
2314 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2315 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002316 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302317 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562318 }
2319
2320 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342321 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562322}
2323
2324RTCError PeerConnection::ApplyRemoteDescription(
2325 std::unique_ptr<SessionDescriptionInterface> desc) {
2326 RTC_DCHECK_RUN_ON(signaling_thread());
2327 RTC_DCHECK(desc);
2328
henrike@webrtc.org28e20752013-07-10 00:45:362329 // Update stats here so that we have the most recent stats for tracks and
2330 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262331 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562332
Steve Antondcc3c022017-12-23 00:02:542333 // Take a reference to the old remote description since it's used below to
2334 // compare against the new remote description. When setting the new remote
2335 // description, grab ownership of the replaced session description in case it
2336 // is the same as |old_remote_description|, to keep it alive for the duration
2337 // of the method.
Steve Anton8a006912017-12-04 23:25:562338 const SessionDescriptionInterface* old_remote_description =
2339 remote_description();
Steve Anton8a006912017-12-04 23:25:562340 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512341 SdpType type = desc->GetType();
2342 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562343 replaced_remote_description = pending_remote_description_
2344 ? std::move(pending_remote_description_)
2345 : std::move(current_remote_description_);
2346 current_remote_description_ = std::move(desc);
2347 pending_remote_description_ = nullptr;
2348 current_local_description_ = std::move(pending_local_description_);
2349 } else {
2350 replaced_remote_description = std::move(pending_remote_description_);
2351 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362352 }
Steve Anton8a006912017-12-04 23:25:562353 // The session description to apply now must be accessed by
2354 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442355 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362356
Zhi Huange830e682018-03-30 17:48:352357 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2358 if (!error.ok()) {
2359 return error;
2360 }
Steve Anton8a006912017-12-04 23:25:562361 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542362 if (IsUnifiedPlan()) {
2363 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482364 cricket::CS_REMOTE, *remote_description(), local_description(),
2365 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562366 if (!error.ok()) {
2367 return error;
2368 }
Steve Antondcc3c022017-12-23 00:02:542369 } else {
Zhi Huange830e682018-03-30 17:48:352370 // Media channels will be created only when offer is set. These may use new
2371 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542372 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352373 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542374 // description is applied. Restore back to old description.
2375 RTCError error = CreateChannels(*remote_description()->description());
2376 if (!error.ok()) {
2377 return error;
2378 }
2379 }
Steve Antondcc3c022017-12-23 00:02:542380 // Remove unused channels if MediaContentDescription is rejected.
2381 RemoveUnusedChannels(remote_description()->description());
2382 }
Steve Anton8a006912017-12-04 23:25:562383
Zhi Huange830e682018-03-30 17:48:352384 // NOTE: Candidates allocation will be initiated only when
2385 // SetLocalDescription is called.
2386 error = UpdateSessionState(type, cricket::CS_REMOTE,
2387 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562388 if (!error.ok()) {
2389 return error;
2390 }
2391
2392 if (local_description() &&
2393 !UseCandidatesInSessionDescription(remote_description())) {
2394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2395 }
2396
2397 if (old_remote_description) {
2398 for (const cricket::ContentInfo& content :
2399 old_remote_description->description()->contents()) {
2400 // Check if this new SessionDescription contains new ICE ufrag and
2401 // password that indicates the remote peer requests an ICE restart.
2402 // TODO(deadbeef): When we start storing both the current and pending
2403 // remote description, this should reset pending_ice_restarts and compare
2404 // against the current description.
2405 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2406 content.name)) {
Steve Anton3828c062017-12-06 18:34:512407 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562408 pending_ice_restarts_.insert(content.name);
2409 }
2410 } else {
2411 // We retain all received candidates only if ICE is not restarted.
2412 // When ICE is restarted, all previous candidates belong to an old
2413 // generation and should not be kept.
2414 // TODO(deadbeef): This goes against the W3C spec which says the remote
2415 // description should only contain candidates from the last set remote
2416 // description plus any candidates added since then. We should remove
2417 // this once we're sure it won't break anything.
2418 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2419 old_remote_description, content.name, mutable_remote_description());
2420 }
2421 }
2422 }
2423
2424 if (session_error() != SessionError::kNone) {
2425 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2426 }
2427
2428 // Set the the ICE connection state to connecting since the connection may
2429 // become writable with peer reflexive candidates before any remote candidate
2430 // is signaled.
2431 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2432 // is to have a new signal the indicates a change in checking state from the
2433 // transport and expose a new checking() member from transport that can be
2434 // read to determine the current checking state. The existing SignalConnecting
2435 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412436 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172437 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562438 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2439 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2440 }
2441
deadbeefab9b2d12015-10-14 18:33:112442 // If setting the description decided our SSL role, allocate any necessary
2443 // SCTP sids.
2444 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222445 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112446 AllocateSctpSids(role);
2447 }
2448
Steve Antondcc3c022017-12-23 00:02:542449 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422450 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182451 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362452 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132453 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182454 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542455 for (auto transceiver : transceivers_) {
2456 const ContentInfo* content =
2457 FindMediaSectionForTransceiver(transceiver, remote_description());
2458 if (!content) {
2459 continue;
2460 }
2461 const MediaContentDescription* media_desc = content->media_description();
2462 RtpTransceiverDirection local_direction =
2463 RtpTransceiverDirectionReversed(media_desc->direction());
2464 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2465 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2466 // transceiver's current direction is neither sendrecv nor recvonly,
2467 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362468 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422469 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332470 // The remote description has signaled the stream IDs.
2471 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422472 }
Steve Antondcc3c022017-12-23 00:02:542473 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362474 (!transceiver->fired_direction() ||
2475 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232476 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362477 << content->name << " (added to "
2478 << GetStreamIdsString(stream_ids) << ").";
2479
2480 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2481 for (const std::string& stream_id : stream_ids) {
2482 rtc::scoped_refptr<MediaStreamInterface> stream =
2483 remote_streams_->find(stream_id);
2484 if (!stream) {
2485 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2486 MediaStream::Create(stream_id));
2487 remote_streams_->AddStream(stream);
2488 added_streams.push_back(stream);
2489 }
2490 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202491 }
Steve Anton3172c032018-05-03 22:30:182492 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 18:51:532493 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2494 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 23:31:362495 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 22:30:182496 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542497 }
Steve Anton0f5400a2018-07-17 21:25:362498 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2499 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2500 // removal of a remote track for the media description, given transceiver,
2501 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:542502 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362503 (transceiver->fired_direction() &&
2504 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2505 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2506 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542507 }
Steve Anton0f5400a2018-07-17 21:25:362508 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2509 transceiver->internal()->set_fired_direction(local_direction);
2510 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2511 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542512 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362513 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2514 // direction.
Steve Antondcc3c022017-12-23 00:02:542515 transceiver->internal()->set_current_direction(local_direction);
2516 }
Steve Anton0f5400a2018-07-17 21:25:362517 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2518 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:542519 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232520 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2521 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542522 transceiver->Stop();
2523 }
Seth Hampson2f0d7022018-02-20 19:54:422524 if (!content->rejected &&
2525 RtpTransceiverDirectionHasRecv(local_direction)) {
2526 // Set ssrc to 0 in the case of an unsignalled ssrc.
2527 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332528 if (!media_desc->streams().empty() &&
2529 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422530 ssrc = media_desc->streams()[0].first_ssrc();
2531 }
2532 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022533 }
Steve Antondcc3c022017-12-23 00:02:542534 }
Steve Antonc49bcd92018-02-14 22:28:132535 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162536 auto observer = Observer();
Steve Anton3172c032018-05-03 22:30:182537 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162538 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162539 observer->OnTrack(transceiver);
2540 observer->OnAddTrack(transceiver->receiver(),
2541 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202542 }
Steve Antonc49bcd92018-02-14 22:28:132543 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162544 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132545 }
Steve Anton0f5400a2018-07-17 21:25:362546 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162547 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182548 }
2549 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162550 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182551 }
Steve Antondcc3c022017-12-23 00:02:542552 }
2553
Henrik Boströmfdb92012017-11-09 18:55:442554 const cricket::ContentInfo* audio_content =
2555 GetFirstAudioContent(remote_description()->description());
2556 const cricket::ContentInfo* video_content =
2557 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402558 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442559 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402560 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442561 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402562 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442563 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402564
2565 // Check if the descriptions include streams, just in case the peer supports
2566 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442567 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402568 (audio_desc && !audio_desc->streams().empty()) ||
2569 (video_desc && !video_desc->streams().empty())) {
2570 remote_peer_supports_msid_ = true;
2571 }
deadbeefab9b2d12015-10-14 18:33:112572
2573 // We wait to signal new streams until we finish processing the description,
2574 // since only at that point will new streams have all their tracks.
2575 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2576
Steve Antondcc3c022017-12-23 00:02:542577 if (!IsUnifiedPlan()) {
2578 // TODO(steveanton): When removing RTP senders/receivers in response to a
2579 // rejected media section, there is some cleanup logic that expects the
2580 // voice/ video channel to still be set. But in this method the voice/video
2581 // channel would have been destroyed by the SetRemoteDescription caller
2582 // above so the cleanup that relies on them fails to run. The RemoveSenders
2583 // calls should be moved to right before the DestroyChannel calls to fix
2584 // this.
Steve Anton8d3444d2017-10-20 22:30:512585
Steve Antondcc3c022017-12-23 00:02:542586 // Find all audio rtp streams and create corresponding remote AudioTracks
2587 // and MediaStreams.
2588 if (audio_content) {
2589 if (audio_content->rejected) {
2590 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2591 } else {
2592 bool default_audio_track_needed =
2593 !remote_peer_supports_msid_ &&
2594 RtpTransceiverDirectionHasSend(audio_desc->direction());
2595 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2596 default_audio_track_needed, audio_desc->type(),
2597 new_streams);
2598 }
deadbeeffaac4972015-11-12 23:33:072599 }
deadbeefab9b2d12015-10-14 18:33:112600
Steve Antondcc3c022017-12-23 00:02:542601 // Find all video rtp streams and create corresponding remote VideoTracks
2602 // and MediaStreams.
2603 if (video_content) {
2604 if (video_content->rejected) {
2605 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2606 } else {
2607 bool default_video_track_needed =
2608 !remote_peer_supports_msid_ &&
2609 RtpTransceiverDirectionHasSend(video_desc->direction());
2610 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2611 default_video_track_needed, video_desc->type(),
2612 new_streams);
2613 }
deadbeeffaac4972015-11-12 23:33:072614 }
deadbeefab9b2d12015-10-14 18:33:112615
Steve Antondcc3c022017-12-23 00:02:542616 // Update the DataChannels with the information from the remote peer.
2617 if (data_desc) {
2618 if (rtc::starts_with(data_desc->protocol().data(),
2619 cricket::kMediaProtocolRtpPrefix)) {
2620 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2621 }
deadbeefab9b2d12015-10-14 18:33:112622 }
deadbeefab9b2d12015-10-14 18:33:112623
Steve Antondcc3c022017-12-23 00:02:542624 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162625 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542626 for (size_t i = 0; i < new_streams->count(); ++i) {
2627 MediaStreamInterface* new_stream = new_streams->at(i);
2628 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:162629 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542630 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2631 }
deadbeefab9b2d12015-10-14 18:33:112632
Steve Antondcc3c022017-12-23 00:02:542633 UpdateEndedRemoteMediaStreams();
2634 }
deadbeefab9b2d12015-10-14 18:33:112635
Steve Anton8a006912017-12-04 23:25:562636 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332637}
2638
Steve Anton0f5400a2018-07-17 21:25:362639void PeerConnection::ProcessRemovalOfRemoteTrack(
2640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2641 transceiver,
2642 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2643 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2644 RTC_DCHECK(transceiver->mid());
2645 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2646 << *transceiver->mid();
2647 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2648 transceiver->internal()->receiver_internal()->streams();
2649 // This will remove the remote track from the streams.
2650 transceiver->internal()->receiver_internal()->set_stream_ids({});
2651 remove_list->push_back(transceiver);
2652 // Remove any streams that no longer have tracks.
2653 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2654 // of streams, see if the stream was removed by checking if this was the
2655 // last receiver with that stream ID.
2656 for (auto stream : media_streams) {
2657 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2658 remote_streams_->RemoveStream(stream);
2659 removed_streams->push_back(stream);
2660 }
2661 }
2662}
2663
Steve Antondcc3c022017-12-23 00:02:542664RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2665 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482666 const SessionDescriptionInterface& new_session,
2667 const SessionDescriptionInterface* old_local_description,
2668 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542669 RTC_DCHECK(IsUnifiedPlan());
2670
Steve Anton7464fca2018-01-19 19:10:372671 const cricket::ContentGroup* bundle_group = nullptr;
2672 if (new_session.GetType() == SdpType::kOffer) {
2673 auto bundle_group_or_error =
2674 GetEarlyBundleGroup(*new_session.description());
2675 if (!bundle_group_or_error.ok()) {
2676 return bundle_group_or_error.MoveError();
2677 }
2678 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542679 }
Steve Antondcc3c022017-12-23 00:02:542680
Steve Antondcc3c022017-12-23 00:02:542681 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542682 for (size_t i = 0; i < new_contents.size(); ++i) {
2683 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542684 cricket::MediaType media_type = new_content.media_description()->type();
2685 seen_mids_.insert(new_content.name);
2686 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2687 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482688 const cricket::ContentInfo* old_local_content = nullptr;
2689 if (old_local_description &&
2690 i < old_local_description->description()->contents().size()) {
2691 old_local_content =
2692 &old_local_description->description()->contents()[i];
2693 }
2694 const cricket::ContentInfo* old_remote_content = nullptr;
2695 if (old_remote_description &&
2696 i < old_remote_description->description()->contents().size()) {
2697 old_remote_content =
2698 &old_remote_description->description()->contents()[i];
2699 }
Steve Antondcc3c022017-12-23 00:02:542700 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482701 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2702 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542703 if (!transceiver_or_error.ok()) {
2704 return transceiver_or_error.MoveError();
2705 }
2706 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542707 RTCError error =
2708 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2709 if (!error.ok()) {
2710 return error;
2711 }
2712 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232713 if (GetDataMid() && new_content.name != *GetDataMid()) {
2714 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232715 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2716 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232717 continue;
2718 }
2719 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2720 if (!error.ok()) {
2721 return error;
2722 }
Steve Antondcc3c022017-12-23 00:02:542723 } else {
2724 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2725 "Unknown section type.");
2726 }
2727 }
2728
2729 return RTCError::OK();
2730}
2731
2732RTCError PeerConnection::UpdateTransceiverChannel(
2733 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2734 transceiver,
2735 const cricket::ContentInfo& content,
2736 const cricket::ContentGroup* bundle_group) {
2737 RTC_DCHECK(IsUnifiedPlan());
2738 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-14 00:26:052739 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:542740 if (content.rejected) {
2741 if (channel) {
2742 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:052743 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:542744 }
2745 } else {
2746 if (!channel) {
Steve Anton69470252018-02-09 19:43:082747 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352748 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542749 } else {
Steve Anton69470252018-02-09 19:43:082750 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352751 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542752 }
2753 if (!channel) {
2754 LOG_AND_RETURN_ERROR(
2755 RTCErrorType::INTERNAL_ERROR,
2756 "Failed to create channel for mid=" + content.name);
2757 }
2758 transceiver->internal()->SetChannel(channel);
2759 }
2760 }
2761 return RTCError::OK();
2762}
2763
Steve Antonfa2260d2017-12-29 00:38:232764RTCError PeerConnection::UpdateDataChannel(
2765 cricket::ContentSource source,
2766 const cricket::ContentInfo& content,
2767 const cricket::ContentGroup* bundle_group) {
2768 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402769 // If data channels are disabled, ignore this media section. CreateAnswer
2770 // will take care of rejecting it.
2771 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232772 }
2773 if (content.rejected) {
2774 DestroyDataChannel();
2775 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:222776 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:352777 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2779 "Failed to create data channel.");
2780 }
2781 }
2782 if (source == cricket::CS_REMOTE) {
2783 const MediaContentDescription* data_desc = content.media_description();
2784 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2785 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2786 }
2787 }
2788 }
2789 return RTCError::OK();
2790}
2791
Steve Antondcc3c022017-12-23 00:02:542792RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2793PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482794 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542795 size_t mline_index,
2796 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482797 const ContentInfo* old_local_content,
2798 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542799 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482800 // If this is an offer then the m= section might be recycled. If the m=
2801 // section is being recycled (defined as: rejected in the current local or
2802 // remote description and not rejected in new description), dissociate the
2803 // currently associated RtpTransceiver by setting its mid property to null,
2804 // and discard the mapping between the transceiver and its m= section index.
2805 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2806 old_remote_content)) {
2807 // We want to dissociate the transceiver that has the rejected mid.
2808 const std::string& old_mid =
2809 (old_local_content && old_local_content->rejected)
2810 ? old_local_content->name
2811 : old_remote_content->name;
2812 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542813 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232814 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2815 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:432816 old_transceiver->internal()->set_mid(absl::nullopt);
2817 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:542818 }
2819 }
2820 const MediaContentDescription* media_desc = content.media_description();
2821 auto transceiver = GetAssociatedTransceiver(content.name);
2822 if (source == cricket::CS_LOCAL) {
2823 // Find the RtpTransceiver that corresponds to this m= section, using the
2824 // mapping between transceivers and m= section indices established when
2825 // creating the offer.
2826 if (!transceiver) {
2827 transceiver = GetTransceiverByMLineIndex(mline_index);
2828 }
2829 if (!transceiver) {
2830 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2831 "Unknown transceiver");
2832 }
2833 } else {
2834 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2835 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2836 // of the same type...
2837 if (!transceiver &&
2838 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2839 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2840 }
2841 // If no RtpTransceiver was found in the previous step, create one with a
2842 // recvonly direction.
2843 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232844 RTC_LOG(LS_INFO) << "Adding "
2845 << cricket::MediaTypeToString(media_desc->type())
2846 << " transceiver for MID=" << content.name
2847 << " at i=" << mline_index
2848 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:362849 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 20:47:202850 auto sender =
2851 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 18:58:302852 std::string receiver_id;
2853 if (!media_desc->streams().empty()) {
2854 receiver_id = media_desc->streams()[0].id;
2855 } else {
2856 receiver_id = rtc::CreateRandomUuid();
2857 }
2858 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062859 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542860 transceiver->internal()->set_direction(
2861 RtpTransceiverDirection::kRecvOnly);
2862 }
2863 }
2864 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082865 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542866 LOG_AND_RETURN_ERROR(
2867 RTCErrorType::INVALID_PARAMETER,
2868 "Transceiver type does not match media description type.");
2869 }
2870 // Associate the found or created RtpTransceiver with the m= section by
2871 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2872 // section, and establish a mapping between the transceiver and the index of
2873 // the m= section.
2874 transceiver->internal()->set_mid(content.name);
2875 transceiver->internal()->set_mline_index(mline_index);
2876 return std::move(transceiver);
2877}
2878
2879rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2880PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2881 RTC_DCHECK(IsUnifiedPlan());
2882 for (auto transceiver : transceivers_) {
2883 if (transceiver->mid() == mid) {
2884 return transceiver;
2885 }
2886 }
2887 return nullptr;
2888}
2889
2890rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2891PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2892 RTC_DCHECK(IsUnifiedPlan());
2893 for (auto transceiver : transceivers_) {
2894 if (transceiver->internal()->mline_index() == mline_index) {
2895 return transceiver;
2896 }
2897 }
2898 return nullptr;
2899}
2900
2901rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2902PeerConnection::FindAvailableTransceiverToReceive(
2903 cricket::MediaType media_type) const {
2904 RTC_DCHECK(IsUnifiedPlan());
2905 // From JSEP section 5.10 (Applying a Remote Description):
2906 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2907 // the same type that were added to the PeerConnection by addTrack and are not
2908 // associated with any m= section and are not stopped, find the first such
2909 // RtpTransceiver.
2910 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082911 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542912 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2913 !transceiver->stopped()) {
2914 return transceiver;
2915 }
2916 }
2917 return nullptr;
2918}
2919
Steve Antoned10bd92017-12-05 18:52:592920const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2921 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2922 transceiver,
2923 const SessionDescriptionInterface* sdesc) const {
2924 RTC_DCHECK(transceiver);
2925 RTC_DCHECK(sdesc);
2926 if (IsUnifiedPlan()) {
2927 if (!transceiver->internal()->mid()) {
2928 // This transceiver is not associated with a media section yet.
2929 return nullptr;
2930 }
2931 return sdesc->description()->GetContentByName(
2932 *transceiver->internal()->mid());
2933 } else {
2934 // Plan B only allows at most one audio and one video section, so use the
2935 // first media section of that type.
2936 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082937 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592938 }
2939}
2940
deadbeef46c73892016-11-17 03:42:042941PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2942 return configuration_;
2943}
2944
deadbeef293e9262017-01-11 20:28:302945bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2946 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172947 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:102948 if (IsClosed()) {
2949 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2950 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2951 }
2952
Qingsi Wanga2d60672018-04-11 23:57:452953 // According to JSEP, after setLocalDescription, changing the candidate pool
2954 // size is not allowed, and changing the set of ICE servers will not result
2955 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:172956 if (local_description() && configuration.ice_candidate_pool_size !=
2957 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252958 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2959 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302960 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452961 }
Taylor Brandstettera1c30352016-05-13 15:15:112962
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:452963 if (local_description() &&
2964 configuration.use_media_transport != configuration_.use_media_transport) {
2965 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2966 "SetLocalDescription.";
2967 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2968 }
2969
2970 if (remote_description() &&
2971 configuration.use_media_transport != configuration_.use_media_transport) {
2972 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2973 "SetRemoteDescription.";
2974 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2975 }
2976
Benjamin Wright8c27cca2018-10-25 17:16:442977 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 16:07:482978 configuration.use_media_transport_for_data_channels !=
2979 configuration_.use_media_transport_for_data_channels) {
2980 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2981 "after calling SetLocalDescription.";
2982 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2983 }
2984
2985 if (remote_description() &&
2986 configuration.use_media_transport_for_data_channels !=
2987 configuration_.use_media_transport_for_data_channels) {
2988 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2989 "after calling SetRemoteDescription.";
2990 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2991 }
2992
2993 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 17:16:442994 configuration.crypto_options != configuration_.crypto_options) {
2995 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2996 "SetLocalDescription.";
2997 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2998 }
2999
Piotr (Peter) Slatala37227be2018-11-21 15:42:223000 if (configuration.use_media_transport_for_data_channels ||
3001 configuration.use_media_transport) {
3002 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3003 << "Media transport requires MaxBundle policy.";
3004 }
3005
deadbeef293e9262017-01-11 20:28:303006 // The simplest (and most future-compatible) way to tell if the config was
3007 // modified in an invalid way is to copy each property we do support
3008 // modifying, then use operator==. There are far more properties we don't
3009 // support modifying than those we do, and more could be added.
3010 RTCConfiguration modified_config = configuration_;
3011 modified_config.servers = configuration.servers;
3012 modified_config.type = configuration.type;
3013 modified_config.ice_candidate_pool_size =
3014 configuration.ice_candidate_pool_size;
3015 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:053016 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:143017 modified_config.ice_check_interval_strong_connectivity =
3018 configuration.ice_check_interval_strong_connectivity;
3019 modified_config.ice_check_interval_weak_connectivity =
3020 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:573021 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3022 modified_config.ice_unwritable_min_checks =
3023 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:493024 modified_config.stun_candidate_keepalive_interval =
3025 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:403026 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:403027 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:113028 modified_config.active_reset_srtp_params =
3029 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453030 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:483031 modified_config.use_media_transport_for_data_channels =
3032 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 20:28:303033 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:253034 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:303035 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3036 }
3037
Steve Anton038834f2017-07-14 22:59:593038 // Validate the modified configuration.
3039 RTCError validate_error = ValidateConfiguration(modified_config);
3040 if (!validate_error.ok()) {
3041 return SafeSetError(std::move(validate_error), error);
3042 }
3043
deadbeef293e9262017-01-11 20:28:303044 // Note that this isn't possible through chromium, since it's an unsigned
3045 // short in WebIDL.
3046 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:173047 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:303048 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3049 }
3050
3051 // Parse ICE servers before hopping to network thread.
3052 cricket::ServerAddresses stun_servers;
3053 std::vector<cricket::RelayServerConfig> turn_servers;
3054 RTCErrorType parse_error =
3055 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3056 if (parse_error != RTCErrorType::NONE) {
3057 return SafeSetError(parse_error, error);
3058 }
Harald Alvestrand8ebba742018-05-31 12:00:343059 // Note if STUN or TURN servers were supplied.
3060 if (!stun_servers.empty()) {
3061 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3062 }
3063 if (!turn_servers.empty()) {
3064 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3065 }
deadbeef293e9262017-01-11 20:28:303066
3067 // In theory this shouldn't fail.
3068 if (!network_thread()->Invoke<bool>(
3069 RTC_FROM_HERE,
3070 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3071 stun_servers, turn_servers, modified_config.type,
3072 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:403073 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:493074 modified_config.turn_customizer,
3075 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:253076 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:303077 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3078 }
Honghai Zhang4cedf2b2016-08-31 15:18:113079
deadbeefd1a38b52016-12-10 21:15:333080 // As described in JSEP, calling setConfiguration with new ICE servers or
3081 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3082 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:303083 if (modified_config.servers != configuration_.servers ||
3084 modified_config.type != configuration_.type ||
3085 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:293086 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:333087 }
skvladd1f5fda2017-02-04 00:54:053088
Qingsi Wang9c98f0c2018-02-15 23:10:593089 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 19:57:593090 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 16:07:483091 modified_config.use_media_transport ||
3092 modified_config.use_media_transport_for_data_channels
3093 ? factory_->media_transport_factory()
3094 : nullptr);
skvladd1f5fda2017-02-04 00:54:053095
Zhi Huangb57e1692018-06-12 18:41:113096 if (configuration_.active_reset_srtp_params !=
3097 modified_config.active_reset_srtp_params) {
3098 transport_controller_->SetActiveResetSrtpParams(
3099 modified_config.active_reset_srtp_params);
3100 }
3101
deadbeef293e9262017-01-11 20:28:303102 configuration_ = modified_config;
3103 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453104}
3105
henrike@webrtc.org28e20752013-07-10 00:45:363106bool PeerConnection::AddIceCandidate(
3107 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:173108 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:253109 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:103110 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:363111 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:253112 return false;
3113 }
Steve Antond25da372017-11-06 22:50:293114
3115 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103116 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:073117 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:363118 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:293119 return false;
3120 }
3121
3122 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:103123 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:363124 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:293125 return false;
3126 }
3127
3128 bool valid = false;
3129 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3130 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:363131 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:293132 return false;
3133 }
3134
3135 // Add this candidate to the remote session description.
3136 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:103137 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:363138 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:293139 return false;
3140 }
3141
3142 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:363143 bool result = UseCandidate(ice_candidate);
3144 if (result) {
3145 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3146 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3147 } else {
3148 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3149 }
3150 return result;
Steve Antond25da372017-11-06 22:50:293151 } else {
Steve Antonc79268f2018-04-24 16:54:103152 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:363153 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:293154 return true;
3155 }
henrike@webrtc.org28e20752013-07-10 00:45:363156}
3157
Honghai Zhang7fb69db2016-03-14 18:59:183158bool PeerConnection::RemoveIceCandidates(
3159 const std::vector<cricket::Candidate>& candidates) {
3160 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:103161 if (IsClosed()) {
3162 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3163 return false;
3164 }
3165
Steve Antond25da372017-11-06 22:50:293166 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103167 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3168 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293169 return false;
3170 }
3171
3172 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103173 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293174 return false;
3175 }
3176
3177 size_t number_removed =
3178 mutable_remote_description()->RemoveCandidates(candidates);
3179 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253180 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103181 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073182 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253183 << " are removed.";
Steve Antond25da372017-11-06 22:50:293184 }
3185
3186 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353187 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3188 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103189 RTC_LOG(LS_ERROR)
3190 << "RemoveIceCandidates: Error when removing remote candidates: "
3191 << error.message();
Steve Antond25da372017-11-06 22:50:293192 }
3193 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183194}
3195
Niels Möller0c4f7be2018-05-07 12:01:373196RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023197 if (!worker_thread()->IsCurrent()) {
3198 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053199 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373200 }
3201
Niels Möller0c4f7be2018-05-07 12:01:373202 const bool has_min = bitrate.min_bitrate_bps.has_value();
3203 const bool has_start = bitrate.start_bitrate_bps.has_value();
3204 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373205 if (has_min && *bitrate.min_bitrate_bps < 0) {
3206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3207 "min_bitrate_bps <= 0");
3208 }
Niels Möller0c4f7be2018-05-07 12:01:373209 if (has_start) {
3210 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373212 "start_bitrate_bps < min_bitrate_bps");
3213 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3215 "curent_bitrate_bps < 0");
3216 }
3217 }
3218 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053219 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373221 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373222 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3224 "max_bitrate_bps < min_bitrate_bps");
3225 } else if (*bitrate.max_bitrate_bps < 0) {
3226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3227 "max_bitrate_bps < 0");
3228 }
3229 }
3230
zstein4b979802017-06-02 21:37:373231 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373232 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373233
3234 return RTCError::OK();
3235}
3236
Alex Narest78609d52017-10-20 08:37:473237void PeerConnection::SetBitrateAllocationStrategy(
3238 std::unique_ptr<rtc::BitrateAllocationStrategy>
3239 bitrate_allocation_strategy) {
3240 rtc::Thread* worker_thread = factory_->worker_thread();
3241 if (!worker_thread->IsCurrent()) {
3242 rtc::BitrateAllocationStrategy* strategy_raw =
3243 bitrate_allocation_strategy.release();
3244 auto functor = [this, strategy_raw]() {
3245 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 09:40:333246 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 08:37:473247 };
3248 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3249 return;
3250 }
3251 RTC_DCHECK(call_.get());
3252 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3253}
3254
henrika5f6bf242017-11-01 10:06:563255void PeerConnection::SetAudioPlayout(bool playout) {
3256 if (!worker_thread()->IsCurrent()) {
3257 worker_thread()->Invoke<void>(
3258 RTC_FROM_HERE,
3259 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3260 return;
3261 }
3262 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553263 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563264 audio_state->SetPlayout(playout);
3265}
3266
3267void PeerConnection::SetAudioRecording(bool recording) {
3268 if (!worker_thread()->IsCurrent()) {
3269 worker_thread()->Invoke<void>(
3270 RTC_FROM_HERE,
3271 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3272 return;
3273 }
3274 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553275 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563276 audio_state->SetRecording(recording);
3277}
3278
Steve Anton8c0f7a72017-10-03 17:03:103279std::unique_ptr<rtc::SSLCertificate>
3280PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513281 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3282 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103283 return nullptr;
3284 }
Steve Antonf25303e2018-10-16 22:23:313285 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:103286}
3287
Zhi Huang70b820f2018-01-27 22:16:153288std::unique_ptr<rtc::SSLCertChain>
3289PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373290 auto audio_transceiver = GetFirstAudioTransceiver();
3291 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153292 return nullptr;
3293 }
Zhi Huang70b820f2018-01-27 22:16:153294 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373295 audio_transceiver->internal()->channel()->transport_name());
3296}
3297
3298rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3299PeerConnection::GetFirstAudioTransceiver() const {
3300 for (auto transceiver : transceivers_) {
3301 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3302 return transceiver;
3303 }
3304 }
3305 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153306}
3307
ivoc14d5dbe2016-07-04 14:06:553308bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3309 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403310 // TODO(eladalon): It would be better to not allow negative values into PC.
3311 const size_t max_size = (max_size_bytes < 0)
3312 ? RtcEventLog::kUnlimitedOutput
3313 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 14:43:013314 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3315 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3316 output_period_ms = 5000;
3317 }
Elad Alon99c3fe52017-10-13 14:29:403318 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333319 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 14:43:013320 output_period_ms);
Elad Alon99c3fe52017-10-13 14:29:403321}
3322
Bjorn Tereliusde939432017-11-20 16:38:143323bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3324 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063325 // TODO(eladalon): In C++14, this can be done with a lambda.
3326 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143327 bool operator()() {
3328 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3329 }
Karl Wibergd6b48192017-10-16 21:01:063330 PeerConnection* const pc;
3331 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143332 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403333 };
Bjorn Tereliusde939432017-11-20 16:38:143334 return worker_thread()->Invoke<bool>(
3335 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553336}
3337
3338void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023339 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553340 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3341}
3342
henrike@webrtc.org28e20752013-07-10 00:45:363343const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173344 return pending_local_description_ ? pending_local_description_.get()
3345 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363346}
3347
3348const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173349 return pending_remote_description_ ? pending_remote_description_.get()
3350 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363351}
3352
deadbeeffe4a8a42016-12-21 01:56:173353const SessionDescriptionInterface* PeerConnection::current_local_description()
3354 const {
Steve Anton75737c02017-11-06 18:37:173355 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173356}
3357
3358const SessionDescriptionInterface* PeerConnection::current_remote_description()
3359 const {
Steve Anton75737c02017-11-06 18:37:173360 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173361}
3362
3363const SessionDescriptionInterface* PeerConnection::pending_local_description()
3364 const {
Steve Anton75737c02017-11-06 18:37:173365 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173366}
3367
3368const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3369 const {
Steve Anton75737c02017-11-06 18:37:173370 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173371}
3372
henrike@webrtc.org28e20752013-07-10 00:45:363373void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173374 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363375 // Update stats here so that we have the most recent stats for tracks and
3376 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263377 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363378
Steve Anton75737c02017-11-06 18:37:173379 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343380 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083381
Steve Anton8af21862017-12-15 19:20:133382 for (auto transceiver : transceivers_) {
3383 transceiver->Stop();
3384 }
Steve Anton25cfeb92018-04-26 18:44:003385
3386 // Ensure that all asynchronous stats requests are completed before destroying
3387 // the transport controller below.
3388 if (stats_collector_) {
3389 stats_collector_->WaitForPendingRequest();
3390 }
3391
3392 // Don't destroy BaseChannels until after stats has been cleaned up so that
3393 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133394 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173395
Qingsi Wang93a84392018-01-31 01:13:093396 // The event log is used in the transport controller, which must be outlived
3397 // by the former. CreateOffer by the peer connection is implemented
3398 // asynchronously and if the peer connection is closed without resetting the
3399 // WebRTC session description factory, the session description factory would
3400 // call the transport controller.
3401 webrtc_session_desc_factory_.reset();
3402 transport_controller_.reset();
3403
deadbeef42a42632017-03-10 23:18:003404 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053405 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3406 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023407
Steve Anton978b8762017-09-29 19:15:023408 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153409 call_.reset();
3410 // The event log must outlive call (and any other object that uses it).
3411 event_log_.reset();
3412 });
Harald Alvestrand8ebba742018-05-31 12:00:343413 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163414 // The .h file says that observer can be discarded after close() returns.
3415 // Make sure this is true.
3416 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:363417}
3418
Steve Antonad182762018-09-05 20:22:403419void PeerConnection::OnMessage(rtc::Message* msg) {
3420 switch (msg->message_id) {
3421 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3422 SetSessionDescriptionMsg* param =
3423 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3424 param->observer->OnSuccess();
3425 delete param;
3426 break;
3427 }
3428 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3429 SetSessionDescriptionMsg* param =
3430 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3431 param->observer->OnFailure(std::move(param->error));
3432 delete param;
3433 break;
3434 }
3435 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3436 CreateSessionDescriptionMsg* param =
3437 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3438 param->observer->OnFailure(std::move(param->error));
3439 delete param;
3440 break;
3441 }
3442 case MSG_GETSTATS: {
3443 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3444 StatsReports reports;
3445 stats_->GetStats(param->track, &reports);
3446 param->observer->OnComplete(reports);
3447 delete param;
3448 break;
3449 }
3450 case MSG_FREE_DATACHANNELS: {
3451 sctp_data_channels_to_free_.clear();
3452 break;
3453 }
3454 case MSG_REPORT_USAGE_PATTERN: {
3455 ReportUsagePattern();
3456 break;
3457 }
3458 default:
3459 RTC_NOTREACHED() << "Not implemented";
3460 break;
3461 }
3462}
3463
Steve Antonafb0bb72018-02-20 19:35:373464cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3465 RTC_DCHECK(!IsUnifiedPlan());
3466 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3467 GetAudioTransceiver()->internal()->channel());
3468 if (voice_channel) {
3469 return voice_channel->media_channel();
3470 } else {
3471 return nullptr;
3472 }
3473}
3474
3475cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3476 RTC_DCHECK(!IsUnifiedPlan());
3477 auto* video_channel = static_cast<cricket::VideoChannel*>(
3478 GetVideoTransceiver()->internal()->channel());
3479 if (video_channel) {
3480 return video_channel->media_channel();
3481 } else {
3482 return nullptr;
3483 }
3484}
3485
Steve Anton4171afb2017-11-20 18:20:223486void PeerConnection::CreateAudioReceiver(
3487 MediaStreamInterface* stream,
3488 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513489 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3490 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533491 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3492 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023493 auto* audio_receiver = new AudioRtpReceiver(
3494 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053495 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023496 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3497 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3498 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223499 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163500 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343501 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363502}
3503
Steve Anton4171afb2017-11-20 18:20:223504void PeerConnection::CreateVideoReceiver(
3505 MediaStreamInterface* stream,
3506 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513507 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3508 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533509 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3510 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023511 auto* video_receiver = new VideoRtpReceiver(
3512 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053513 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023514 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3515 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3516 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223517 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163518 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343519 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363520}
3521
deadbeef70ab1a12015-09-28 23:53:553522// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3523// description.
Henrik Boström933d8b02017-10-10 17:05:163524rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223525 const RtpSenderInfo& remote_sender_info) {
3526 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3527 if (!receiver) {
3528 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3529 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163530 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553531 }
Steve Anton4171afb2017-11-20 18:20:223532 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3533 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3534 } else {
3535 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3536 }
Henrik Boström933d8b02017-10-10 17:05:163537 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363538}
3539
korniltsev.anatolyec390b52017-07-25 00:00:253540void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3541 MediaStreamInterface* stream) {
3542 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363543 RTC_DCHECK(track);
3544 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253545 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223546 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253547 // We already have a sender for this track, so just change the stream_id
3548 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363549 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253550 return;
3551 }
3552
3553 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363554 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203555 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053556 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223557 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253558 // If the sender has already been configured in SDP, we call SetSsrc,
3559 // which will connect the sender to the underlying transport. This can
3560 // occur if a local session description that contains the ID of the sender
3561 // is set before AddStream is called. It can also occur if the local
3562 // session description is not changed and RemoveStream is called, and
3563 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223564 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183565 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223566 if (sender_info) {
3567 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253568 }
3569}
3570
3571// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3572// indefinitely, when we have unified plan SDP.
3573void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3574 MediaStreamInterface* stream) {
3575 RTC_DCHECK(!IsClosed());
3576 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223577 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253578 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3579 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253580 return;
3581 }
Steve Anton4171afb2017-11-20 18:20:223582 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253583}
3584
3585void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3586 MediaStreamInterface* stream) {
3587 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363588 RTC_DCHECK(track);
3589 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253590 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223591 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253592 // We already have a sender for this track, so just change the stream_id
3593 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363594 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253595 return;
3596 }
3597
3598 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363599 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203600 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053601 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223602 GetVideoTransceiver()->internal()->AddSender(new_sender);
3603 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183604 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223605 if (sender_info) {
3606 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253607 }
3608}
3609
3610void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3611 MediaStreamInterface* stream) {
3612 RTC_DCHECK(!IsClosed());
3613 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223614 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253615 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3616 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253617 return;
3618 }
Steve Anton4171afb2017-11-20 18:20:223619 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253620}
3621
Steve Antonba818672017-11-06 18:21:573622void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283623 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573624 if (ice_connection_state_ == new_state) {
3625 return;
3626 }
3627
deadbeefcbecd352015-09-23 18:50:273628 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573629 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113630 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273631 return;
3632 }
Steve Antonba818672017-11-06 18:21:573633
Mirko Bonadei675513b2017-11-09 10:09:253634 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3635 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573636 RTC_DCHECK(ice_connection_state_ !=
3637 PeerConnectionInterface::kIceConnectionClosed);
3638
henrike@webrtc.org28e20752013-07-10 00:45:363639 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163640 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363641}
3642
Alex Loiko9289eda2018-11-23 16:18:593643void PeerConnection::SetStandardizedIceConnectionState(
3644 PeerConnectionInterface::IceConnectionState new_state) {
3645 RTC_DCHECK(signaling_thread()->IsCurrent());
3646 if (standardized_ice_connection_state_ == new_state)
3647 return;
3648 if (IsClosed())
3649 return;
3650 standardized_ice_connection_state_ = new_state;
3651 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3652 // the old one once disconnects are handled properly.
3653}
3654
Jonas Olsson635474e2018-10-18 13:58:173655void PeerConnection::SetConnectionState(
3656 PeerConnectionInterface::PeerConnectionState new_state) {
3657 RTC_DCHECK(signaling_thread()->IsCurrent());
3658 if (connection_state_ == new_state)
3659 return;
3660 if (IsClosed())
3661 return;
3662 connection_state_ = new_state;
3663 Observer()->OnConnectionChange(new_state);
3664}
3665
henrike@webrtc.org28e20752013-07-10 00:45:363666void PeerConnection::OnIceGatheringChange(
3667 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283668 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363669 if (IsClosed()) {
3670 return;
3671 }
3672 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163673 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363674}
3675
jbauch81bf7b02017-03-25 15:31:123676void PeerConnection::OnIceCandidate(
3677 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283678 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253679 if (IsClosed()) {
3680 return;
3681 }
Harald Alvestrand8ebba742018-05-31 12:00:343682 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:583683 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3684 candidate->candidate().address().IsPrivateIP()) {
3685 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3686 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163687 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363688}
3689
Honghai Zhang7fb69db2016-03-14 18:59:183690void PeerConnection::OnIceCandidatesRemoved(
3691 const std::vector<cricket::Candidate>& candidates) {
3692 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253693 if (IsClosed()) {
3694 return;
3695 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163696 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:183697}
3698
henrike@webrtc.org28e20752013-07-10 00:45:363699void PeerConnection::ChangeSignalingState(
3700 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573701 RTC_DCHECK(signaling_thread()->IsCurrent());
3702 if (signaling_state_ == signaling_state) {
3703 return;
3704 }
Mirko Bonadei675513b2017-11-09 10:09:253705 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3706 << GetSignalingStateString(signaling_state_)
3707 << " New state: "
3708 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363709 signaling_state_ = signaling_state;
3710 if (signaling_state == kClosed) {
3711 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:163712 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:593713 standardized_ice_connection_state_ =
3714 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:173715 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3716 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363717 if (ice_gathering_state_ != kIceGatheringComplete) {
3718 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:163719 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363720 }
3721 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163722 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363723}
3724
deadbeefeb459812015-12-16 03:24:433725void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3726 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253727 if (IsClosed()) {
3728 return;
3729 }
korniltsev.anatolyec390b52017-07-25 00:00:253730 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163731 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433732}
3733
deadbeefeb459812015-12-16 03:24:433734void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3735 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253736 if (IsClosed()) {
3737 return;
3738 }
korniltsev.anatolyec390b52017-07-25 00:00:253739 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163740 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433741}
3742
3743void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3744 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253745 if (IsClosed()) {
3746 return;
3747 }
korniltsev.anatolyec390b52017-07-25 00:00:253748 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163749 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433750}
3751
3752void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3753 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253754 if (IsClosed()) {
3755 return;
3756 }
korniltsev.anatolyec390b52017-07-25 00:00:253757 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163758 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433759}
3760
Henrik Boström31638672017-11-23 16:48:323761void PeerConnection::PostSetSessionDescriptionSuccess(
3762 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:403763 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3764 signaling_thread()->Post(RTC_FROM_HERE, this,
3765 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:323766}
3767
deadbeefab9b2d12015-10-14 18:33:113768void PeerConnection::PostSetSessionDescriptionFailure(
3769 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:403770 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:033771 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403772 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3773 msg->error = std::move(error);
3774 signaling_thread()->Post(RTC_FROM_HERE, this,
3775 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113776}
3777
3778void PeerConnection::PostCreateSessionDescriptionFailure(
3779 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033780 RTCError error) {
3781 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403782 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3783 msg->error = std::move(error);
3784 signaling_thread()->Post(RTC_FROM_HERE, this,
3785 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113786}
3787
zhihuang1c378ed2017-08-17 21:10:503788void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543789 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113790 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543791 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503792
Steve Antondcc3c022017-12-23 00:02:543793 if (IsUnifiedPlan()) {
3794 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3795 } else {
3796 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3797 }
3798
Steve Antonfa2260d2017-12-29 00:38:233799 // Intentionally unset the data channel type for RTP data channel with the
3800 // second condition. Otherwise the RTP data channels would be successfully
3801 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3802 // when building with chromium. We want to leave RTP data channels broken, so
3803 // people won't try to use them.
3804 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3805 session_options->data_channel_type = data_channel_type();
3806 }
3807
Steve Antondcc3c022017-12-23 00:02:543808 // Apply ICE restart flag and renomination flag.
3809 for (auto& options : session_options->media_description_options) {
3810 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3811 options.transport_options.enable_ice_renomination =
3812 configuration_.enable_ice_renomination;
3813 }
3814
3815 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:443816 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 20:22:163817 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 05:47:123818 session_options->pooled_ice_credentials =
3819 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3820 RTC_FROM_HERE,
3821 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3822 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 09:25:483823 session_options->offer_extmap_allow_mixed =
3824 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-23 00:02:543825}
3826
3827void PeerConnection::GetOptionsForPlanBOffer(
3828 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3829 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503830 // Figure out transceiver directional preferences.
3831 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3832 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3833
3834 // By default, generate sendrecv/recvonly m= sections.
3835 bool recv_audio = true;
3836 bool recv_video = true;
3837
3838 // By default, only offer a new m= section if we have media to send with it.
3839 bool offer_new_audio_description = send_audio;
3840 bool offer_new_video_description = send_video;
3841 bool offer_new_data_description = HasDataChannels();
3842
3843 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543844 if (offer_answer_options.offer_to_receive_audio !=
3845 RTCOfferAnswerOptions::kUndefined) {
3846 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503847 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543848 offer_new_audio_description ||
3849 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503850 }
Steve Antondcc3c022017-12-23 00:02:543851 if (offer_answer_options.offer_to_receive_video !=
3852 RTCOfferAnswerOptions::kUndefined) {
3853 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503854 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543855 offer_new_video_description ||
3856 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503857 }
3858
Danil Chapovalov66cadcc2018-06-19 14:47:433859 absl::optional<size_t> audio_index;
3860 absl::optional<size_t> video_index;
3861 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:503862 // If a current description exists, generate m= sections in the same order,
3863 // using the first audio/video/data section that appears and rejecting
3864 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173865 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503866 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173867 local_description(),
Steve Anton1d03a752017-11-27 22:30:093868 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3869 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3870 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113871 }
3872
zhihuang1c378ed2017-08-17 21:10:503873 // Add audio/video/data m= sections to the end if needed.
3874 if (!audio_index && offer_new_audio_description) {
3875 session_options->media_description_options.push_back(
3876 cricket::MediaDescriptionOptions(
3877 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093878 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3879 false));
Oskar Sundbom9b28a032017-11-16 09:53:303880 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453881 }
zhihuang1c378ed2017-08-17 21:10:503882 if (!video_index && offer_new_video_description) {
3883 session_options->media_description_options.push_back(
3884 cricket::MediaDescriptionOptions(
3885 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093886 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3887 false));
Oskar Sundbom9b28a032017-11-16 09:53:303888 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453889 }
zhihuang1c378ed2017-08-17 21:10:503890 if (!data_index && offer_new_data_description) {
3891 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233892 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303893 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503894 }
3895
3896 cricket::MediaDescriptionOptions* audio_media_description_options =
3897 !audio_index ? nullptr
3898 : &session_options->media_description_options[*audio_index];
3899 cricket::MediaDescriptionOptions* video_media_description_options =
3900 !video_index ? nullptr
3901 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503902
Steve Anton4171afb2017-11-20 18:20:223903 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:373904 video_media_description_options,
3905 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:543906}
3907
3908// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3909// and return a reference to it.
3910// Generated MIDs should be no more than 3 bytes long to take up less space in
3911// the RTP packet.
3912static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3913 RTC_DCHECK(used_mids);
3914 // We're boring: just generate MIDs 0, 1, 2, ...
3915 size_t i = 0;
3916 std::set<std::string>::iterator it;
3917 bool inserted;
3918 do {
3919 std::string mid = rtc::ToString(i++);
3920 auto insert_result = used_mids->insert(mid);
3921 it = insert_result.first;
3922 inserted = insert_result.second;
3923 } while (!inserted);
3924 return *it;
3925}
3926
3927static cricket::MediaDescriptionOptions
3928GetMediaDescriptionOptionsForTransceiver(
3929 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3930 transceiver,
3931 const std::string& mid) {
3932 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083933 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543934 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303935 // This behavior is specified in JSEP. The gist is that:
3936 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3937 // sendrecv.
3938 // 2. If the MSID is included, then it must be included in any subsequent
3939 // offer/answer exactly the same until the RtpTransceiver is stopped.
3940 if (!transceiver->stopped() &&
3941 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3942 transceiver->internal()->has_ever_been_used_to_send())) {
3943 cricket::SenderOptions sender_options;
3944 sender_options.track_id = transceiver->sender()->id();
3945 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 20:47:203946 int num_send_encoding_layers =
3947 transceiver->sender()->init_send_encodings().size();
3948 sender_options.num_sim_layers =
3949 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 18:58:303950 media_description_options.sender_options.push_back(sender_options);
3951 }
Steve Antondcc3c022017-12-23 00:02:543952 return media_description_options;
3953}
3954
3955void PeerConnection::GetOptionsForUnifiedPlanOffer(
3956 const RTCOfferAnswerOptions& offer_answer_options,
3957 cricket::MediaSessionOptions* session_options) {
3958 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3959 // Offers) and 5.2.2 (Subsequent Offers).
3960 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3961 const ContentInfos& local_contents =
3962 (local_description() ? local_description()->description()->contents()
3963 : ContentInfos());
3964 const ContentInfos& remote_contents =
3965 (remote_description() ? remote_description()->description()->contents()
3966 : ContentInfos());
3967 // The mline indices that can be recycled. New transceivers should reuse these
3968 // slots first.
3969 std::queue<size_t> recycleable_mline_indices;
3970 // Track the MIDs used in previous offer/answer exchanges and the current
3971 // offer so that new, unique MIDs are generated.
3972 std::set<std::string> used_mids = seen_mids_;
3973 // First, go through each media section that exists in either the local or
3974 // remote description and generate a media section in this offer for the
3975 // associated transceiver. If a media section can be recycled, generate a
3976 // default, rejected media section here that can be later overwritten.
3977 for (size_t i = 0;
3978 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3979 // Either |local_content| or |remote_content| is non-null.
3980 const ContentInfo* local_content =
3981 (i < local_contents.size() ? &local_contents[i] : nullptr);
3982 const ContentInfo* remote_content =
3983 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3984 bool had_been_rejected = (local_content && local_content->rejected) ||
3985 (remote_content && remote_content->rejected);
3986 const std::string& mid =
3987 (local_content ? local_content->name : remote_content->name);
3988 cricket::MediaType media_type =
3989 (local_content ? local_content->media_description()->type()
3990 : remote_content->media_description()->type());
3991 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3992 media_type == cricket::MEDIA_TYPE_VIDEO) {
3993 auto transceiver = GetAssociatedTransceiver(mid);
3994 RTC_CHECK(transceiver);
3995 // A media section is considered eligible for recycling if it is marked as
3996 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483997 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543998 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083999 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4000 RtpTransceiverDirection::kInactive,
4001 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:544002 recycleable_mline_indices.push(i);
4003 } else {
4004 session_options->media_description_options.push_back(
4005 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4006 // CreateOffer shouldn't really cause any state changes in
4007 // PeerConnection, but we need a way to match new transceivers to new
4008 // media sections in SetLocalDescription and JSEP specifies this is done
4009 // by recording the index of the media section generated for the
4010 // transceiver in the offer.
4011 transceiver->internal()->set_mline_index(i);
4012 }
4013 } else {
4014 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:234015 RTC_CHECK(GetDataMid());
4016 if (had_been_rejected || mid != *GetDataMid()) {
4017 session_options->media_description_options.push_back(
4018 GetMediaDescriptionOptionsForRejectedData(mid));
4019 } else {
4020 session_options->media_description_options.push_back(
4021 GetMediaDescriptionOptionsForActiveData(mid));
4022 }
Steve Antondcc3c022017-12-23 00:02:544023 }
4024 }
4025 // Next, look for transceivers that are newly added (that is, are not stopped
4026 // and not associated). Reuse media sections marked as recyclable first,
4027 // otherwise append to the end of the offer. New media sections should be
4028 // added in the order they were added to the PeerConnection.
4029 for (auto transceiver : transceivers_) {
4030 if (transceiver->mid() || transceiver->stopped()) {
4031 continue;
4032 }
4033 size_t mline_index;
4034 if (!recycleable_mline_indices.empty()) {
4035 mline_index = recycleable_mline_indices.front();
4036 recycleable_mline_indices.pop();
4037 session_options->media_description_options[mline_index] =
4038 GetMediaDescriptionOptionsForTransceiver(transceiver,
4039 AllocateMid(&used_mids));
4040 } else {
4041 mline_index = session_options->media_description_options.size();
4042 session_options->media_description_options.push_back(
4043 GetMediaDescriptionOptionsForTransceiver(transceiver,
4044 AllocateMid(&used_mids)));
4045 }
4046 // See comment above for why CreateOffer changes the transceiver's state.
4047 transceiver->internal()->set_mline_index(mline_index);
4048 }
Steve Antonfa2260d2017-12-29 00:38:234049 // Lastly, add a m-section if we have local data channels and an m section
4050 // does not already exist.
4051 if (!GetDataMid() && HasDataChannels()) {
4052 session_options->media_description_options.push_back(
4053 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4054 }
Steve Antondcc3c022017-12-23 00:02:544055}
4056
4057void PeerConnection::GetOptionsForAnswer(
4058 const RTCOfferAnswerOptions& offer_answer_options,
4059 cricket::MediaSessionOptions* session_options) {
4060 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4061
4062 if (IsUnifiedPlan()) {
4063 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4064 } else {
4065 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4066 }
4067
Steve Antonfa2260d2017-12-29 00:38:234068 // Intentionally unset the data channel type for RTP data channel. Otherwise
4069 // the RTP data channels would be successfully negotiated by default and the
4070 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4071 // We want to leave RTP data channels broken, so people won't try to use them.
4072 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4073 session_options->data_channel_type = data_channel_type();
4074 }
4075
Steve Antondcc3c022017-12-23 00:02:544076 // Apply ICE renomination flag.
4077 for (auto& options : session_options->media_description_options) {
4078 options.transport_options.enable_ice_renomination =
4079 configuration_.enable_ice_renomination;
4080 }
zhihuang8f65cdf2016-05-07 01:40:304081
4082 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444083 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 20:22:164084 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 05:47:124085 session_options->pooled_ice_credentials =
4086 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4087 RTC_FROM_HERE,
4088 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4089 port_allocator_.get()));
deadbeefab9b2d12015-10-14 18:33:114090}
4091
Steve Antondcc3c022017-12-23 00:02:544092void PeerConnection::GetOptionsForPlanBAnswer(
4093 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:114094 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504095 // Figure out transceiver directional preferences.
4096 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4097 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4098
4099 // By default, generate sendrecv/recvonly m= sections. The direction is also
4100 // restricted by the direction in the offer.
4101 bool recv_audio = true;
4102 bool recv_video = true;
4103
4104 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544105 if (offer_answer_options.offer_to_receive_audio !=
4106 RTCOfferAnswerOptions::kUndefined) {
4107 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:524108 }
Steve Antondcc3c022017-12-23 00:02:544109 if (offer_answer_options.offer_to_receive_video !=
4110 RTCOfferAnswerOptions::kUndefined) {
4111 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504112 }
4113
Danil Chapovalov66cadcc2018-06-19 14:47:434114 absl::optional<size_t> audio_index;
4115 absl::optional<size_t> video_index;
4116 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:294117
4118 // Generate m= sections that match those in the offer.
4119 // Note that mediasession.cc will handle intersection our preferred
4120 // direction with the offered direction.
4121 GenerateMediaDescriptionOptions(
4122 remote_description(),
4123 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4124 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4125 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:504126
4127 cricket::MediaDescriptionOptions* audio_media_description_options =
4128 !audio_index ? nullptr
4129 : &session_options->media_description_options[*audio_index];
4130 cricket::MediaDescriptionOptions* video_media_description_options =
4131 !video_index ? nullptr
4132 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:504133
Steve Anton4171afb2017-11-20 18:20:224134 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:374135 video_media_description_options,
4136 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544137}
zhihuangaf388472016-11-02 23:49:484138
Steve Antondcc3c022017-12-23 00:02:544139void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4140 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4141 cricket::MediaSessionOptions* session_options) {
4142 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4143 // Answers) and 5.3.2 (Subsequent Answers).
4144 RTC_DCHECK(remote_description());
4145 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4146 for (const ContentInfo& content :
4147 remote_description()->description()->contents()) {
4148 cricket::MediaType media_type = content.media_description()->type();
4149 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4150 media_type == cricket::MEDIA_TYPE_VIDEO) {
4151 auto transceiver = GetAssociatedTransceiver(content.name);
4152 RTC_CHECK(transceiver);
4153 session_options->media_description_options.push_back(
4154 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4155 } else {
4156 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:404157 // Reject all data sections if data channels are disabled.
4158 // Reject a data section if it has already been rejected.
4159 // Reject all data sections except for the first one.
4160 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4161 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:234162 session_options->media_description_options.push_back(
4163 GetMediaDescriptionOptionsForRejectedData(content.name));
4164 } else {
4165 session_options->media_description_options.push_back(
4166 GetMediaDescriptionOptionsForActiveData(content.name));
4167 }
Steve Antondcc3c022017-12-23 00:02:544168 }
4169 }
htaa2a49d92016-03-04 10:51:394170}
4171
zhihuang1c378ed2017-08-17 21:10:504172void PeerConnection::GenerateMediaDescriptionOptions(
4173 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:094174 RtpTransceiverDirection audio_direction,
4175 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:434176 absl::optional<size_t>* audio_index,
4177 absl::optional<size_t>* video_index,
4178 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:394179 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504180 for (const cricket::ContentInfo& content :
4181 session_desc->description()->contents()) {
4182 if (IsAudioContent(&content)) {
4183 // If we already have an audio m= section, reject this extra one.
4184 if (*audio_index) {
4185 session_options->media_description_options.push_back(
4186 cricket::MediaDescriptionOptions(
4187 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:094188 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504189 } else {
4190 session_options->media_description_options.push_back(
4191 cricket::MediaDescriptionOptions(
4192 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:094193 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304194 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504195 }
4196 } else if (IsVideoContent(&content)) {
4197 // If we already have an video m= section, reject this extra one.
4198 if (*video_index) {
4199 session_options->media_description_options.push_back(
4200 cricket::MediaDescriptionOptions(
4201 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:094202 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504203 } else {
4204 session_options->media_description_options.push_back(
4205 cricket::MediaDescriptionOptions(
4206 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:094207 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304208 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504209 }
4210 } else {
4211 RTC_DCHECK(IsDataContent(&content));
4212 // If we already have an data m= section, reject this extra one.
4213 if (*data_index) {
4214 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234215 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504216 } else {
4217 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234218 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304219 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504220 }
4221 }
htaa2a49d92016-03-04 10:51:394222 }
deadbeefab9b2d12015-10-14 18:33:114223}
4224
Steve Antonfa2260d2017-12-29 00:38:234225cricket::MediaDescriptionOptions
4226PeerConnection::GetMediaDescriptionOptionsForActiveData(
4227 const std::string& mid) const {
4228 // Direction for data sections is meaningless, but legacy endpoints might
4229 // expect sendrecv.
4230 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4231 RtpTransceiverDirection::kSendRecv,
4232 /*stopped=*/false);
4233 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4234 return options;
4235}
4236
4237cricket::MediaDescriptionOptions
4238PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4239 const std::string& mid) const {
4240 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4241 RtpTransceiverDirection::kInactive,
4242 /*stopped=*/true);
4243 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4244 return options;
4245}
4246
Danil Chapovalov66cadcc2018-06-19 14:47:434247absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234248 switch (data_channel_type_) {
4249 case cricket::DCT_RTP:
4250 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434251 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234252 }
4253 return rtp_data_channel_->content_name();
4254 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354255 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 19:23:224256 case cricket::DCT_MEDIA_TRANSPORT:
4257 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-29 00:38:234258 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434259 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234260 }
4261}
4262
Steve Anton4171afb2017-11-20 18:20:224263void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4264 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4265 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404266 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074267}
4268
Steve Anton4171afb2017-11-20 18:20:224269void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114270 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224271 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114272 cricket::MediaType media_type,
4273 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364274 RTC_DCHECK(!IsUnifiedPlan());
4275
Steve Anton4171afb2017-11-20 18:20:224276 std::vector<RtpSenderInfo>* current_senders =
4277 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114278
Steve Anton4171afb2017-11-20 18:20:224279 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014280 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224281 for (auto sender_it = current_senders->begin();
4282 sender_it != current_senders->end();
4283 /* incremented manually */) {
4284 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114285 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224286 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094287 std::string params_stream_id;
4288 if (params) {
4289 params_stream_id =
4290 (!params->first_stream_id().empty() ? params->first_stream_id()
4291 : kDefaultStreamId);
4292 }
Seth Hampson5b4f0752018-04-02 23:31:364293 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094294 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404295 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104296 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224297 sender_exists) {
4298 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404299 } else {
Steve Anton4171afb2017-11-20 18:20:224300 OnRemoteSenderRemoved(info, media_type);
4301 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114302 }
4303 }
4304
Steve Anton4171afb2017-11-20 18:20:224305 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114306 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334307 if (!params.has_ssrcs()) {
4308 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4309 // sender, this means it is coming from a Unified Plan endpoint,so we just
4310 // create a default.
4311 default_sender_needed = true;
4312 break;
4313 }
4314
Seth Hampson845e8782018-03-02 19:34:104315 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364316 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334317 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4318 // not supported in Plan B, we just take the first here and create the
4319 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104320 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094321 (!params.first_stream_id().empty() ? params.first_stream_id()
4322 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224323 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114324 uint32_t ssrc = params.first_ssrc();
4325
4326 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104327 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114328 if (!stream) {
4329 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194330 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104331 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114332 remote_streams_->AddStream(stream);
4333 new_streams->AddStream(stream);
4334 }
4335
Steve Anton4171afb2017-11-20 18:20:224336 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184337 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224338 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104339 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224340 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114341 }
4342 }
deadbeefbda7e0b2015-12-09 01:13:404343
Steve Anton4171afb2017-11-20 18:20:224344 // Add default sender if necessary.
4345 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404346 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104347 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404348 if (!default_stream) {
4349 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194350 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104351 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404352 remote_streams_->AddStream(default_stream);
4353 new_streams->AddStream(default_stream);
4354 }
Steve Anton4171afb2017-11-20 18:20:224355 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4356 ? kDefaultAudioSenderId
4357 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104358 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184359 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224360 if (!default_sender_info) {
4361 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104362 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224363 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404364 }
4365 }
deadbeefab9b2d12015-10-14 18:33:114366}
4367
Steve Anton4171afb2017-11-20 18:20:224368void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4369 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234370 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4371 << " receiver for track_id=" << sender_info.sender_id
4372 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114373
Steve Anton3d954a62018-04-02 18:27:234374 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114375 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224376 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114377 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224378 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114379 } else {
nisseeb4ca4e2017-01-12 10:24:274380 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114381 }
4382}
4383
Steve Anton4171afb2017-11-20 18:20:224384void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4385 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094386 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4387 << " receiver for track_id=" << sender_info.sender_id
4388 << " and stream_id=" << sender_info.stream_id;
4389
Seth Hampson845e8782018-03-02 19:34:104390 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114391
Henrik Boström933d8b02017-10-10 17:05:164392 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114393 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194394 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4395 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224396 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114397 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224398 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114399 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114400 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114401 }
4402 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194403 // Stopping or destroying a VideoRtpReceiver will end the
4404 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224405 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114406 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224407 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114408 if (video_track) {
perkjd61bf802016-03-24 10:16:194409 // There's no guarantee the track is still available, e.g. the track may
4410 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114411 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114412 }
4413 } else {
nisseede5da42017-01-12 13:15:364414 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114415 }
Henrik Boström933d8b02017-10-10 17:05:164416 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164417 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164418 }
deadbeefab9b2d12015-10-14 18:33:114419}
4420
4421void PeerConnection::UpdateEndedRemoteMediaStreams() {
4422 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4423 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4424 MediaStreamInterface* stream = remote_streams_->at(i);
4425 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4426 streams_to_remove.push_back(stream);
4427 }
4428 }
4429
Taylor Brandstetter98cde262016-05-31 20:02:214430 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114431 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164432 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114433 }
4434}
4435
Steve Anton4171afb2017-11-20 18:20:224436void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114437 const std::vector<cricket::StreamParams>& streams,
4438 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224439 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114440
Seth Hampson845e8782018-03-02 19:34:104441 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114442 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224443 for (auto sender_it = current_senders->begin();
4444 sender_it != current_senders->end();
4445 /* incremented manually */) {
4446 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114447 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224448 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4449 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104450 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224451 OnLocalSenderRemoved(info, media_type);
4452 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114453 } else {
Steve Anton4171afb2017-11-20 18:20:224454 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114455 }
4456 }
4457
Steve Anton4171afb2017-11-20 18:20:224458 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114459 for (const cricket::StreamParams& params : streams) {
4460 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224461 // sender id.
Seth Hampson845e8782018-03-02 19:34:104462 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224463 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114464 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224465 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184466 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224467 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104468 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224469 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114470 }
4471 }
4472}
4473
Steve Anton4171afb2017-11-20 18:20:224474void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4475 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364476 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224477 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014478 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224479 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4480 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254481 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114482 return;
4483 }
4484
deadbeeffac06552015-11-25 19:26:014485 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254486 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074487 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014488 return;
deadbeefab9b2d12015-10-14 18:33:114489 }
deadbeeffac06552015-11-25 19:26:014490
Seth Hampson5b4f0752018-04-02 23:31:364491 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224492 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114493}
4494
Steve Anton4171afb2017-11-20 18:20:224495void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4496 cricket::MediaType media_type) {
4497 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014498 if (!sender) {
4499 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114500 // SessionDescriptions has been renegotiated.
4501 return;
4502 }
deadbeeffac06552015-11-25 19:26:014503
4504 // A sender has been removed from the SessionDescription but it's still
4505 // associated with the PeerConnection. This only occurs if the SDP doesn't
4506 // match with the calls to CreateSender, AddStream and RemoveStream.
4507 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254508 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074509 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014510 return;
deadbeefab9b2d12015-10-14 18:33:114511 }
deadbeeffac06552015-11-25 19:26:014512
Steve Anton4171afb2017-11-20 18:20:224513 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114514}
4515
4516void PeerConnection::UpdateLocalRtpDataChannels(
4517 const cricket::StreamParamsVec& streams) {
4518 std::vector<std::string> existing_channels;
4519
4520 // Find new and active data channels.
4521 for (const cricket::StreamParams& params : streams) {
4522 // |it->sync_label| is actually the data channel label. The reason is that
4523 // we use the same naming of data channels as we do for
4524 // MediaStreams and Tracks.
4525 // For MediaStreams, the sync_label is the MediaStream label and the
4526 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104527 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114528 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564529 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254530 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114531 continue;
4532 }
4533 // Set the SSRC the data channel should use for sending.
4534 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4535 existing_channels.push_back(data_channel_it->first);
4536 }
4537
4538 UpdateClosingRtpDataChannels(existing_channels, true);
4539}
4540
4541void PeerConnection::UpdateRemoteRtpDataChannels(
4542 const cricket::StreamParamsVec& streams) {
4543 std::vector<std::string> existing_channels;
4544
4545 // Find new and active data channels.
4546 for (const cricket::StreamParams& params : streams) {
4547 // The data channel label is either the mslabel or the SSRC if the mslabel
4548 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104549 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114550 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104551 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114552 auto data_channel_it = rtp_data_channels_.find(label);
4553 if (data_channel_it == rtp_data_channels_.end()) {
4554 // This is a new data channel.
4555 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4556 } else {
4557 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4558 }
4559 existing_channels.push_back(label);
4560 }
4561
4562 UpdateClosingRtpDataChannels(existing_channels, false);
4563}
4564
4565void PeerConnection::UpdateClosingRtpDataChannels(
4566 const std::vector<std::string>& active_channels,
4567 bool is_local_update) {
4568 auto it = rtp_data_channels_.begin();
4569 while (it != rtp_data_channels_.end()) {
4570 DataChannel* data_channel = it->second;
4571 if (std::find(active_channels.begin(), active_channels.end(),
4572 data_channel->label()) != active_channels.end()) {
4573 ++it;
4574 continue;
4575 }
4576
4577 if (is_local_update) {
4578 data_channel->SetSendSsrc(0);
4579 } else {
4580 data_channel->RemotePeerRequestClose();
4581 }
4582
4583 if (data_channel->state() == DataChannel::kClosed) {
4584 rtp_data_channels_.erase(it);
4585 it = rtp_data_channels_.begin();
4586 } else {
4587 ++it;
4588 }
4589 }
4590}
4591
4592void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4593 uint32_t remote_ssrc) {
4594 rtc::scoped_refptr<DataChannel> channel(
4595 InternalCreateDataChannel(label, nullptr));
4596 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254597 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074598 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114599 return;
4600 }
4601 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394602 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4603 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164604 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114605}
4606
4607rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4608 const std::string& label,
4609 const InternalDataChannelInit* config) {
4610 if (IsClosed()) {
4611 return nullptr;
4612 }
Steve Anton75737c02017-11-06 18:37:174613 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254614 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114615 << "InternalCreateDataChannel: Data is not supported in this call.";
4616 return nullptr;
4617 }
4618 InternalDataChannelInit new_config =
4619 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 19:23:224620 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 18:33:114621 if (new_config.id < 0) {
4622 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174623 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114624 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254625 RTC_LOG(LS_ERROR)
4626 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114627 return nullptr;
4628 }
4629 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254630 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074631 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114632 return nullptr;
4633 }
4634 }
4635
Steve Anton75737c02017-11-06 18:37:174636 rtc::scoped_refptr<DataChannel> channel(
4637 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114638 if (!channel) {
4639 sid_allocator_.ReleaseSid(new_config.id);
4640 return nullptr;
4641 }
4642
4643 if (channel->data_channel_type() == cricket::DCT_RTP) {
4644 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254645 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4646 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114647 return nullptr;
4648 }
4649 rtp_data_channels_[channel->label()] = channel;
4650 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:224651 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 18:33:114652 sctp_data_channels_.push_back(channel);
4653 channel->SignalClosed.connect(this,
4654 &PeerConnection::OnSctpDataChannelClosed);
4655 }
4656
Steve Anton2d8609c2018-01-24 00:38:464657 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114658 return channel;
4659}
4660
4661bool PeerConnection::HasDataChannels() const {
4662 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4663}
4664
4665void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4666 for (const auto& channel : sctp_data_channels_) {
4667 if (channel->id() < 0) {
4668 int sid;
4669 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254670 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114671 continue;
4672 }
4673 channel->SetSctpSid(sid);
4674 }
4675 }
4676}
4677
4678void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294679 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114680 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4681 ++it) {
4682 if (it->get() == channel) {
4683 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:324684 // After the closing procedure is done, it's safe to use this ID for
4685 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114686 sid_allocator_.ReleaseSid(channel->id());
4687 }
deadbeefbd292462015-12-15 02:15:294688 // Since this method is triggered by a signal from the DataChannel,
4689 // we can't free it directly here; we need to free it asynchronously.
4690 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114691 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:404692 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4693 nullptr);
deadbeefab9b2d12015-10-14 18:33:114694 return;
4695 }
4696 }
4697}
4698
deadbeefab9b2d12015-10-14 18:33:114699void PeerConnection::OnDataChannelDestroyed() {
4700 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4701 // DataChannel may callback to us and try to modify the list.
4702 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4703 temp_rtp_dcs.swap(rtp_data_channels_);
4704 for (const auto& kv : temp_rtp_dcs) {
4705 kv.second->OnTransportChannelDestroyed();
4706 }
4707
4708 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4709 temp_sctp_dcs.swap(sctp_data_channels_);
4710 for (const auto& channel : temp_sctp_dcs) {
4711 channel->OnTransportChannelDestroyed();
4712 }
4713}
4714
4715void PeerConnection::OnDataChannelOpenMessage(
4716 const std::string& label,
4717 const InternalDataChannelInit& config) {
4718 rtc::scoped_refptr<DataChannel> channel(
4719 InternalCreateDataChannel(label, &config));
4720 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254721 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114722 return;
4723 }
4724
deadbeefa601f5c2016-06-06 21:27:394725 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4726 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164727 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:414728 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:114729}
4730
Bjorn Mellem175aa2e2018-11-08 19:23:224731bool PeerConnection::HandleOpenMessage_s(
4732 const cricket::ReceiveDataParams& params,
4733 const rtc::CopyOnWriteBuffer& buffer) {
4734 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4735 // Received OPEN message; parse and signal that a new data channel should
4736 // be created.
4737 std::string label;
4738 InternalDataChannelInit config;
4739 config.id = params.ssrc;
4740 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4741 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4742 << params.ssrc;
4743 return true;
4744 }
4745 config.open_handshake_role = InternalDataChannelInit::kAcker;
4746 OnDataChannelOpenMessage(label, config);
4747 return true;
4748 }
4749 return false;
4750}
4751
Steve Anton4171afb2017-11-20 18:20:224752rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4753PeerConnection::GetAudioTransceiver() const {
4754 // This method only works with Plan B SDP, where there is a single
4755 // audio/video transceiver.
4756 RTC_DCHECK(!IsUnifiedPlan());
4757 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084758 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224759 return transceiver;
4760 }
4761 }
4762 RTC_NOTREACHED();
4763 return nullptr;
4764}
4765
4766rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4767PeerConnection::GetVideoTransceiver() const {
4768 // This method only works with Plan B SDP, where there is a single
4769 // audio/video transceiver.
4770 RTC_DCHECK(!IsUnifiedPlan());
4771 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084772 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224773 return transceiver;
4774 }
4775 }
4776 RTC_NOTREACHED();
4777 return nullptr;
4778}
4779
4780// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4781// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504782bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224783 switch (type) {
4784 case cricket::MEDIA_TYPE_AUDIO:
4785 return !GetAudioTransceiver()->internal()->senders().empty();
4786 case cricket::MEDIA_TYPE_VIDEO:
4787 return !GetVideoTransceiver()->internal()->senders().empty();
4788 case cricket::MEDIA_TYPE_DATA:
4789 return false;
4790 }
4791 RTC_NOTREACHED();
4792 return false;
zhihuang1c378ed2017-08-17 21:10:504793}
4794
Steve Anton4171afb2017-11-20 18:20:224795rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4796PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4797 for (auto transceiver : transceivers_) {
4798 for (auto sender : transceiver->internal()->senders()) {
4799 if (sender->track() == track) {
4800 return sender;
4801 }
4802 }
4803 }
4804 return nullptr;
deadbeeffac06552015-11-25 19:26:014805}
4806
Steve Anton4171afb2017-11-20 18:20:224807rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4808PeerConnection::FindSenderById(const std::string& sender_id) const {
4809 for (auto transceiver : transceivers_) {
4810 for (auto sender : transceiver->internal()->senders()) {
4811 if (sender->id() == sender_id) {
4812 return sender;
4813 }
4814 }
4815 }
4816 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554817}
4818
Steve Anton4171afb2017-11-20 18:20:224819rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4820PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4821 for (auto transceiver : transceivers_) {
4822 for (auto receiver : transceiver->internal()->receivers()) {
4823 if (receiver->id() == receiver_id) {
4824 return receiver;
4825 }
4826 }
4827 }
4828 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554829}
4830
Steve Anton4171afb2017-11-20 18:20:224831std::vector<PeerConnection::RtpSenderInfo>*
4832PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4833 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4834 media_type == cricket::MEDIA_TYPE_VIDEO);
4835 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4836 ? &remote_audio_sender_infos_
4837 : &remote_video_sender_infos_;
4838}
4839
4840std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114841 cricket::MediaType media_type) {
4842 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4843 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224844 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4845 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114846}
4847
Steve Anton4171afb2017-11-20 18:20:224848const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4849 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184850 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224851 const std::string sender_id) const {
4852 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184853 if (sender_info.stream_id == stream_id &&
4854 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224855 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114856 }
4857 }
4858 return nullptr;
4859}
4860
4861DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4862 for (const auto& channel : sctp_data_channels_) {
4863 if (channel->id() == sid) {
4864 return channel;
4865 }
4866 }
4867 return nullptr;
4868}
4869
deadbeef91dd5672016-05-18 23:55:304870bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:074871 const cricket::ServerAddresses& stun_servers,
4872 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:114873 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-28 00:20:154874 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114875 // To handle both internal and externally created port allocator, we will
4876 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454877 port_allocator_flags_ = port_allocator_->flags();
4878 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4879 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4880 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114881 // If the disable-IPv6 flag was specified, we'll not override it
4882 // by experiment.
4883 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454884 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474885 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4886 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454887 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114888 }
4889
zhihuangb09b3f92017-03-07 22:40:514890 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:454891 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254892 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514893 }
4894
Taylor Brandstettera1c30352016-05-13 15:15:114895 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:454896 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254897 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114898 }
4899
honghaiz60347052016-06-01 01:29:124900 if (configuration.candidate_network_policy ==
4901 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:454902 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254903 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124904 }
4905
Daniel Lazarenko2870b0a2018-01-25 09:30:224906 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:454907 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224908 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4909 }
4910
Qingsi Wanga2d60672018-04-11 23:57:454911 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:114912 // No step delay is used while allocating ports.
4913 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4914 port_allocator_->set_candidate_filter(
4915 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114916 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114917
Harald Alvestrandb2a74782018-06-28 11:54:074918 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:264919 for (auto& turn_server : turn_servers_copy) {
4920 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:254921 }
Taylor Brandstettera1c30352016-05-13 15:15:114922 // Call this last since it may create pooled allocator sessions using the
4923 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494924 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264925 stun_servers, std::move(turn_servers_copy),
4926 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4927 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:494928 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114929 return true;
4930}
4931
deadbeef91dd5672016-05-18 23:55:304932bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304933 const cricket::ServerAddresses& stun_servers,
4934 const std::vector<cricket::RelayServerConfig>& turn_servers,
4935 IceTransportsType type,
4936 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404937 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494938 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 14:47:434939 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114940 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304941 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:454942 // According to JSEP, after setLocalDescription, changing the candidate pool
4943 // size is not allowed, and changing the set of ICE servers will not result
4944 // in new candidates being gathered.
4945 if (local_description()) {
4946 port_allocator_->FreezeCandidatePool();
4947 }
Benjamin Wright6f80f092018-08-14 00:06:264948 // Add the custom tls turn servers if they exist.
4949 auto turn_servers_copy = turn_servers;
4950 for (auto& turn_server : turn_servers_copy) {
4951 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4952 }
Taylor Brandstettera1c30352016-05-13 15:15:114953 // Call this last since it may create pooled allocator sessions using the
4954 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324955 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264956 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4957 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114958}
4959
Steve Antonba818672017-11-06 18:21:574960cricket::ChannelManager* PeerConnection::channel_manager() const {
4961 return factory_->channel_manager();
4962}
4963
Elad Alon99c3fe52017-10-13 14:29:404964bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144965 std::unique_ptr<RtcEventLogOutput> output,
4966 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164967 if (!event_log_) {
4968 return false;
4969 }
Bjorn Tereliusde939432017-11-20 16:38:144970 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554971}
4972
4973void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164974 if (event_log_) {
4975 event_log_->StopLogging();
4976 }
ivoc14d5dbe2016-07-04 14:06:554977}
nisseeaabdf62017-05-05 09:23:024978
Amit Hilbuchdd9390c2018-11-14 00:26:054979cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:174980 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544981 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:054982 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:544983 if (channel && channel->content_name() == content_name) {
4984 return channel;
4985 }
Steve Anton75737c02017-11-06 18:37:174986 }
4987 if (rtp_data_channel() &&
4988 rtp_data_channel()->content_name() == content_name) {
4989 return rtp_data_channel();
4990 }
4991 return nullptr;
4992}
4993
4994bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 19:23:224995 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174996 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254997 RTC_LOG(LS_INFO)
4998 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074999 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175000 return false;
5001 }
Bjorn Mellem175aa2e2018-11-08 19:23:225002 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255003 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:075004 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175005 return false;
5006 }
5007
Bjorn Mellem175aa2e2018-11-08 19:23:225008 absl::optional<rtc::SSLRole> dtls_role;
5009 if (sctp_mid_) {
5010 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5011 } else if (is_caller_) {
5012 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5013 }
Zhi Huange830e682018-03-30 17:48:355014 if (dtls_role) {
5015 *role = *dtls_role;
5016 return true;
5017 }
5018 return false;
Steve Anton75737c02017-11-06 18:37:175019}
5020
5021bool PeerConnection::GetSslRole(const std::string& content_name,
5022 rtc::SSLRole* role) {
5023 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255024 RTC_LOG(LS_INFO)
5025 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075026 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:175027 return false;
5028 }
5029
Zhi Huange830e682018-03-30 17:48:355030 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5031 if (dtls_role) {
5032 *role = *dtls_role;
5033 return true;
5034 }
5035 return false;
Steve Anton75737c02017-11-06 18:37:175036}
5037
Steve Antonf8470812017-12-04 18:46:215038void PeerConnection::SetSessionError(SessionError error,
5039 const std::string& error_desc) {
5040 RTC_DCHECK_RUN_ON(signaling_thread());
5041 if (error != session_error_) {
5042 session_error_ = error;
5043 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:175044 }
5045}
5046
Zhi Huange830e682018-03-30 17:48:355047RTCError PeerConnection::UpdateSessionState(
5048 SdpType type,
5049 cricket::ContentSource source,
5050 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:565051 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175052
5053 // If there's already a pending error then no state transition should happen.
5054 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:215055 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:475056
Steve Anton6d6a2ae2017-12-05 01:19:475057 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:515058 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:595059 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:475060 }
5061
5062 // Update the signaling state according to the specified state machine (see
5063 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:515064 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:475065 ChangeSignalingState(source == cricket::CS_LOCAL
5066 ? PeerConnectionInterface::kHaveLocalOffer
5067 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:515068 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:475069 ChangeSignalingState(source == cricket::CS_LOCAL
5070 ? PeerConnectionInterface::kHaveLocalPrAnswer
5071 : PeerConnectionInterface::kHaveRemotePrAnswer);
5072 } else {
Steve Anton3828c062017-12-06 18:34:515073 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:475074 ChangeSignalingState(PeerConnectionInterface::kStable);
5075 }
5076
5077 // Update internal objects according to the session description's media
5078 // descriptions.
Zhi Huange830e682018-03-30 17:48:355079 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:475080 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:425081 return error;
Steve Anton6d6a2ae2017-12-05 01:19:475082 }
5083
Steve Anton8a006912017-12-04 23:25:565084 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175085}
5086
Steve Anton8a006912017-12-04 23:25:565087RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:515088 SdpType type,
Steve Anton8a006912017-12-04 23:25:565089 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:595090 const SessionDescriptionInterface* sdesc =
5091 (source == cricket::CS_LOCAL ? local_description()
5092 : remote_description());
Steve Anton75737c02017-11-06 18:37:175093 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:595094
5095 // Push down the new SDP media section for each audio/video transceiver.
5096 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:175097 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:595098 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:055099 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595100 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:175101 continue;
5102 }
5103 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:305104 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:595105 if (!content_desc) {
5106 continue;
5107 }
5108 std::string error;
Yves Gerey665174f2018-06-19 13:03:055109 bool success = (source == cricket::CS_LOCAL)
5110 ? channel->SetLocalContent(content_desc, type, &error)
5111 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595112 if (!success) {
5113 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5114 }
5115 }
5116
5117 // If using the RtpDataChannel, push down the new SDP section for it too.
5118 if (rtp_data_channel_) {
5119 const ContentInfo* data_content =
5120 cricket::GetFirstDataContent(sdesc->description());
5121 if (data_content && !data_content->rejected) {
5122 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:305123 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:595124 if (data_desc) {
5125 std::string error;
5126 bool success =
5127 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:515128 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:055129 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595130 if (!success) {
5131 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5132 std::move(error));
5133 }
Steve Anton75737c02017-11-06 18:37:175134 }
5135 }
5136 }
Steve Antoned10bd92017-12-05 18:52:595137
Steve Anton75737c02017-11-06 18:37:175138 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5139 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5140 if (sctp_transport_ && local_description() && remote_description() &&
5141 cricket::GetFirstDataContent(local_description()->description()) &&
5142 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:565143 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:175144 RTC_FROM_HERE,
5145 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:565146 if (!success) {
5147 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5148 "Failed to push down SCTP parameters.");
5149 }
Steve Anton75737c02017-11-06 18:37:175150 }
Steve Antoned10bd92017-12-05 18:52:595151
Steve Anton8a006912017-12-04 23:25:565152 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175153}
5154
5155bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5156 RTC_DCHECK(network_thread()->IsCurrent());
5157 RTC_DCHECK(local_description());
5158 RTC_DCHECK(remote_description());
5159 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5160 // When we support "max-message-size", that would also be pushed down here.
5161 return sctp_transport_->Start(
5162 GetSctpPort(local_description()->description()),
5163 GetSctpPort(remote_description()->description()));
5164}
5165
Steve Anton8a006912017-12-04 23:25:565166RTCError PeerConnection::PushdownTransportDescription(
5167 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:515168 SdpType type) {
Steve Anton8a006912017-12-04 23:25:565169 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175170
Zhi Huange830e682018-03-30 17:48:355171 if (source == cricket::CS_LOCAL) {
5172 const SessionDescriptionInterface* sdesc = local_description();
5173 RTC_DCHECK(sdesc);
5174 return transport_controller_->SetLocalDescription(type,
5175 sdesc->description());
5176 } else {
5177 const SessionDescriptionInterface* sdesc = remote_description();
5178 RTC_DCHECK(sdesc);
5179 return transport_controller_->SetRemoteDescription(type,
5180 sdesc->description());
Steve Anton75737c02017-11-06 18:37:175181 }
Steve Anton75737c02017-11-06 18:37:175182}
5183
5184bool PeerConnection::GetTransportDescription(
5185 const SessionDescription* description,
5186 const std::string& content_name,
5187 cricket::TransportDescription* tdesc) {
5188 if (!description || !tdesc) {
5189 return false;
5190 }
5191 const TransportInfo* transport_info =
5192 description->GetTransportInfoByName(content_name);
5193 if (!transport_info) {
5194 return false;
5195 }
5196 *tdesc = transport_info->description;
5197 return true;
5198}
5199
Steve Anton75737c02017-11-06 18:37:175200cricket::IceConfig PeerConnection::ParseIceConfig(
5201 const PeerConnectionInterface::RTCConfiguration& config) const {
5202 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:175203 switch (config.continual_gathering_policy) {
5204 case PeerConnectionInterface::GATHER_ONCE:
5205 gathering_policy = cricket::GATHER_ONCE;
5206 break;
5207 case PeerConnectionInterface::GATHER_CONTINUALLY:
5208 gathering_policy = cricket::GATHER_CONTINUALLY;
5209 break;
5210 default:
5211 RTC_NOTREACHED();
5212 gathering_policy = cricket::GATHER_ONCE;
5213 }
Qingsi Wang9a5c6f82018-02-01 18:38:405214
Steve Anton75737c02017-11-06 18:37:175215 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235216 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5217 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175218 ice_config.prioritize_most_likely_candidate_pairs =
5219 config.prioritize_most_likely_ice_candidate_pairs;
5220 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:235221 RTCConfigurationToIceConfigOptionalInt(
5222 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175223 ice_config.continual_gathering_policy = gathering_policy;
5224 ice_config.presume_writable_when_fully_relayed =
5225 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:145226 ice_config.ice_check_interval_strong_connectivity =
5227 config.ice_check_interval_strong_connectivity;
5228 ice_config.ice_check_interval_weak_connectivity =
5229 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:175230 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:495231 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175232 ice_config.regather_all_networks_interval_range =
5233 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405234 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175235 return ice_config;
5236}
5237
Steve Anton75737c02017-11-06 18:37:175238bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5239 std::string* track_id) {
5240 if (!local_description()) {
5241 return false;
5242 }
5243 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5244 track_id);
5245}
5246
5247bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5248 std::string* track_id) {
5249 if (!remote_description()) {
5250 return false;
5251 }
5252 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5253 track_id);
5254}
5255
5256bool PeerConnection::SendData(const cricket::SendDataParams& params,
5257 const rtc::CopyOnWriteBuffer& payload,
5258 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 19:23:225259 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5260 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5261 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175262 return false;
5263 }
Bjorn Mellem175aa2e2018-11-08 19:23:225264 if (media_transport_) {
5265 SendDataParams send_params;
5266 send_params.type = ToWebrtcDataMessageType(params.type);
5267 send_params.ordered = params.ordered;
5268 if (params.max_rtx_count >= 0) {
5269 send_params.max_rtx_count = params.max_rtx_count;
5270 } else if (params.max_rtx_ms >= 0) {
5271 send_params.max_rtx_ms = params.max_rtx_ms;
5272 }
5273 return media_transport_->SendData(params.sid, send_params, payload).ok();
5274 }
Steve Anton75737c02017-11-06 18:37:175275 return rtp_data_channel_
5276 ? rtp_data_channel_->SendData(params, payload, result)
5277 : network_thread()->Invoke<bool>(
5278 RTC_FROM_HERE,
5279 Bind(&cricket::SctpTransportInternal::SendData,
5280 sctp_transport_.get(), params, payload, result));
5281}
5282
5283bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225284 RTC_DCHECK_RUN_ON(signaling_thread());
5285 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 18:37:175286 // Don't log an error here, because DataChannels are expected to call
5287 // ConnectDataChannel in this state. It's the only way to initially tell
5288 // whether or not the underlying transport is ready.
5289 return false;
5290 }
Bjorn Mellem175aa2e2018-11-08 19:23:225291 if (media_transport_) {
5292 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5293 &DataChannel::OnChannelReady);
5294 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5295 &DataChannel::OnDataReceived);
5296 SignalMediaTransportChannelClosing_s.connect(
5297 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5298 SignalMediaTransportChannelClosed_s.connect(
5299 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5300 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175301 rtp_data_channel_->SignalReadyToSendData.connect(
5302 webrtc_data_channel, &DataChannel::OnChannelReady);
5303 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5304 &DataChannel::OnDataReceived);
5305 } else {
5306 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5307 &DataChannel::OnChannelReady);
5308 SignalSctpDataReceived.connect(webrtc_data_channel,
5309 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325310 SignalSctpClosingProcedureStartedRemotely.connect(
5311 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5312 SignalSctpClosingProcedureComplete.connect(
5313 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175314 }
5315 return true;
5316}
5317
5318void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225319 RTC_DCHECK_RUN_ON(signaling_thread());
5320 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255321 RTC_LOG(LS_ERROR)
5322 << "DisconnectDataChannel called when rtp_data_channel_ and "
5323 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175324 return;
5325 }
Bjorn Mellem175aa2e2018-11-08 19:23:225326 if (media_transport_) {
5327 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5328 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5329 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5330 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5331 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175332 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5333 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5334 } else {
5335 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5336 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325337 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5338 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175339 }
5340}
5341
5342void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225343 if (media_transport_) {
5344 // No-op. Media transport does not need to add streams.
5345 return;
5346 }
Steve Anton75737c02017-11-06 18:37:175347 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255348 RTC_LOG(LS_ERROR)
5349 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175350 return;
5351 }
5352 network_thread()->Invoke<void>(
5353 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5354 sctp_transport_.get(), sid));
5355}
5356
5357void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225358 if (media_transport_) {
5359 media_transport_->CloseChannel(sid);
5360 return;
5361 }
Steve Anton75737c02017-11-06 18:37:175362 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255363 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075364 "NULL.";
Steve Anton75737c02017-11-06 18:37:175365 return;
5366 }
5367 network_thread()->Invoke<void>(
5368 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5369 sctp_transport_.get(), sid));
5370}
5371
5372bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 19:23:225373 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175374 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 19:23:225375 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 18:37:175376 sctp_ready_to_send_data_;
5377}
5378
Bjorn Mellem175aa2e2018-11-08 19:23:225379void PeerConnection::OnDataReceived(int channel_id,
5380 DataMessageType type,
5381 const rtc::CopyOnWriteBuffer& buffer) {
5382 cricket::ReceiveDataParams params;
5383 params.sid = channel_id;
5384 params.type = ToCricketDataMessageType(type);
5385 media_transport_invoker_->AsyncInvoke<void>(
5386 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5387 RTC_DCHECK_RUN_ON(signaling_thread());
5388 if (!HandleOpenMessage_s(params, buffer)) {
5389 SignalMediaTransportReceivedData_s(params, buffer);
5390 }
5391 });
5392}
5393
5394void PeerConnection::OnChannelClosing(int channel_id) {
5395 media_transport_invoker_->AsyncInvoke<void>(
5396 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5397 RTC_DCHECK_RUN_ON(signaling_thread());
5398 SignalMediaTransportChannelClosing_s(channel_id);
5399 });
5400}
5401
5402void PeerConnection::OnChannelClosed(int channel_id) {
5403 media_transport_invoker_->AsyncInvoke<void>(
5404 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5405 RTC_DCHECK_RUN_ON(signaling_thread());
5406 SignalMediaTransportChannelClosed_s(channel_id);
5407 });
5408}
5409
Danil Chapovalov66cadcc2018-06-19 14:47:435410absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 17:48:355411 if (sctp_mid_ && transport_controller_) {
5412 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5413 if (dtls_transport) {
5414 return dtls_transport->transport_name();
5415 }
Danil Chapovalov66cadcc2018-06-19 14:47:435416 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355417 }
Danil Chapovalov66cadcc2018-06-19 14:47:435418 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355419}
5420
Qingsi Wang72a43a12018-02-21 00:03:185421cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5422 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455423 network_thread()->Invoke<void>(
5424 RTC_FROM_HERE,
5425 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5426 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185427 return candidate_states_list;
5428}
5429
Steve Anton5dfde182018-02-06 18:34:405430std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5431 const {
5432 std::map<std::string, std::string> transport_names_by_mid;
5433 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055434 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:405435 if (channel) {
5436 transport_names_by_mid[channel->content_name()] =
5437 channel->transport_name();
5438 }
Steve Anton75737c02017-11-06 18:37:175439 }
Steve Anton5dfde182018-02-06 18:34:405440 if (rtp_data_channel_) {
5441 transport_names_by_mid[rtp_data_channel_->content_name()] =
5442 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175443 }
5444 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435445 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355446 RTC_DCHECK(transport_name);
5447 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175448 }
Steve Anton5dfde182018-02-06 18:34:405449 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175450}
5451
Steve Anton5dfde182018-02-06 18:34:405452std::map<std::string, cricket::TransportStats>
5453PeerConnection::GetTransportStatsByNames(
5454 const std::set<std::string>& transport_names) {
5455 if (!network_thread()->IsCurrent()) {
5456 return network_thread()
5457 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5458 RTC_FROM_HERE,
5459 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175460 }
Steve Anton5dfde182018-02-06 18:34:405461 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5462 for (const std::string& transport_name : transport_names) {
5463 cricket::TransportStats transport_stats;
5464 bool success =
5465 transport_controller_->GetStats(transport_name, &transport_stats);
5466 if (success) {
5467 transport_stats_by_name[transport_name] = std::move(transport_stats);
5468 } else {
5469 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5470 << transport_name;
5471 }
5472 }
5473 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175474}
5475
5476bool PeerConnection::GetLocalCertificate(
5477 const std::string& transport_name,
5478 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355479 if (!certificate) {
5480 return false;
5481 }
5482 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5483 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175484}
5485
Taylor Brandstetterc3928662018-02-23 21:04:515486std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175487 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515488 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175489}
5490
5491cricket::DataChannelType PeerConnection::data_channel_type() const {
5492 return data_channel_type_;
5493}
5494
5495bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5496 return pending_ice_restarts_.find(content_name) !=
5497 pending_ice_restarts_.end();
5498}
5499
Steve Anton75737c02017-11-06 18:37:175500bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5501 return transport_controller_->NeedsIceRestart(content_name);
5502}
5503
5504void PeerConnection::OnCertificateReady(
5505 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5506 transport_controller_->SetLocalCertificate(certificate);
5507}
5508
5509void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215510 SetSessionError(SessionError::kTransport,
5511 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175512}
5513
Alex Loiko9289eda2018-11-23 16:18:595514void PeerConnection::OnTransportControllerConnectionState(
5515 cricket::IceConnectionState state) {
5516 switch (state) {
5517 case cricket::kIceConnectionConnecting:
5518 // If the current state is Connected or Completed, then there were
5519 // writable channels but now there are not, so the next state must
5520 // be Disconnected.
5521 // kIceConnectionConnecting is currently used as the default,
5522 // un-connected state by the TransportController, so its only use is
5523 // detecting disconnections.
5524 if (ice_connection_state_ ==
5525 PeerConnectionInterface::kIceConnectionConnected ||
5526 ice_connection_state_ ==
5527 PeerConnectionInterface::kIceConnectionCompleted) {
5528 SetIceConnectionState(
5529 PeerConnectionInterface::kIceConnectionDisconnected);
5530 }
5531 break;
5532 case cricket::kIceConnectionFailed:
5533 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5534 break;
5535 case cricket::kIceConnectionConnected:
5536 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5537 "all transports are writable.";
5538 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5539 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5540 break;
5541 case cricket::kIceConnectionCompleted:
5542 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5543 "all transports are complete.";
5544 if (ice_connection_state_ !=
5545 PeerConnectionInterface::kIceConnectionConnected) {
5546 // If jumping directly from "checking" to "connected",
5547 // signal "connected" first.
5548 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5549 }
5550 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5551 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5552 ReportTransportStats();
5553 break;
5554 default:
5555 RTC_NOTREACHED();
5556 }
5557}
5558
Steve Anton75737c02017-11-06 18:37:175559void PeerConnection::OnTransportControllerCandidatesGathered(
5560 const std::string& transport_name,
5561 const cricket::Candidates& candidates) {
5562 RTC_DCHECK(signaling_thread()->IsCurrent());
5563 int sdp_mline_index;
5564 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255565 RTC_LOG(LS_ERROR)
5566 << "OnTransportControllerCandidatesGathered: content name "
5567 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175568 return;
5569 }
5570
5571 for (cricket::Candidates::const_iterator citer = candidates.begin();
5572 citer != candidates.end(); ++citer) {
5573 // Use transport_name as the candidate media id.
5574 std::unique_ptr<JsepIceCandidate> candidate(
5575 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5576 if (local_description()) {
5577 mutable_local_description()->AddCandidate(candidate.get());
5578 }
5579 OnIceCandidate(std::move(candidate));
5580 }
5581}
5582
5583void PeerConnection::OnTransportControllerCandidatesRemoved(
5584 const std::vector<cricket::Candidate>& candidates) {
5585 RTC_DCHECK(signaling_thread()->IsCurrent());
5586 // Sanity check.
5587 for (const cricket::Candidate& candidate : candidates) {
5588 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255589 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075590 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255591 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175592 return;
5593 }
5594 }
5595
5596 if (local_description()) {
5597 mutable_local_description()->RemoveCandidates(candidates);
5598 }
5599 OnIceCandidatesRemoved(candidates);
5600}
5601
5602void PeerConnection::OnTransportControllerDtlsHandshakeError(
5603 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:535604 RTC_HISTOGRAM_ENUMERATION(
5605 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5606 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:175607}
5608
Steve Antoned10bd92017-12-05 18:52:595609void PeerConnection::EnableSending() {
5610 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055611 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595612 if (channel && !channel->enabled()) {
5613 channel->Enable(true);
5614 }
Steve Anton75737c02017-11-06 18:37:175615 }
5616
Steve Anton4171afb2017-11-20 18:20:225617 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175618 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225619 }
Steve Anton75737c02017-11-06 18:37:175620}
5621
5622// Returns the media index for a local ice candidate given the content name.
5623bool PeerConnection::GetLocalCandidateMediaIndex(
5624 const std::string& content_name,
5625 int* sdp_mline_index) {
5626 if (!local_description() || !sdp_mline_index) {
5627 return false;
5628 }
5629
5630 bool content_found = false;
5631 const ContentInfos& contents = local_description()->description()->contents();
5632 for (size_t index = 0; index < contents.size(); ++index) {
5633 if (contents[index].name == content_name) {
5634 *sdp_mline_index = static_cast<int>(index);
5635 content_found = true;
5636 break;
5637 }
5638 }
5639 return content_found;
5640}
5641
5642bool PeerConnection::UseCandidatesInSessionDescription(
5643 const SessionDescriptionInterface* remote_desc) {
5644 if (!remote_desc) {
5645 return true;
5646 }
5647 bool ret = true;
5648
5649 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5650 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5651 for (size_t n = 0; n < candidates->count(); ++n) {
5652 const IceCandidateInterface* candidate = candidates->at(n);
5653 bool valid = false;
5654 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5655 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255656 RTC_LOG(LS_INFO)
5657 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075658 "candidate.";
Steve Anton75737c02017-11-06 18:37:175659 }
5660 continue;
5661 }
5662 ret = UseCandidate(candidate);
5663 if (!ret) {
5664 break;
5665 }
5666 }
5667 }
5668 return ret;
5669}
5670
5671bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5672 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5673 size_t remote_content_size =
5674 remote_description()->description()->contents().size();
5675 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255676 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175677 return false;
5678 }
5679
5680 cricket::ContentInfo content =
5681 remote_description()->description()->contents()[mediacontent_index];
5682 std::vector<cricket::Candidate> candidates;
5683 candidates.push_back(candidate->candidate());
5684 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355685 RTCError error =
5686 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505687 if (error.ok()) {
5688 // Candidates successfully submitted for checking.
5689 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5690 ice_connection_state_ ==
5691 PeerConnectionInterface::kIceConnectionDisconnected) {
5692 // If state is New, then the session has just gotten its first remote ICE
5693 // candidates, so go to Checking.
5694 // If state is Disconnected, the session is re-using old candidates or
5695 // receiving additional ones, so go to Checking.
5696 // If state is Connected, stay Connected.
5697 // TODO(bemasc): If state is Connected, and the new candidates are for a
5698 // newly added transport, then the state actually _should_ move to
5699 // checking. Add a way to distinguish that case.
5700 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5701 }
5702 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:075703 } else {
Zhi Huange830e682018-03-30 17:48:355704 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175705 }
5706 return true;
5707}
5708
5709void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175710 // Destroy video channel first since it may have a pointer to the
5711 // voice channel.
5712 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295713 if (!video_info || video_info->rejected) {
5714 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175715 }
5716
Steve Anton6fec8802017-12-04 18:37:295717 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5718 if (!audio_info || audio_info->rejected) {
5719 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175720 }
5721
5722 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5723 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295724 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175725 }
5726}
5727
Steve Antondcc3c022017-12-23 00:02:545728RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5729 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175730 const cricket::ContentGroup* bundle_group = nullptr;
5731 if (configuration_.bundle_policy ==
5732 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545733 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175734 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565735 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5736 "max-bundle configured but session description "
5737 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175738 }
5739 }
Steve Antondcc3c022017-12-23 00:02:545740 return std::move(bundle_group);
5741}
5742
5743RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355744 // Creating the media channels. Transports should already have been created
5745 // at this point.
Steve Antondcc3c022017-12-23 00:02:545746 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555747 if (voice && !voice->rejected &&
5748 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355749 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555750 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565751 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5752 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555753 }
5754 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5755 }
5756
Steve Antondcc3c022017-12-23 00:02:545757 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555758 if (video && !video->rejected &&
5759 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355760 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555761 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565762 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5763 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175764 }
Steve Antoneda6ccd2017-12-04 18:21:555765 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175766 }
5767
Steve Antondcc3c022017-12-23 00:02:545768 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175769 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 19:23:225770 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:355771 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565772 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5773 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175774 }
5775 }
5776
Steve Anton8a006912017-12-04 23:25:565777 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175778}
5779
Steve Anton4171afb2017-11-20 18:20:225780// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555781cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355782 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425783 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 16:07:485784 MediaTransportInterface* media_transport = nullptr;
5785 if (configuration_.use_media_transport) {
5786 media_transport = GetMediaTransport(mid);
5787 }
Anton Sukhanov98a462c2018-10-17 20:15:425788
Steve Anton75737c02017-11-06 18:37:175789 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 20:15:425790 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445791 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5792 audio_options_);
Steve Anton75737c02017-11-06 18:37:175793 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555794 return nullptr;
Steve Anton75737c02017-11-06 18:37:175795 }
Steve Anton75737c02017-11-06 18:37:175796 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5797 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175798 voice_channel->SignalSentPacket.connect(this,
5799 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355800 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225801
Steve Antoneda6ccd2017-12-04 18:21:555802 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175803}
5804
Steve Anton4171afb2017-11-20 18:20:225805// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555806cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355807 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425808 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5809
5810 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 18:37:175811 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355812 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445813 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5814 video_options_);
Steve Anton75737c02017-11-06 18:37:175815 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555816 return nullptr;
Steve Anton75737c02017-11-06 18:37:175817 }
Steve Anton75737c02017-11-06 18:37:175818 video_channel->SignalDtlsSrtpSetupFailure.connect(
5819 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175820 video_channel->SignalSentPacket.connect(this,
5821 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355822 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225823
Steve Antoneda6ccd2017-12-04 18:21:555824 return video_channel;
Steve Anton75737c02017-11-06 18:37:175825}
5826
Zhi Huange830e682018-03-30 17:48:355827bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225828 switch (data_channel_type_) {
5829 case cricket::DCT_MEDIA_TRANSPORT:
5830 if (network_thread()->Invoke<bool>(
5831 RTC_FROM_HERE,
5832 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5833 this, mid))) {
5834 for (const auto& channel : sctp_data_channels_) {
5835 channel->OnTransportChannelCreated();
5836 }
5837 return true;
5838 }
Steve Anton75737c02017-11-06 18:37:175839 return false;
Bjorn Mellem175aa2e2018-11-08 19:23:225840 case cricket::DCT_SCTP:
5841 if (!sctp_factory_) {
5842 RTC_LOG(LS_ERROR)
5843 << "Trying to create SCTP transport, but didn't compile with "
5844 "SCTP support (HAVE_SCTP)";
5845 return false;
5846 }
5847 if (!network_thread()->Invoke<bool>(
5848 RTC_FROM_HERE,
5849 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5850 return false;
5851 }
5852 for (const auto& channel : sctp_data_channels_) {
5853 channel->OnTransportChannelCreated();
5854 }
5855 return true;
5856 case cricket::DCT_RTP:
5857 default:
5858 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5859 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5860 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5861 SrtpRequired(), GetCryptoOptions());
5862 if (!rtp_data_channel_) {
5863 return false;
5864 }
5865 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5866 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5867 rtp_data_channel_->SignalSentPacket.connect(
5868 this, &PeerConnection::OnSentPacket_w);
5869 rtp_data_channel_->SetRtpTransport(rtp_transport);
5870 return true;
Steve Anton75737c02017-11-06 18:37:175871 }
5872
Steve Anton75737c02017-11-06 18:37:175873 return true;
5874}
5875
5876Call::Stats PeerConnection::GetCallStats() {
5877 if (!worker_thread()->IsCurrent()) {
5878 return worker_thread()->Invoke<Call::Stats>(
5879 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5880 }
5881 if (call_) {
5882 return call_->GetStats();
5883 } else {
5884 return Call::Stats();
5885 }
5886}
5887
Zhi Huange830e682018-03-30 17:48:355888bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175889 RTC_DCHECK(network_thread()->IsCurrent());
5890 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265891 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355892 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265893 RTC_DCHECK(dtls_transport);
5894 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175895 RTC_DCHECK(sctp_transport_);
5896 sctp_invoker_.reset(new rtc::AsyncInvoker());
5897 sctp_transport_->SignalReadyToSendData.connect(
5898 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5899 sctp_transport_->SignalDataReceived.connect(
5900 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:325901 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5902 // another thread. Would be nice if there was a helper class similar to
5903 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5904 // code.
5905 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5906 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5907 sctp_transport_->SignalClosingProcedureComplete.connect(
5908 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:355909 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265910 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355911 return true;
Steve Anton75737c02017-11-06 18:37:175912}
5913
5914void PeerConnection::DestroySctpTransport_n() {
5915 RTC_DCHECK(network_thread()->IsCurrent());
5916 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355917 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175918 sctp_invoker_.reset(nullptr);
5919 sctp_ready_to_send_data_ = false;
5920}
5921
5922void PeerConnection::OnSctpTransportReadyToSendData_n() {
5923 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5924 RTC_DCHECK(network_thread()->IsCurrent());
5925 // Note: Cannot use rtc::Bind here because it will grab a reference to
5926 // PeerConnection and potentially cause PeerConnection to live longer than
5927 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5928 // be destroyed before PeerConnection is destroyed, and at that point all
5929 // pending tasks will be cleared.
5930 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5931 OnSctpTransportReadyToSendData_s(true);
5932 });
5933}
5934
5935void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5936 RTC_DCHECK(signaling_thread()->IsCurrent());
5937 sctp_ready_to_send_data_ = ready;
5938 SignalSctpReadyToSendData(ready);
5939}
5940
5941void PeerConnection::OnSctpTransportDataReceived_n(
5942 const cricket::ReceiveDataParams& params,
5943 const rtc::CopyOnWriteBuffer& payload) {
5944 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5945 RTC_DCHECK(network_thread()->IsCurrent());
5946 // Note: Cannot use rtc::Bind here because it will grab a reference to
5947 // PeerConnection and potentially cause PeerConnection to live longer than
5948 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5949 // be destroyed before PeerConnection is destroyed, and at that point all
5950 // pending tasks will be cleared.
5951 sctp_invoker_->AsyncInvoke<void>(
5952 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5953 OnSctpTransportDataReceived_s(params, payload);
5954 });
5955}
5956
5957void PeerConnection::OnSctpTransportDataReceived_s(
5958 const cricket::ReceiveDataParams& params,
5959 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 19:23:225960 RTC_DCHECK_RUN_ON(signaling_thread());
5961 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 18:37:175962 SignalSctpDataReceived(params, payload);
5963 }
5964}
5965
Taylor Brandstettercdd05f02018-05-31 20:23:325966void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:175967 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5968 RTC_DCHECK(network_thread()->IsCurrent());
5969 sctp_invoker_->AsyncInvoke<void>(
5970 RTC_FROM_HERE, signaling_thread(),
5971 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:325972 &SignalSctpClosingProcedureStartedRemotely, sid));
5973}
5974
5975void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5976 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5977 RTC_DCHECK(network_thread()->IsCurrent());
5978 sctp_invoker_->AsyncInvoke<void>(
5979 RTC_FROM_HERE, signaling_thread(),
5980 rtc::Bind(&sigslot::signal1<int>::operator(),
5981 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:175982}
5983
Bjorn Mellem175aa2e2018-11-08 19:23:225984bool PeerConnection::SetupMediaTransportForDataChannels_n(
5985 const std::string& mid) {
5986 media_transport_ = transport_controller_->GetMediaTransport(mid);
5987 if (!media_transport_) {
5988 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5989 return false;
5990 }
5991
5992 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5993 media_transport_->SetDataSink(this);
5994 media_transport_data_mid_ = mid;
5995 transport_controller_->SignalMediaTransportStateChanged.connect(
5996 this, &PeerConnection::OnMediaTransportStateChanged_n);
5997 // Check the initial state right away, in case transport is already writable.
5998 OnMediaTransportStateChanged_n();
5999 return true;
6000}
6001
6002void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6003 if (!media_transport_) {
6004 return;
6005 }
6006 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6007 media_transport_data_mid_.reset();
6008 media_transport_->SetDataSink(nullptr);
6009 media_transport_invoker_ = nullptr;
6010 media_transport_ = nullptr;
6011}
6012
6013void PeerConnection::OnMediaTransportStateChanged_n() {
6014 if (!media_transport_data_mid_ ||
6015 transport_controller_->GetMediaTransportState(
6016 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6017 return;
6018 }
6019 media_transport_invoker_->AsyncInvoke<void>(
6020 RTC_FROM_HERE, signaling_thread(), [this] {
6021 RTC_DCHECK_RUN_ON(signaling_thread());
6022 media_transport_ready_to_send_data_ = true;
6023 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6024 });
6025}
6026
Steve Anton75737c02017-11-06 18:37:176027// Returns false if bundle is enabled and rtcp_mux is disabled.
6028bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6029 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6030 if (!bundle_enabled)
6031 return true;
6032
6033 const cricket::ContentGroup* bundle_group =
6034 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6035 RTC_DCHECK(bundle_group != NULL);
6036
6037 const cricket::ContentInfos& contents = desc->contents();
6038 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6039 citer != contents.end(); ++citer) {
6040 const cricket::ContentInfo* content = (&*citer);
6041 RTC_DCHECK(content != NULL);
6042 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:006043 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:176044 if (!HasRtcpMuxEnabled(content))
6045 return false;
6046 }
6047 }
6048 // RTCP-MUX is enabled in all the contents.
6049 return true;
6050}
6051
6052bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:306053 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:176054}
6055
Steve Anton8a006912017-12-04 23:25:566056RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:176057 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:566058 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:216059 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:566060 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:176061 }
6062
6063 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:566064 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:176065 }
6066
Steve Anton3828c062017-12-06 18:34:516067 SdpType type = sdesc->GetType();
6068 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6069 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:566070 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:036071 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:566072 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:176073 }
6074
6075 // Verify crypto settings.
6076 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:566077 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6078 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:536079 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:566080 if (!crypto_error.ok()) {
6081 return crypto_error;
6082 }
Steve Anton75737c02017-11-06 18:37:176083 }
6084
6085 // Verify ice-ufrag and ice-pwd.
6086 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566087 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6088 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:176089 }
6090
6091 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566092 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6093 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:176094 }
6095
6096 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6097 // m-lines that do not rtcp-mux enabled.
6098
6099 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:516100 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:486101 // With an answer we want to compare the new answer session description with
6102 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:176103 const cricket::SessionDescription* offer_desc =
6104 (source == cricket::CS_LOCAL) ? remote_description()->description()
6105 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:486106 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6107 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6108 type)) {
Steve Anton8a006912017-12-04 23:25:566109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6110 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:176111 }
6112 } else {
Steve Anton75737c02017-11-06 18:37:176113 // The re-offers should respect the order of m= sections in current
6114 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:486115 // With a re-offer, either the current local or current remote descriptions
6116 // could be the most up to date, so we would like to check against both of
6117 // them if they exist. It could be the case that one of them has a 0 port
6118 // for a media section, but the other does not. This is important to check
6119 // against in the case that we are recycling an m= section.
6120 const cricket::SessionDescription* current_desc = nullptr;
6121 const cricket::SessionDescription* secondary_current_desc = nullptr;
6122 if (local_description()) {
6123 current_desc = local_description()->description();
6124 if (remote_description()) {
6125 secondary_current_desc = remote_description()->description();
6126 }
6127 } else if (remote_description()) {
6128 current_desc = remote_description()->description();
6129 }
Steve Anton75737c02017-11-06 18:37:176130 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:486131 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6132 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:566133 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6134 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:176135 }
6136 }
6137
Steve Antonba42e992018-04-09 21:10:016138 if (IsUnifiedPlan()) {
6139 // Ensure that each audio and video media section has at most one
6140 // "StreamParams". This will return an error if receiving a session
6141 // description from a "Plan B" endpoint which adds multiple tracks of the
6142 // same type. With Unified Plan, there can only be at most one track per
6143 // media section.
6144 for (const ContentInfo& content : sdesc->description()->contents()) {
6145 const MediaContentDescription& desc = *content.description;
6146 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6147 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6148 desc.streams().size() > 1u) {
6149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6150 "Media section has more than one track specified "
6151 "with a=ssrc lines which is not supported with "
6152 "Unified Plan.");
6153 }
6154 }
6155 }
6156
Steve Anton8a006912017-12-04 23:25:566157 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176158}
6159
Steve Anton3828c062017-12-06 18:34:516160bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176161 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516162 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176163 return (state == PeerConnectionInterface::kStable) ||
6164 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:526165 } else {
Steve Anton3828c062017-12-06 18:34:516166 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176167 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6168 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6169 }
6170}
6171
Steve Anton3828c062017-12-06 18:34:516172bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176173 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516174 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176175 return (state == PeerConnectionInterface::kStable) ||
6176 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:526177 } else {
Steve Anton3828c062017-12-06 18:34:516178 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176179 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6180 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6181 }
6182}
6183
Steve Antonf8470812017-12-04 18:46:216184const char* PeerConnection::SessionErrorToString(SessionError error) const {
6185 switch (error) {
6186 case SessionError::kNone:
6187 return "ERROR_NONE";
6188 case SessionError::kContent:
6189 return "ERROR_CONTENT";
6190 case SessionError::kTransport:
6191 return "ERROR_TRANSPORT";
6192 }
6193 RTC_NOTREACHED();
6194 return "";
6195}
6196
Steve Anton75737c02017-11-06 18:37:176197std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:306198 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:216199 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6200 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:326201 return desc.Release();
Steve Anton75737c02017-11-06 18:37:176202}
6203
Steve Anton8e20f172018-03-06 18:55:046204void PeerConnection::ReportSdpFormatReceived(
6205 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:046206 int num_audio_mlines = 0;
6207 int num_video_mlines = 0;
6208 int num_audio_tracks = 0;
6209 int num_video_tracks = 0;
6210 for (const ContentInfo& content : remote_offer.description()->contents()) {
6211 cricket::MediaType media_type = content.media_description()->type();
6212 int num_tracks = std::max(
6213 1, static_cast<int>(content.media_description()->streams().size()));
6214 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6215 num_audio_mlines += 1;
6216 num_audio_tracks += num_tracks;
6217 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6218 num_video_mlines += 1;
6219 num_video_tracks += num_tracks;
6220 }
6221 }
6222 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6223 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6224 format = kSdpFormatReceivedComplexUnifiedPlan;
6225 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6226 format = kSdpFormatReceivedComplexPlanB;
6227 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6228 format = kSdpFormatReceivedSimple;
6229 }
Qingsi Wang7fc821d2018-07-12 19:54:536230 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6231 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:046232}
6233
Harald Alvestrand8ebba742018-05-31 12:00:346234void PeerConnection::NoteUsageEvent(UsageEvent event) {
6235 RTC_DCHECK_RUN_ON(signaling_thread());
6236 usage_event_accumulator_ |= static_cast<int>(event);
6237}
6238
6239void PeerConnection::ReportUsagePattern() const {
6240 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:536241 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6242 usage_event_accumulator_,
6243 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:556244 const int bad_bits =
6245 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6246 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6247 const int good_bits =
6248 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6249 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6250 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6251 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6252 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:166253 // If called after close(), we can't report, because observer may have
6254 // been deallocated, and therefore pointer is null. Write to log instead.
6255 if (observer_) {
6256 Observer()->OnInterestingUsage(usage_event_accumulator_);
6257 } else {
6258 RTC_LOG(LS_INFO) << "Interesting usage signature "
6259 << usage_event_accumulator_
6260 << " observed after observer shutdown";
6261 }
Harald Alvestrandc0e97252018-07-26 08:39:556262 }
Harald Alvestrand8ebba742018-05-31 12:00:346263}
6264
Steve Anton0ffaaa22018-02-23 18:31:306265void PeerConnection::ReportNegotiatedSdpSemantics(
6266 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:536267 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:306268 switch (answer.description()->msid_signaling()) {
6269 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:536270 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:306271 break;
6272 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:536273 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:306274 break;
6275 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536276 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:306277 break;
6278 case cricket::kMsidSignalingMediaSection |
6279 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536280 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:306281 break;
6282 default:
6283 RTC_NOTREACHED();
6284 }
Qingsi Wang7fc821d2018-07-12 19:54:536285 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6286 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:306287}
6288
Steve Anton75737c02017-11-06 18:37:176289// We need to check the local/remote description for the Transport instead of
6290// the session, because a new Transport added during renegotiation may have
6291// them unset while the session has them set from the previous negotiation.
6292// Not doing so may trigger the auto generation of transport description and
6293// mess up DTLS identity information, ICE credential, etc.
6294bool PeerConnection::ReadyToUseRemoteCandidate(
6295 const IceCandidateInterface* candidate,
6296 const SessionDescriptionInterface* remote_desc,
6297 bool* valid) {
6298 *valid = true;
6299
6300 const SessionDescriptionInterface* current_remote_desc =
6301 remote_desc ? remote_desc : remote_description();
6302
6303 if (!current_remote_desc) {
6304 return false;
6305 }
6306
6307 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6308 size_t remote_content_size =
6309 current_remote_desc->description()->contents().size();
6310 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:256311 RTC_LOG(LS_ERROR)
6312 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6313 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176314
6315 *valid = false;
6316 return false;
6317 }
6318
6319 cricket::ContentInfo content =
6320 current_remote_desc->description()->contents()[mediacontent_index];
6321
6322 const std::string transport_name = GetTransportName(content.name);
6323 if (transport_name.empty()) {
6324 return false;
6325 }
Zhi Huange830e682018-03-30 17:48:356326 return true;
Steve Anton75737c02017-11-06 18:37:176327}
6328
6329bool PeerConnection::SrtpRequired() const {
6330 return dtls_enabled_ ||
6331 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6332}
6333
6334void PeerConnection::OnTransportControllerGatheringState(
6335 cricket::IceGatheringState state) {
6336 RTC_DCHECK(signaling_thread()->IsCurrent());
6337 if (state == cricket::kIceGatheringGathering) {
6338 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6339 } else if (state == cricket::kIceGatheringComplete) {
6340 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6341 }
6342}
6343
6344void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:456345 std::map<std::string, std::set<cricket::MediaType>>
6346 media_types_by_transport_name;
6347 for (auto transceiver : transceivers_) {
6348 if (transceiver->internal()->channel()) {
6349 const std::string& transport_name =
6350 transceiver->internal()->channel()->transport_name();
6351 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086352 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456353 }
Steve Anton75737c02017-11-06 18:37:176354 }
6355 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456356 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6357 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176358 }
Zhi Huange830e682018-03-30 17:48:356359
Danil Chapovalov66cadcc2018-06-19 14:47:436360 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356361 if (transport_name) {
6362 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456363 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176364 }
Zhi Huange830e682018-03-30 17:48:356365
Steve Antonc7b964c2018-02-01 22:39:456366 for (const auto& entry : media_types_by_transport_name) {
6367 const std::string& transport_name = entry.first;
6368 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176369 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456370 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176371 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456372 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176373 }
6374 }
6375}
6376// Walk through the ConnectionInfos to gather best connection usage
6377// for IPv4 and IPv6.
6378void PeerConnection::ReportBestConnectionState(
6379 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:456380 for (const cricket::TransportChannelStats& channel_stats :
6381 stats.channel_stats) {
6382 for (const cricket::ConnectionInfo& connection_info :
6383 channel_stats.connection_infos) {
6384 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176385 continue;
6386 }
6387
Steve Antonc7b964c2018-02-01 22:39:456388 const cricket::Candidate& local = connection_info.local_candidate;
6389 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176390
6391 // Increment the counter for IceCandidatePairType.
6392 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6393 (local.type() == RELAY_PORT_TYPE &&
6394 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:536395 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6396 GetIceCandidatePairCounter(local, remote),
6397 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176398 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536399 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6400 GetIceCandidatePairCounter(local, remote),
6401 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176402 } else {
6403 RTC_CHECK(0);
6404 }
Steve Anton75737c02017-11-06 18:37:176405
6406 // Increment the counter for IP type.
6407 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536408 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6409 kBestConnections_IPv4,
6410 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176411 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536412 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6413 kBestConnections_IPv6,
6414 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176415 } else {
6416 RTC_CHECK(0);
6417 }
6418
6419 return;
6420 }
6421 }
6422}
6423
6424void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456425 const cricket::TransportStats& stats,
6426 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176427 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6428 return;
6429 }
6430
6431 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6432 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6433 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6434 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6435 return;
6436 }
6437
Qingsi Wang7fc821d2018-07-12 19:54:536438 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6439 for (cricket::MediaType media_type : media_types) {
6440 switch (media_type) {
6441 case cricket::MEDIA_TYPE_AUDIO:
6442 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6443 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6444 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6445 break;
6446 case cricket::MEDIA_TYPE_VIDEO:
6447 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6448 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6449 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6450 break;
6451 case cricket::MEDIA_TYPE_DATA:
6452 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6453 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6454 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6455 break;
6456 default:
6457 RTC_NOTREACHED();
6458 continue;
6459 }
Steve Antonc7b964c2018-02-01 22:39:456460 }
Qingsi Wang7fc821d2018-07-12 19:54:536461 }
6462
6463 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6464 for (cricket::MediaType media_type : media_types) {
6465 switch (media_type) {
6466 case cricket::MEDIA_TYPE_AUDIO:
6467 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6468 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6469 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6470 break;
6471 case cricket::MEDIA_TYPE_VIDEO:
6472 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6473 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6474 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6475 break;
6476 case cricket::MEDIA_TYPE_DATA:
6477 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6478 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6479 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6480 break;
6481 default:
6482 RTC_NOTREACHED();
6483 continue;
6484 }
Steve Antonc7b964c2018-02-01 22:39:456485 }
Steve Anton75737c02017-11-06 18:37:176486 }
6487}
6488
6489void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6490 RTC_DCHECK(worker_thread()->IsCurrent());
6491 RTC_DCHECK(call_);
6492 call_->OnSentPacket(sent_packet);
6493}
6494
6495const std::string PeerConnection::GetTransportName(
6496 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-14 00:26:056497 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296498 if (channel) {
6499 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176500 }
Steve Anton6fec8802017-12-04 18:37:296501 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356502 RTC_DCHECK(sctp_mid_);
6503 if (content_name == *sctp_mid_) {
6504 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296505 }
6506 }
6507 // Return an empty string if failed to retrieve the transport name.
6508 return "";
Steve Anton75737c02017-11-06 18:37:176509}
6510
Steve Anton6fec8802017-12-04 18:37:296511void PeerConnection::DestroyTransceiverChannel(
6512 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6513 transceiver) {
6514 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176515
Amit Hilbuchdd9390c2018-11-14 00:26:056516 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:296517 if (channel) {
6518 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:056519 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:176520 }
6521}
6522
6523void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296524 if (rtp_data_channel_) {
6525 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-14 00:26:056526 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 18:37:296527 rtp_data_channel_ = nullptr;
6528 }
6529
6530 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6531 // grab a reference to this PeerConnection. If this is called from the
6532 // PeerConnection destructor, the RefCountedObject vtable will have already
6533 // been destroyed (since it is a subclass of PeerConnection) and using
6534 // rtc::Bind will cause "Pure virtual function called" error to appear.
6535
6536 if (sctp_transport_) {
6537 OnDataChannelDestroyed();
6538 network_thread()->Invoke<void>(RTC_FROM_HERE,
6539 [this] { DestroySctpTransport_n(); });
6540 }
Bjorn Mellem175aa2e2018-11-08 19:23:226541
6542 if (media_transport_) {
6543 OnDataChannelDestroyed();
6544 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6545 RTC_DCHECK_RUN_ON(network_thread());
6546 TeardownMediaTransportForDataChannels_n();
6547 });
6548 }
Steve Anton6fec8802017-12-04 18:37:296549}
6550
Amit Hilbuchdd9390c2018-11-14 00:26:056551void PeerConnection::DestroyChannelInterface(
6552 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:296553 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296554 switch (channel->media_type()) {
6555 case cricket::MEDIA_TYPE_AUDIO:
6556 channel_manager()->DestroyVoiceChannel(
6557 static_cast<cricket::VoiceChannel*>(channel));
6558 break;
6559 case cricket::MEDIA_TYPE_VIDEO:
6560 channel_manager()->DestroyVideoChannel(
6561 static_cast<cricket::VideoChannel*>(channel));
6562 break;
6563 case cricket::MEDIA_TYPE_DATA:
6564 channel_manager()->DestroyRtpDataChannel(
6565 static_cast<cricket::RtpDataChannel*>(channel));
6566 break;
6567 default:
6568 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6569 break;
6570 }
Zhi Huange830e682018-03-30 17:48:356571}
Steve Anton6fec8802017-12-04 18:37:296572
Taylor Brandstettercbaa2542018-04-16 23:42:146573bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356574 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146575 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196576 cricket::DtlsTransportInternal* dtls_transport,
6577 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 23:42:146578 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356579 auto base_channel = GetChannel(mid);
6580 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146581 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356582 }
Taylor Brandstettercbaa2542018-04-16 23:42:146583 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266584 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176585 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196586
6587 call_->MediaTransportChange(media_transport);
6588
Taylor Brandstettercbaa2542018-04-16 23:42:146589 return ret;
Steve Anton75737c02017-11-06 18:37:176590}
6591
Harald Alvestrand7a1c7f72018-08-01 08:50:166592PeerConnectionObserver* PeerConnection::Observer() const {
6593 // In earlier production code, the pointer was not cleared on close,
6594 // which might have led to undefined behavior if the observer was not
6595 // deallocated, or strange crashes if it was.
6596 // We use CHECK in order to catch such behavior if it exists.
6597 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6598 RTC_CHECK(observer_);
6599 return observer_;
6600}
6601
Benjamin Wright8c27cca2018-10-25 17:16:446602CryptoOptions PeerConnection::GetCryptoOptions() {
6603 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6604 // after it has been removed.
6605 return configuration_.crypto_options.has_value()
6606 ? *configuration_.crypto_options
6607 : factory_->options().crypto_options;
6608}
6609
Harald Alvestrand89061872018-01-02 13:08:346610void PeerConnection::ClearStatsCache() {
6611 if (stats_collector_) {
6612 stats_collector_->ClearCachedStatsReport();
6613 }
6614}
6615
Harald Alvestrand7a1c7f72018-08-01 08:50:166616void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:406617 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6618 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:166619}
6620
henrike@webrtc.org28e20752013-07-10 00:45:366621} // namespace webrtc