blob: c81749451c8267a5994a0c3265ab574fc15ac882 [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
Steve Anton75737c02017-11-06 18:37:17521// Get the SCTP port out of a SessionDescription.
522// Return -1 if not found.
523int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30524 const cricket::DataContentDescription* data_desc =
525 GetFirstDataContentDescription(session_description);
526 RTC_DCHECK(data_desc);
527 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17528 return -1;
529 }
Steve Anton75737c02017-11-06 18:37:17530 std::string value;
531 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
532 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30533 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17534 if (!codec.Matches(match_pattern)) {
535 continue;
536 }
537 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
538 return rtc::FromString<int>(value);
539 }
540 }
541 return -1;
542}
543
Steve Anton75737c02017-11-06 18:37:17544// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
545bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
546 const SessionDescriptionInterface* new_desc,
547 const std::string& content_name) {
548 if (!old_desc) {
549 return false;
550 }
551 const SessionDescription* new_sd = new_desc->description();
552 const SessionDescription* old_sd = old_desc->description();
553 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
554 if (!cinfo || cinfo->rejected) {
555 return false;
556 }
557 // If the content isn't rejected, check if ufrag and password has changed.
558 const cricket::TransportDescription* new_transport_desc =
559 new_sd->GetTransportDescriptionByName(content_name);
560 const cricket::TransportDescription* old_transport_desc =
561 old_sd->GetTransportDescriptionByName(content_name);
562 if (!new_transport_desc || !old_transport_desc) {
563 // No transport description exists. This is not an ICE restart.
564 return false;
565 }
566 if (cricket::IceCredentialsChanged(
567 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
568 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25569 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
570 << ".";
Steve Anton75737c02017-11-06 18:37:17571 return true;
572 }
573 return false;
574}
575
Steve Anton80dd7b52018-02-17 01:08:42576// Generates a string error message for SetLocalDescription/SetRemoteDescription
577// from an RTCError.
578std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
579 SdpType type,
580 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 11:41:30581 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42582 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
583 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32584 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42585}
586
Seth Hampson5b4f0752018-04-02 23:31:36587std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
588 std::string output = "streams=[";
589 const char* separator = "";
590 for (const auto& stream_id : stream_ids) {
591 output.append(separator).append(stream_id);
592 separator = ", ";
593 }
594 output.append("]");
595 return output;
596}
597
Danil Chapovalov66cadcc2018-06-19 14:47:43598absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23599 int rtc_configuration_parameter) {
600 if (rtc_configuration_parameter ==
601 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43602 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23603 }
604 return rtc_configuration_parameter;
605}
606
Bjorn Mellem175aa2e2018-11-08 19:23:22607cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
608 switch (type) {
609 case DataMessageType::kText:
610 return cricket::DMT_TEXT;
611 case DataMessageType::kBinary:
612 return cricket::DMT_BINARY;
613 case DataMessageType::kControl:
614 return cricket::DMT_CONTROL;
615 default:
616 return cricket::DMT_NONE;
617 }
618 return cricket::DMT_NONE;
619}
620
621DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
622 switch (type) {
623 case cricket::DMT_TEXT:
624 return DataMessageType::kText;
625 case cricket::DMT_BINARY:
626 return DataMessageType::kBinary;
627 case cricket::DMT_CONTROL:
628 return DataMessageType::kControl;
629 case cricket::DMT_NONE:
630 default:
631 RTC_NOTREACHED();
632 }
633 return DataMessageType::kControl;
634}
635
Steve Anton75737c02017-11-06 18:37:17636} // namespace
637
Henrik Boström31638672017-11-23 16:48:32638// Upon completion, posts a task to execute the callback of the
639// SetSessionDescriptionObserver asynchronously on the same thread. At this
640// point, the state of the peer connection might no longer reflect the effects
641// of the SetRemoteDescription operation, as the peer connection could have been
642// modified during the post.
643// TODO(hbos): Remove this class once we remove the version of
644// PeerConnectionInterface::SetRemoteDescription() that takes a
645// SetSessionDescriptionObserver as an argument.
646class PeerConnection::SetRemoteDescriptionObserverAdapter
647 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
648 public:
649 SetRemoteDescriptionObserverAdapter(
650 rtc::scoped_refptr<PeerConnection> pc,
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
652 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
653
654 // SetRemoteDescriptionObserverInterface implementation.
655 void OnSetRemoteDescriptionComplete(RTCError error) override {
656 if (error.ok())
657 pc_->PostSetSessionDescriptionSuccess(wrapper_);
658 else
Harald Alvestrand5081c0c2018-03-09 14:18:03659 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32660 }
661
662 private:
663 rtc::scoped_refptr<PeerConnection> pc_;
664 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
665};
666
deadbeef293e9262017-01-11 20:28:30667bool PeerConnectionInterface::RTCConfiguration::operator==(
668 const PeerConnectionInterface::RTCConfiguration& o) const {
669 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10670 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30671 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56672 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10673 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30674 BundlePolicy bundle_policy;
675 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10676 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
677 int ice_candidate_pool_size;
678 bool disable_ipv6;
679 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11680 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22681 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10682 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43683 absl::optional<int> screencast_min_bitrate;
684 absl::optional<bool> combined_audio_video_bwe;
685 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30686 TcpCandidatePolicy tcp_candidate_policy;
687 CandidateNetworkPolicy candidate_network_policy;
688 int audio_jitter_buffer_max_packets;
689 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 14:45:20690 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 20:28:30691 int ice_connection_receiving_timeout;
692 int ice_backup_candidate_pair_ping_interval;
693 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30694 bool prioritize_most_likely_ice_candidate_pairs;
695 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30696 bool prune_turn_ports;
697 bool presume_writable_when_fully_relayed;
698 bool enable_ice_renomination;
699 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 14:47:43700 absl::optional<int> ice_check_interval_strong_connectivity;
701 absl::optional<int> ice_check_interval_weak_connectivity;
702 absl::optional<int> ice_check_min_interval;
703 absl::optional<int> ice_unwritable_timeout;
704 absl::optional<int> ice_unwritable_min_checks;
705 absl::optional<int> stun_candidate_keepalive_interval;
706 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40707 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56708 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43709 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11710 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21711 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48712 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 17:16:44713 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48714 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30715 };
716 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
717 "Did you add something to RTCConfiguration and forget to "
718 "update operator==?");
719 return type == o.type && servers == o.servers &&
720 bundle_policy == o.bundle_policy &&
721 rtcp_mux_policy == o.rtcp_mux_policy &&
722 tcp_candidate_policy == o.tcp_candidate_policy &&
723 candidate_network_policy == o.candidate_network_policy &&
724 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
725 audio_jitter_buffer_fast_accelerate ==
726 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 14:45:20727 audio_jitter_buffer_min_delay_ms ==
728 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 20:28:30729 ice_connection_receiving_timeout ==
730 o.ice_connection_receiving_timeout &&
731 ice_backup_candidate_pair_ping_interval ==
732 o.ice_backup_candidate_pair_ping_interval &&
733 continual_gathering_policy == o.continual_gathering_policy &&
734 certificates == o.certificates &&
735 prioritize_most_likely_ice_candidate_pairs ==
736 o.prioritize_most_likely_ice_candidate_pairs &&
737 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51738 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11739 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22740 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30741 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30742 screencast_min_bitrate == o.screencast_min_bitrate &&
743 combined_audio_video_bwe == o.combined_audio_video_bwe &&
744 enable_dtls_srtp == o.enable_dtls_srtp &&
745 ice_candidate_pool_size == o.ice_candidate_pool_size &&
746 prune_turn_ports == o.prune_turn_ports &&
747 presume_writable_when_fully_relayed ==
748 o.presume_writable_when_fully_relayed &&
749 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14750 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14751 ice_check_interval_strong_connectivity ==
752 o.ice_check_interval_strong_connectivity &&
753 ice_check_interval_weak_connectivity ==
754 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10755 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57756 ice_unwritable_timeout == o.ice_unwritable_timeout &&
757 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49758 stun_candidate_keepalive_interval ==
759 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40760 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56761 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40762 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11763 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21764 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44765 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48766 use_media_transport_for_data_channels ==
767 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 09:25:48768 crypto_options == o.crypto_options &&
769 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30770}
771
772bool PeerConnectionInterface::RTCConfiguration::operator!=(
773 const PeerConnectionInterface::RTCConfiguration& o) const {
774 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26775}
776
zhihuang8f65cdf2016-05-07 01:40:30777// Generate a RTCP CNAME when a PeerConnection is created.
778std::string GenerateRtcpCname() {
779 std::string cname;
780 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25781 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27782 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30783 }
784 return cname;
785}
786
zhihuang1c378ed2017-08-17 21:10:50787bool ValidateOfferAnswerOptions(
788 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
789 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
790 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32791}
792
zhihuang1c378ed2017-08-17 21:10:50793// From |rtc_options|, fill parts of |session_options| shared by all generated
794// m= sections (in other words, nothing that involves a map/array).
795void ExtractSharedMediaSessionOptions(
796 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
797 cricket::MediaSessionOptions* session_options) {
798 session_options->vad_enabled = rtc_options.voice_activity_detection;
799 session_options->bundle_enabled = rtc_options.use_rtp_mux;
800}
zhihuanga77e6bb2017-08-15 01:17:48801
zhihuang38ede132017-06-15 19:52:32802PeerConnection::PeerConnection(PeerConnectionFactory* factory,
803 std::unique_ptr<RtcEventLog> event_log,
804 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36805 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32806 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30807 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11808 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32809 remote_streams_(StreamCollection::Create()),
810 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36811
812PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17813 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22814 RTC_DCHECK_RUN_ON(signaling_thread());
815
Steve Anton8af21862017-12-15 19:20:13816 // Need to stop transceivers before destroying the stats collector because
817 // AudioRtpSender has a reference to the StatsCollector it will update when
818 // stopping.
819 for (auto transceiver : transceivers_) {
820 transceiver->Stop();
821 }
Steve Anton4171afb2017-11-20 18:20:22822
Taylor Brandstettera1c30352016-05-13 15:15:11823 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57824 if (stats_collector_) {
825 stats_collector_->WaitForPendingRequest();
826 stats_collector_ = nullptr;
827 }
Steve Anton75737c02017-11-06 18:37:17828
Steve Anton8af21862017-12-15 19:20:13829 // Don't destroy BaseChannels until after stats has been cleaned up so that
830 // the last stats request can still read from the channels.
831 DestroyAllChannels();
832
Mirko Bonadei675513b2017-11-09 10:09:25833 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17834
835 webrtc_session_desc_factory_.reset();
836 sctp_invoker_.reset();
837 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 19:23:22838 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 18:37:17839 transport_controller_.reset();
840
deadbeef91dd5672016-05-18 23:55:30841 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27842 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02843 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15844 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02845 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15846 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09847 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15848 event_log_.reset();
849 });
henrike@webrtc.org28e20752013-07-10 00:45:36850}
851
Steve Anton8af21862017-12-15 19:20:13852void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08853 // Destroy video channels first since they may have a pointer to a voice
854 // channel.
855 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08856 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08857 DestroyTransceiverChannel(transceiver);
858 }
859 }
860 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08861 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08862 DestroyTransceiverChannel(transceiver);
863 }
864 }
865 DestroyDataChannel();
866}
867
henrike@webrtc.org28e20752013-07-10 00:45:36868bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45869 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47870 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17871 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59872
873 RTCError config_error = ValidateConfiguration(configuration);
874 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25875 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59876 return false;
877 }
878
Benjamin Wrightcab588882018-05-02 22:12:47879 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25880 RTC_LOG(LS_ERROR)
881 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07882 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30883 return false;
884 }
Jonas Orelandbdcee282017-10-10 12:01:40885
Benjamin Wrightcab588882018-05-02 22:12:47886 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30887 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25888 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07889 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10890 return false;
891 }
Benjamin Wrightd6f86e82018-05-08 20:12:25892
Benjamin Wrightcab588882018-05-02 22:12:47893 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15894 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47895 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25896 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10897
Harald Alvestrandb2a74782018-06-28 11:54:07898 cricket::ServerAddresses stun_servers;
899 std::vector<cricket::RelayServerConfig> turn_servers;
900
901 RTCErrorType parse_error =
902 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
903 if (parse_error != RTCErrorType::NONE) {
904 return false;
905 }
906
deadbeef91dd5672016-05-18 23:55:30907 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11908 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27909 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 11:54:07910 RTC_FROM_HERE,
911 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
912 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36913 return false;
914 }
Harald Alvestrandb2a74782018-06-28 11:54:07915 // If initialization was successful, note if STUN or TURN servers
916 // were supplied.
917 if (!stun_servers.empty()) {
918 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
919 }
920 if (!turn_servers.empty()) {
921 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
922 }
henrike@webrtc.org28e20752013-07-10 00:45:36923
Qingsi Wang7fc821d2018-07-12 19:54:53924 // Send information about IPv4/IPv6 status.
925 PeerConnectionAddressFamilyCounter address_family;
926 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
927 address_family = kPeerConnection_IPv6;
928 } else {
929 address_family = kPeerConnection_IPv4;
930 }
931 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
932 kPeerConnectionAddressFamilyCounter_Max);
933
Zhi Huange830e682018-03-30 17:48:35934 const PeerConnectionFactoryInterface::Options& options = factory_->options();
935
Steve Anton75737c02017-11-06 18:37:17936 // RFC 3264: The numeric value of the session id and version in the
937 // o line MUST be representable with a "64 bit signed integer".
938 // Due to this constraint session id |session_id_| is max limited to
939 // LLONG_MAX.
940 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35941 JsepTransportController::Config config;
942 config.redetermine_role_on_ice_restart =
943 configuration.redetermine_role_on_ice_restart;
944 config.ssl_max_version = factory_->options().ssl_max_version;
945 config.disable_encryption = options.disable_encryption;
946 config.bundle_policy = configuration.bundle_policy;
947 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 17:16:44948 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
949 // stub.
950 config.crypto_options = configuration.crypto_options.has_value()
951 ? *configuration.crypto_options
952 : options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:34953 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46954 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35955#if defined(ENABLE_EXTERNAL_AUTH)
956 config.enable_external_auth = true;
957#endif
Zhi Huangb57e1692018-06-12 18:41:11958 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:42959
Bjorn Mellema9bbd862018-11-02 16:07:48960 if (configuration.use_media_transport ||
961 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 20:15:42962 if (!factory_->media_transport_factory()) {
963 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 16:07:48964 << "PeerConnecton is initialized with use_media_transport = true or "
965 << "use_media_transport_for_data_channels = true "
966 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 20:15:42967 return false;
968 }
969
970 config.media_transport_factory = factory_->media_transport_factory();
971 }
972
Zhi Huange830e682018-03-30 17:48:35973 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:15974 signaling_thread(), network_thread(), port_allocator_.get(),
975 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:35976 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59977 this, &PeerConnection::OnTransportControllerConnectionState);
978 transport_controller_->SignalStandardizedIceConnectionState.connect(
979 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:17980 transport_controller_->SignalConnectionState.connect(
981 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:35982 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17983 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35984 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17985 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35986 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17987 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
988 transport_controller_->SignalDtlsHandshakeError.connect(
989 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
990
991 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25992
deadbeefab9b2d12015-10-14 18:33:11993 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01994 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36995
Steve Antonba818672017-11-06 18:21:57996 configuration_ = configuration;
997
Steve Anton75737c02017-11-06 18:37:17998 // Obtain a certificate from RTCConfiguration if any were provided (optional).
999 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1000 if (!configuration.certificates.empty()) {
1001 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1002 // just picking the first one. The decision should be made based on the DTLS
1003 // handshake. The DTLS negotiations need to know about all certificates.
1004 certificate = configuration.certificates[0];
1005 }
1006
Steve Antond25da372017-11-06 22:50:291007 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171008
1009 if (options.disable_encryption) {
1010 dtls_enabled_ = false;
1011 } else {
1012 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:471013 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:171014 // |configuration| can override the default |dtls_enabled_| value.
1015 if (configuration.enable_dtls_srtp) {
1016 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1017 }
1018 }
1019
Bjorn Mellem175aa2e2018-11-08 19:23:221020 if (configuration.use_media_transport_for_data_channels) {
1021 if (configuration.enable_rtp_data_channel) {
1022 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1023 "use_media_transport_for_data_channels are "
1024 "incompatible and cannot both be set to true";
1025 return false;
1026 }
1027 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1028 } else if (configuration.enable_rtp_data_channel) {
1029 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1030 // set. It takes precendence over the disable_sctp_data_channels
1031 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 18:37:171032 data_channel_type_ = cricket::DCT_RTP;
1033 } else {
1034 // DTLS has to be enabled to use SCTP.
1035 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1036 data_channel_type_ = cricket::DCT_SCTP;
1037 }
1038 }
1039
1040 video_options_.screencast_min_bitrate_kbps =
1041 configuration.screencast_min_bitrate;
1042 audio_options_.combined_audio_video_bwe =
1043 configuration.combined_audio_video_bwe;
1044
1045 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301046 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171047
1048 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301049 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171050
Jakob Ivarsson10403ae2018-11-27 14:45:201051 audio_options_.audio_jitter_buffer_min_delay_ms =
1052 configuration.audio_jitter_buffer_min_delay_ms;
1053
Steve Anton75737c02017-11-06 18:37:171054 // Whether the certificate generator/certificate is null or not determines
1055 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1056 // the right instructions by clearing the variables if needed.
1057 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471058 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171059 certificate = nullptr;
1060 } else if (certificate) {
1061 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471062 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171063 }
1064
1065 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1066 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471067 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171068 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1069 this, &PeerConnection::OnCertificateReady);
1070
1071 if (options.disable_encryption) {
1072 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1073 }
1074
1075 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 17:16:441076 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361077
Steve Anton4171afb2017-11-20 18:20:221078 // Add default audio/video transceivers for Plan B SDP.
1079 if (!IsUnifiedPlan()) {
1080 transceivers_.push_back(
1081 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1082 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1083 transceivers_.push_back(
1084 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1085 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1086 }
Harald Alvestrand183e09d2018-06-28 10:04:411087 int delay_ms =
1088 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401089 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1090 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:361091 return true;
1092}
1093
Steve Anton038834f2017-07-14 22:59:591094RTCError PeerConnection::ValidateConfiguration(
1095 const RTCConfiguration& config) const {
1096 if (config.ice_regather_interval_range &&
1097 config.continual_gathering_policy == GATHER_ONCE) {
1098 return RTCError(RTCErrorType::INVALID_PARAMETER,
1099 "ice_regather_interval_range specified but continual "
1100 "gathering policy is GATHER_ONCE");
1101 }
Qingsi Wangdea68892018-03-27 17:55:211102 auto result =
1103 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1104 return result;
Steve Anton038834f2017-07-14 22:59:591105}
1106
Yves Gerey665174f2018-06-19 13:03:051107rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581108 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1109 "Plan SdpSemantics. Please use GetSenders "
1110 "instead.";
deadbeefab9b2d12015-10-14 18:33:111111 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361112}
1113
Yves Gerey665174f2018-06-19 13:03:051114rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581115 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1116 "Plan SdpSemantics. Please use GetReceivers "
1117 "instead.";
deadbeefab9b2d12015-10-14 18:33:111118 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361119}
1120
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291121bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581122 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1123 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171124 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361125 if (IsClosed()) {
1126 return false;
1127 }
deadbeefab9b2d12015-10-14 18:33:111128 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361129 return false;
1130 }
deadbeefab9b2d12015-10-14 18:33:111131
1132 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431133 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1134 observer->SignalAudioTrackAdded.connect(this,
1135 &PeerConnection::OnAudioTrackAdded);
1136 observer->SignalAudioTrackRemoved.connect(
1137 this, &PeerConnection::OnAudioTrackRemoved);
1138 observer->SignalVideoTrackAdded.connect(this,
1139 &PeerConnection::OnVideoTrackAdded);
1140 observer->SignalVideoTrackRemoved.connect(
1141 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291142 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111143
deadbeefab9b2d12015-10-14 18:33:111144 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251145 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111146 }
1147 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251148 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111149 }
1150
tommi@webrtc.org03505bc2014-07-14 20:15:261151 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:161152 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361153 return true;
1154}
1155
1156void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581157 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1158 "Plan SdpSemantics. Please use RemoveTrack "
1159 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171160 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251161 if (!IsClosed()) {
1162 for (const auto& track : local_stream->GetAudioTracks()) {
1163 RemoveAudioTrack(track.get(), local_stream);
1164 }
1165 for (const auto& track : local_stream->GetVideoTracks()) {
1166 RemoveVideoTrack(track.get(), local_stream);
1167 }
deadbeefab9b2d12015-10-14 18:33:111168 }
deadbeefab9b2d12015-10-14 18:33:111169 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431170 stream_observers_.erase(
1171 std::remove_if(
1172 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291173 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281174 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431175 }),
1176 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111177
henrike@webrtc.org28e20752013-07-10 00:45:361178 if (IsClosed()) {
1179 return;
1180 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161181 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361182}
1183
Steve Anton2d6c76a2018-01-06 01:10:521184RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101186 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521187 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571188 if (!track) {
1189 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1190 }
1191 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1192 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1193 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1194 "Track has invalid kind: " + track->kind());
1195 }
Steve Antonf9381f02017-12-14 18:23:571196 if (IsClosed()) {
1197 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1198 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421199 }
Steve Anton4171afb2017-11-20 18:20:221200 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571201 LOG_AND_RETURN_ERROR(
1202 RTCErrorType::INVALID_PARAMETER,
1203 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421204 }
Steve Antonf9381f02017-12-14 18:23:571205 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361206 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1207 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571208 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161209 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171210 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571211 }
1212 return sender_or_error;
1213}
deadbeefe1f9d832016-01-14 23:35:421214
Steve Antonf9381f02017-12-14 18:23:571215RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1216PeerConnection::AddTrackPlanB(
1217 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101218 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361219 if (stream_ids.size() > 1u) {
1220 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1221 "AddTrack with more than one stream is not "
1222 "supported with Plan B semantics.");
1223 }
1224 std::vector<std::string> adjusted_stream_ids = stream_ids;
1225 if (adjusted_stream_ids.empty()) {
1226 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1227 }
Steve Anton02ee47c2018-01-11 00:26:061228 cricket::MediaType media_type =
1229 (track->kind() == MediaStreamTrackInterface::kAudioKind
1230 ? cricket::MEDIA_TYPE_AUDIO
1231 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361232 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201233 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421234 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051235 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221236 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221237 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181238 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361239 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221240 if (sender_info) {
1241 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421242 }
Steve Antonf9381f02017-12-14 18:23:571243 } else {
1244 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051245 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221246 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221247 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181248 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361249 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221250 if (sender_info) {
1251 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421252 }
deadbeefe1f9d832016-01-14 23:35:421253 }
Steve Anton02ee47c2018-01-11 00:26:061254 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571255}
deadbeefe1f9d832016-01-14 23:35:421256
Steve Antonf9381f02017-12-14 18:23:571257RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1258PeerConnection::AddTrackUnifiedPlan(
1259 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101260 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571261 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1262 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231263 RTC_LOG(LS_INFO) << "Reusing an existing "
1264 << cricket::MediaTypeToString(transceiver->media_type())
1265 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571266 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121267 transceiver->internal()->set_direction(
1268 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571269 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121270 transceiver->internal()->set_direction(
1271 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571272 }
Steve Anton02ee47c2018-01-11 00:26:061273 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101274 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571275 } else {
1276 cricket::MediaType media_type =
1277 (track->kind() == MediaStreamTrackInterface::kAudioKind
1278 ? cricket::MEDIA_TYPE_AUDIO
1279 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231280 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1281 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501282 std::string sender_id = track->id();
1283 // Avoid creating a sender with an existing ID by generating a random ID.
1284 // This can happen if this is the second time AddTrack has created a sender
1285 // for this track.
1286 if (FindSenderById(sender_id)) {
1287 sender_id = rtc::CreateRandomUuid();
1288 }
Florent Castelli892acf02018-10-01 20:47:201289 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061290 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1291 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571292 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121293 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571294 }
Steve Antonf9381f02017-12-14 18:23:571295 return transceiver->sender();
1296}
1297
1298rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1299PeerConnection::FindFirstTransceiverForAddedTrack(
1300 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1301 RTC_DCHECK(track);
1302 for (auto transceiver : transceivers_) {
1303 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081304 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571305 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421306 !transceiver->internal()->has_ever_been_used_to_send() &&
1307 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571308 return transceiver;
1309 }
1310 }
1311 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421312}
1313
1314bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1315 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331316 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571317}
1318
Steve Anton24db5732018-07-23 17:27:331319RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571320 rtc::scoped_refptr<RtpSenderInterface> sender) {
1321 if (!sender) {
1322 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1323 }
deadbeefe1f9d832016-01-14 23:35:421324 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1326 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421327 }
Steve Antonf9381f02017-12-14 18:23:571328 if (IsUnifiedPlan()) {
1329 auto transceiver = FindTransceiverBySender(sender);
1330 if (!transceiver || !sender->track()) {
1331 return RTCError::OK();
1332 }
1333 sender->SetTrack(nullptr);
1334 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121335 transceiver->internal()->set_direction(
1336 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571337 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121338 transceiver->internal()->set_direction(
1339 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571340 }
Steve Anton4171afb2017-11-20 18:20:221341 } else {
Steve Antonf9381f02017-12-14 18:23:571342 bool removed;
1343 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1344 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1345 } else {
1346 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1347 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1348 }
1349 if (!removed) {
1350 LOG_AND_RETURN_ERROR(
1351 RTCErrorType::INVALID_PARAMETER,
1352 "Couldn't find sender " + sender->id() + " to remove.");
1353 }
Steve Anton4171afb2017-11-20 18:20:221354 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161355 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571356 return RTCError::OK();
1357}
1358
1359rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1360PeerConnection::FindTransceiverBySender(
1361 rtc::scoped_refptr<RtpSenderInterface> sender) {
1362 for (auto transceiver : transceivers_) {
1363 if (transceiver->sender() == sender) {
1364 return transceiver;
1365 }
1366 }
1367 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421368}
1369
Steve Anton9158ef62017-11-27 21:01:521370RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1371PeerConnection::AddTransceiver(
1372 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1373 return AddTransceiver(track, RtpTransceiverInit());
1374}
1375
1376RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1377PeerConnection::AddTransceiver(
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1379 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581380 RTC_CHECK(IsUnifiedPlan())
1381 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521382 if (!track) {
1383 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1384 }
1385 cricket::MediaType media_type;
1386 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1387 media_type = cricket::MEDIA_TYPE_AUDIO;
1388 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1389 media_type = cricket::MEDIA_TYPE_VIDEO;
1390 } else {
1391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1392 "Track kind is not audio or video");
1393 }
1394 return AddTransceiver(media_type, track, init);
1395}
1396
1397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1399 return AddTransceiver(media_type, RtpTransceiverInit());
1400}
1401
1402RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1403PeerConnection::AddTransceiver(cricket::MediaType media_type,
1404 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581405 RTC_CHECK(IsUnifiedPlan())
1406 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521407 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1408 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1409 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1410 "media type is not audio or video");
1411 }
1412 return AddTransceiver(media_type, nullptr, init);
1413}
1414
1415RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1416PeerConnection::AddTransceiver(
1417 cricket::MediaType media_type,
1418 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071419 const RtpTransceiverInit& init,
1420 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521421 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1422 media_type == cricket::MEDIA_TYPE_VIDEO));
1423 if (track) {
1424 RTC_DCHECK_EQ(media_type,
1425 (track->kind() == MediaStreamTrackInterface::kAudioKind
1426 ? cricket::MEDIA_TYPE_AUDIO
1427 : cricket::MEDIA_TYPE_VIDEO));
1428 }
1429
1430 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 20:47:201431 if (init.send_encodings.size() > 1) {
1432 LOG_AND_RETURN_ERROR(
1433 RTCErrorType::UNSUPPORTED_PARAMETER,
1434 "Attempted to create an encoder with more than 1 encoding parameter.");
1435 }
1436
1437 for (const auto& encoding : init.send_encodings) {
1438 if (encoding.ssrc.has_value()) {
1439 LOG_AND_RETURN_ERROR(
1440 RTCErrorType::UNSUPPORTED_PARAMETER,
1441 "Attempted to set an unimplemented parameter of RtpParameters.");
1442 }
1443 }
1444
1445 RtpParameters parameters;
1446 parameters.encodings = init.send_encodings;
1447 if (UnimplementedRtpParameterHasValue(parameters)) {
1448 LOG_AND_RETURN_ERROR(
1449 RTCErrorType::UNSUPPORTED_PARAMETER,
1450 "Attempted to set an unimplemented parameter of RtpParameters.");
1451 }
Steve Anton9158ef62017-11-27 21:01:521452
Steve Anton3d954a62018-04-02 18:27:231453 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1454 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501455 // Set the sender ID equal to the track ID if the track is specified unless
1456 // that sender ID is already in use.
1457 std::string sender_id =
1458 (track && !FindSenderById(track->id()) ? track->id()
1459 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 20:47:201460 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1461 init.send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061462 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1463 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1464 transceiver->internal()->set_direction(init.direction);
1465
Steve Anton22da89f2018-01-25 21:58:071466 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161467 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071468 }
Steve Antonf9381f02017-12-14 18:23:571469
1470 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1471}
1472
Steve Anton02ee47c2018-01-11 00:26:061473rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1474PeerConnection::CreateSender(
1475 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361476 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061477 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201478 const std::vector<std::string>& stream_ids,
1479 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 21:01:521480 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061481 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1482 RTC_DCHECK(!track ||
1483 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1484 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1485 signaling_thread(),
Steve Anton111fdfd2018-06-25 20:03:361486 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341487 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061488 } else {
1489 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1490 RTC_DCHECK(!track ||
1491 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1492 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 20:03:361493 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341494 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061495 }
Steve Anton111fdfd2018-06-25 20:03:361496 bool set_track_succeeded = sender->SetTrack(track);
1497 RTC_DCHECK(set_track_succeeded);
1498 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 20:47:201499 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061500 return sender;
1501}
1502
1503rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1504PeerConnection::CreateReceiver(cricket::MediaType media_type,
1505 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521506 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1507 receiver;
Steve Anton9158ef62017-11-27 21:01:521508 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521509 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531510 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1511 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341512 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521513 } else {
Steve Anton02ee47c2018-01-11 00:26:061514 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521515 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531516 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1517 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341518 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521519 }
Steve Anton02ee47c2018-01-11 00:26:061520 return receiver;
1521}
1522
1523rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1524PeerConnection::CreateAndAddTransceiver(
1525 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1526 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1527 receiver) {
Steve Anton07563732018-06-26 18:13:501528 // Ensure that the new sender does not have an ID that is already in use by
1529 // another sender.
1530 // Allow receiver IDs to conflict since those come from remote SDP (which
1531 // could be invalid, but should not cause a crash).
1532 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061533 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1534 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521535 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121536 transceiver->internal()->SignalNegotiationNeeded.connect(
1537 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571538 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521539}
1540
Steve Anton52d86772018-02-20 23:48:121541void PeerConnection::OnNegotiationNeeded() {
1542 RTC_DCHECK_RUN_ON(signaling_thread());
1543 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 08:50:161544 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121545}
1546
deadbeeffac06552015-11-25 19:26:011547rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441548 const std::string& kind,
1549 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581550 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1551 "Plan SdpSemantics. Please use AddTransceiver "
1552 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171553 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251554 if (IsClosed()) {
1555 return nullptr;
1556 }
Steve Anton4171afb2017-11-20 18:20:221557
Seth Hampson5b4f0752018-04-02 23:31:361558 // Internally we need to have one stream with Plan B semantics, so we
1559 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101560 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361561 if (stream_id.empty()) {
1562 stream_ids.push_back(rtc::CreateRandomUuid());
1563 RTC_LOG(LS_INFO)
1564 << "No stream_id specified for sender. Generated stream ID: "
1565 << stream_ids[0];
1566 } else {
Seth Hampson845e8782018-03-02 19:34:101567 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061568 }
1569
Steve Anton4171afb2017-11-20 18:20:221570 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391571 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011572 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 20:03:361573 auto* audio_sender = new AudioRtpSender(
1574 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-14 00:26:051575 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391576 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061577 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221578 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011579 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351580 auto* video_sender =
Steve Anton111fdfd2018-06-25 20:03:361581 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-14 00:26:051582 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391583 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061584 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221585 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011586 } else {
Mirko Bonadei675513b2017-11-09 10:09:251587 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221588 return nullptr;
deadbeeffac06552015-11-25 19:26:011589 }
Steve Anton111fdfd2018-06-25 20:03:361590 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221591
deadbeefe1f9d832016-01-14 23:35:421592 return new_sender;
deadbeeffac06552015-11-25 19:26:011593}
1594
deadbeef70ab1a12015-09-28 23:53:551595std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1596 const {
deadbeefa601f5c2016-06-06 21:27:391597 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221598 for (auto sender : GetSendersInternal()) {
1599 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391600 }
1601 return ret;
deadbeef70ab1a12015-09-28 23:53:551602}
1603
Steve Anton4171afb2017-11-20 18:20:221604std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1605PeerConnection::GetSendersInternal() const {
1606 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1607 all_senders;
1608 for (auto transceiver : transceivers_) {
1609 auto senders = transceiver->internal()->senders();
1610 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1611 }
1612 return all_senders;
1613}
1614
deadbeef70ab1a12015-09-28 23:53:551615std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1616PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391617 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221618 for (const auto& receiver : GetReceiversInternal()) {
1619 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391620 }
1621 return ret;
deadbeef70ab1a12015-09-28 23:53:551622}
1623
Steve Anton4171afb2017-11-20 18:20:221624std::vector<
1625 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1626PeerConnection::GetReceiversInternal() const {
1627 std::vector<
1628 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1629 all_receivers;
1630 for (auto transceiver : transceivers_) {
1631 auto receivers = transceiver->internal()->receivers();
1632 all_receivers.insert(all_receivers.end(), receivers.begin(),
1633 receivers.end());
1634 }
1635 return all_receivers;
1636}
1637
Steve Anton9158ef62017-11-27 21:01:521638std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1639PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581640 RTC_CHECK(IsUnifiedPlan())
1641 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521642 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1643 for (auto transceiver : transceivers_) {
1644 all_transceivers.push_back(transceiver);
1645 }
1646 return all_transceivers;
1647}
1648
henrike@webrtc.org28e20752013-07-10 00:45:361649bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491650 MediaStreamTrackInterface* track,
1651 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171652 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281653 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561654 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251655 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361656 return false;
1657 }
1658
tommi@webrtc.org03505bc2014-07-14 20:15:261659 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151660 // The StatsCollector is used to tell if a track is valid because it may
1661 // remember tracks that the PeerConnection previously removed.
1662 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251663 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1664 << track->id();
zhihuange9e94c32016-11-04 18:38:151665 return false;
1666 }
Steve Antonad182762018-09-05 20:22:401667 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1668 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361669 return true;
1670}
1671
hbos74e1a4f2016-09-16 06:33:011672void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201673 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011674 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201675 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011676 stats_collector_->GetStatsReport(callback);
1677}
1678
Henrik Boström1df1bf82018-03-20 12:24:201679void PeerConnection::GetStats(
1680 rtc::scoped_refptr<RtpSenderInterface> selector,
1681 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1682 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1683 RTC_DCHECK(callback);
1684 RTC_DCHECK(stats_collector_);
1685 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1686 if (selector) {
1687 for (const auto& proxy_transceiver : transceivers_) {
1688 for (const auto& proxy_sender :
1689 proxy_transceiver->internal()->senders()) {
1690 if (proxy_sender == selector) {
1691 internal_sender = proxy_sender->internal();
1692 break;
1693 }
1694 }
1695 if (internal_sender)
1696 break;
1697 }
1698 }
Sebastian Jansson6eb8a162018-11-16 10:29:551699 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:201700 // belong to the PeerConnection (in Plan B, senders can be removed from the
1701 // PeerConnection). This means that "all the stats objects representing the
1702 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1703 // produces an empty stats report.
1704 stats_collector_->GetStatsReport(internal_sender, callback);
1705}
1706
1707void PeerConnection::GetStats(
1708 rtc::scoped_refptr<RtpReceiverInterface> selector,
1709 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1710 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1711 RTC_DCHECK(callback);
1712 RTC_DCHECK(stats_collector_);
1713 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1714 if (selector) {
1715 for (const auto& proxy_transceiver : transceivers_) {
1716 for (const auto& proxy_receiver :
1717 proxy_transceiver->internal()->receivers()) {
1718 if (proxy_receiver == selector) {
1719 internal_receiver = proxy_receiver->internal();
1720 break;
1721 }
1722 }
1723 if (internal_receiver)
1724 break;
1725 }
1726 }
Sebastian Jansson6eb8a162018-11-16 10:29:551727 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:201728 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1729 // the PeerConnection). This means that "all the stats objects representing
1730 // the selector" is an empty set. Invoking GetStatsReport() with a null
1731 // selector produces an empty stats report.
1732 stats_collector_->GetStatsReport(internal_receiver, callback);
1733}
1734
henrike@webrtc.org28e20752013-07-10 00:45:361735PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1736 return signaling_state_;
1737}
1738
henrike@webrtc.org28e20752013-07-10 00:45:361739PeerConnectionInterface::IceConnectionState
1740PeerConnection::ice_connection_state() {
1741 return ice_connection_state_;
1742}
1743
Alex Loiko9289eda2018-11-23 16:18:591744PeerConnectionInterface::IceConnectionState
1745PeerConnection::standardized_ice_connection_state() {
1746 return standardized_ice_connection_state_;
1747}
1748
Jonas Olsson635474e2018-10-18 13:58:171749PeerConnectionInterface::PeerConnectionState
1750PeerConnection::peer_connection_state() {
1751 return connection_state_;
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:361754PeerConnectionInterface::IceGatheringState
1755PeerConnection::ice_gathering_state() {
1756 return ice_gathering_state_;
1757}
1758
Yves Gerey665174f2018-06-19 13:03:051759rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361760 const std::string& label,
1761 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171762 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501763
deadbeefab9b2d12015-10-14 18:33:111764 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111765
kwibergd1fe2812016-04-27 13:47:291766 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581767 if (config) {
1768 internal_config.reset(new InternalDataChannelInit(*config));
1769 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521770 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111771 InternalCreateDataChannel(label, internal_config.get()));
1772 if (!channel.get()) {
1773 return nullptr;
1774 }
henrike@webrtc.org28e20752013-07-10 00:45:361775
jiayl@webrtc.org001fd2d2014-05-29 15:31:111776 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1777 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171778 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161779 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111780 }
Harald Alvestrand8ebba742018-05-31 12:00:341781 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361782 return DataChannelProxy::Create(signaling_thread(), channel.get());
1783}
1784
1785void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161786 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171787 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511788
nisse7ce109a2017-01-31 08:57:561789 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251790 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161791 return;
1792 }
deadbeefab9b2d12015-10-14 18:33:111793
Steve Anton8d3444d2017-10-20 22:30:511794 if (IsClosed()) {
1795 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251796 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031797 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101798 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511799 return;
1800 }
1801
zhihuang1c378ed2017-08-17 21:10:501802 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111803 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251804 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031805 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101806 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111807 return;
1808 }
1809
Steve Anton22da89f2018-01-25 21:58:071810 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1811 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1812 if (IsUnifiedPlan()) {
1813 RTCError error = HandleLegacyOfferOptions(options);
1814 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031815 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071816 return;
1817 }
1818 }
1819
zhihuang1c378ed2017-08-17 21:10:501820 cricket::MediaSessionOptions session_options;
1821 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291822 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361823}
1824
Steve Anton22da89f2018-01-25 21:58:071825RTCError PeerConnection::HandleLegacyOfferOptions(
1826 const RTCOfferAnswerOptions& options) {
1827 RTC_DCHECK(IsUnifiedPlan());
1828
1829 if (options.offer_to_receive_audio == 0) {
1830 RemoveRecvDirectionFromReceivingTransceiversOfType(
1831 cricket::MEDIA_TYPE_AUDIO);
1832 } else if (options.offer_to_receive_audio == 1) {
1833 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1834 } else if (options.offer_to_receive_audio > 1) {
1835 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1836 "offer_to_receive_audio > 1 is not supported.");
1837 }
1838
1839 if (options.offer_to_receive_video == 0) {
1840 RemoveRecvDirectionFromReceivingTransceiversOfType(
1841 cricket::MEDIA_TYPE_VIDEO);
1842 } else if (options.offer_to_receive_video == 1) {
1843 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1844 } else if (options.offer_to_receive_video > 1) {
1845 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1846 "offer_to_receive_video > 1 is not supported.");
1847 }
1848
1849 return RTCError::OK();
1850}
1851
1852void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1853 cricket::MediaType media_type) {
1854 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231855 RtpTransceiverDirection new_direction =
1856 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1857 if (new_direction != transceiver->direction()) {
1858 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1859 << " transceiver (MID="
1860 << transceiver->mid().value_or("<not set>") << ") from "
1861 << RtpTransceiverDirectionToString(
1862 transceiver->direction())
1863 << " to "
1864 << RtpTransceiverDirectionToString(new_direction)
1865 << " since CreateOffer specified offer_to_receive=0";
1866 transceiver->internal()->set_direction(new_direction);
1867 }
Steve Anton22da89f2018-01-25 21:58:071868 }
1869}
1870
1871void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1872 cricket::MediaType media_type) {
1873 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231874 RTC_LOG(LS_INFO)
1875 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1876 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071877 RtpTransceiverInit init;
1878 init.direction = RtpTransceiverDirection::kRecvOnly;
1879 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1880 }
1881}
1882
1883std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1884PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1885 std::vector<
1886 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1887 receiving_transceivers;
1888 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081889 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071890 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1891 receiving_transceivers.push_back(transceiver);
1892 }
1893 }
1894 return receiving_transceivers;
1895}
1896
htaa2a49d92016-03-04 10:51:391897void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1898 const RTCOfferAnswerOptions& options) {
1899 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561900 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251901 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391902 return;
1903 }
1904
Steve Antondffead82018-02-06 18:31:291905 if (!(signaling_state_ == kHaveRemoteOffer ||
1906 signaling_state_ == kHaveLocalPrAnswer)) {
1907 std::string error =
1908 "PeerConnection cannot create an answer in a state other than "
1909 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251910 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031911 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101912 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511913 return;
1914 }
1915
Steve Antondffead82018-02-06 18:31:291916 // The remote description should be set if we're in the right state.
1917 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511918
Steve Anton22da89f2018-01-25 21:58:071919 if (IsUnifiedPlan()) {
1920 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1921 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1922 "supported with Unified Plan semantics. Use the "
1923 "RtpTransceiver API instead.";
1924 }
1925 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1926 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1927 "supported with Unified Plan semantics. Use the "
1928 "RtpTransceiver API instead.";
1929 }
1930 }
1931
htaa2a49d92016-03-04 10:51:391932 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501933 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391934
Steve Antond25da372017-11-06 22:50:291935 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361936}
1937
1938void PeerConnection::SetLocalDescription(
1939 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421940 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171941 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561942
Steve Anton80dd7b52018-02-17 01:08:421943 // The SetLocalDescription contract is that we take ownership of the session
1944 // description regardless of the outcome, so wrap it in a unique_ptr right
1945 // away. Ideally, SetLocalDescription's signature will be changed to take the
1946 // description as a unique_ptr argument to formalize this agreement.
1947 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1948
nisse7ce109a2017-01-31 08:57:561949 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251950 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361951 return;
1952 }
Steve Anton8a006912017-12-04 23:25:561953
henrike@webrtc.org28e20752013-07-10 00:45:361954 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031955 PostSetSessionDescriptionFailure(
1956 observer,
1957 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361958 return;
1959 }
Steve Anton8d3444d2017-10-20 22:30:511960
Steve Anton80dd7b52018-02-17 01:08:421961 // If a session error has occurred the PeerConnection is in a possibly
1962 // inconsistent state so fail right away.
1963 if (session_error() != SessionError::kNone) {
1964 std::string error_message = GetSessionErrorMsg();
1965 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031966 PostSetSessionDescriptionFailure(
1967 observer,
1968 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421969 return;
1970 }
Steve Anton8d3444d2017-10-20 22:30:511971
Steve Anton80dd7b52018-02-17 01:08:421972 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1973 if (!error.ok()) {
1974 std::string error_message = GetSetDescriptionErrorMessage(
1975 cricket::CS_LOCAL, desc->GetType(), error);
1976 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031977 PostSetSessionDescriptionFailure(
1978 observer,
1979 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421980 return;
1981 }
1982
1983 // Grab the description type before moving ownership to ApplyLocalDescription,
1984 // which may destroy it before returning.
1985 const SdpType type = desc->GetType();
1986
1987 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561988 // |desc| may be destroyed at this point.
1989
1990 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421991 // If ApplyLocalDescription fails, the PeerConnection could be in an
1992 // inconsistent state, so act conservatively here and set the session error
1993 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1994 SetSessionError(SessionError::kContent, error.message());
1995 std::string error_message =
1996 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, 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 Anton8d3444d2017-10-20 22:30:512001 return;
2002 }
Steve Anton8a006912017-12-04 23:25:562003 RTC_DCHECK(local_description());
2004
2005 PostSetSessionDescriptionSuccess(observer);
2006
Steve Antonad182762018-09-05 20:22:402007 // MaybeStartGathering needs to be called after posting
2008 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2009 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:562010 transport_controller_->MaybeStartGathering();
2011
Steve Antona3a92c22017-12-07 18:27:412012 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562013 // TODO(deadbeef): We already had to hop to the network thread for
2014 // MaybeStartGathering...
2015 network_thread()->Invoke<void>(
2016 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2017 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:302018 // Make UMA notes about what was agreed to.
2019 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562020 }
Harald Alvestrand8ebba742018-05-31 12:00:342021 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562022}
2023
2024RTCError PeerConnection::ApplyLocalDescription(
2025 std::unique_ptr<SessionDescriptionInterface> desc) {
2026 RTC_DCHECK_RUN_ON(signaling_thread());
2027 RTC_DCHECK(desc);
2028
henrike@webrtc.org28e20752013-07-10 00:45:362029 // Update stats here so that we have the most recent stats for tracks and
2030 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262031 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562032
Steve Antondcc3c022017-12-23 00:02:542033 // Take a reference to the old local description since it's used below to
2034 // compare against the new local description. When setting the new local
2035 // description, grab ownership of the replaced session description in case it
2036 // is the same as |old_local_description|, to keep it alive for the duration
2037 // of the method.
2038 const SessionDescriptionInterface* old_local_description =
2039 local_description();
2040 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352041 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512042 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542043 replaced_local_description = pending_local_description_
2044 ? std::move(pending_local_description_)
2045 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562046 current_local_description_ = std::move(desc);
2047 pending_local_description_ = nullptr;
2048 current_remote_description_ = std::move(pending_remote_description_);
2049 } else {
Steve Antondcc3c022017-12-23 00:02:542050 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562051 pending_local_description_ = std::move(desc);
2052 }
2053 // The session description to apply now must be accessed by
2054 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442055 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112056
Bjorn Mellem175aa2e2018-11-08 19:23:222057 if (!is_caller_) {
2058 if (remote_description()) {
2059 // Remote description was applied first, so this PC is the callee.
2060 is_caller_ = false;
2061 } else {
2062 // Local description is applied first, so this PC is the caller.
2063 is_caller_ = true;
2064 }
2065 }
2066
Zhi Huange830e682018-03-30 17:48:352067 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2068 if (!error.ok()) {
2069 return error;
2070 }
2071
Steve Antondcc3c022017-12-23 00:02:542072 if (IsUnifiedPlan()) {
2073 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482074 cricket::CS_LOCAL, *local_description(), old_local_description,
2075 remote_description());
Steve Anton8a006912017-12-04 23:25:562076 if (!error.ok()) {
2077 return error;
2078 }
Steve Anton0f5400a2018-07-17 21:25:362079 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2080 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542081 for (auto transceiver : transceivers_) {
2082 const ContentInfo* content =
2083 FindMediaSectionForTransceiver(transceiver, local_description());
2084 if (!content) {
2085 continue;
2086 }
2087 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:362088 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2089 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542090 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362091 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2092 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2093 // "recvonly", process the removal of a remote track for the media
2094 // description, given transceiver, removeList, and muteTracks.
2095 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2096 (transceiver->internal()->fired_direction() &&
2097 RtpTransceiverDirectionHasRecv(
2098 *transceiver->internal()->fired_direction()))) {
2099 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2100 &removed_streams);
2101 }
2102 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2103 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542104 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362105 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542106 }
Steve Anton0f5400a2018-07-17 21:25:362107 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162108 auto observer = Observer();
Steve Anton0f5400a2018-07-17 21:25:362109 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162110 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362111 }
2112 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162113 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542114 }
2115 } else {
Zhi Huange830e682018-03-30 17:48:352116 // Media channels will be created only when offer is set. These may use new
2117 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542118 if (type == SdpType::kOffer) {
2119 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2120 // description is applied. Restore back to old description.
2121 RTCError error = CreateChannels(*local_description()->description());
2122 if (!error.ok()) {
2123 return error;
2124 }
2125 }
Steve Antondcc3c022017-12-23 00:02:542126 // Remove unused channels if MediaContentDescription is rejected.
2127 RemoveUnusedChannels(local_description()->description());
2128 }
Steve Anton8a006912017-12-04 23:25:562129
Zhi Huange830e682018-03-30 17:48:352130 error = UpdateSessionState(type, cricket::CS_LOCAL,
2131 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562132 if (!error.ok()) {
2133 return error;
2134 }
Steve Antondcc3c022017-12-23 00:02:542135
Steve Anton8a006912017-12-04 23:25:562136 if (remote_description()) {
2137 // Now that we have a local description, we can push down remote candidates.
2138 UseCandidatesInSessionDescription(remote_description());
2139 }
2140
2141 pending_ice_restarts_.clear();
2142 if (session_error() != SessionError::kNone) {
2143 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2144 }
2145
deadbeefab9b2d12015-10-14 18:33:112146 // If setting the description decided our SSL role, allocate any necessary
2147 // SCTP sids.
2148 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222149 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112150 AllocateSctpSids(role);
2151 }
2152
Steve Antond3679212018-01-18 01:41:022153 if (IsUnifiedPlan()) {
2154 for (auto transceiver : transceivers_) {
2155 const ContentInfo* content =
2156 FindMediaSectionForTransceiver(transceiver, local_description());
2157 if (!content) {
2158 continue;
2159 }
Steve Anton74255ff2018-01-25 02:32:572160 const auto& streams = content->media_description()->streams();
2161 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022162 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102163 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022164 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572165 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272166 } else {
2167 // 0 is a special value meaning "this sender has no associated send
2168 // stream". Need to call this so the sender won't attempt to configure
2169 // a no longer existing stream and run into DCHECKs in the lower
2170 // layers.
2171 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-18 01:41:022172 }
2173 }
2174 } else {
2175 // Plan B semantics.
2176
Steve Antondcc3c022017-12-23 00:02:542177 // Update state and SSRC of local MediaStreams and DataChannels based on the
2178 // local session description.
2179 const cricket::ContentInfo* audio_content =
2180 GetFirstAudioContent(local_description()->description());
2181 if (audio_content) {
2182 if (audio_content->rejected) {
2183 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2184 } else {
2185 const cricket::AudioContentDescription* audio_desc =
2186 audio_content->media_description()->as_audio();
2187 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2188 }
deadbeeffaac4972015-11-12 23:33:072189 }
deadbeefab9b2d12015-10-14 18:33:112190
Steve Antondcc3c022017-12-23 00:02:542191 const cricket::ContentInfo* video_content =
2192 GetFirstVideoContent(local_description()->description());
2193 if (video_content) {
2194 if (video_content->rejected) {
2195 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2196 } else {
2197 const cricket::VideoContentDescription* video_desc =
2198 video_content->media_description()->as_video();
2199 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2200 }
deadbeeffaac4972015-11-12 23:33:072201 }
deadbeefab9b2d12015-10-14 18:33:112202 }
2203
2204 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442205 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112206 if (data_content) {
2207 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302208 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112209 if (rtc::starts_with(data_desc->protocol().data(),
2210 cricket::kMediaProtocolRtpPrefix)) {
2211 UpdateLocalRtpDataChannels(data_desc->streams());
2212 }
2213 }
2214
Steve Anton8a006912017-12-04 23:25:562215 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362216}
2217
2218void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072219 SetSessionDescriptionObserver* observer,
2220 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322221 SetRemoteDescription(
2222 std::unique_ptr<SessionDescriptionInterface>(desc),
2223 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2224 new SetRemoteDescriptionObserverAdapter(this, observer)));
2225}
2226
2227void PeerConnection::SetRemoteDescription(
2228 std::unique_ptr<SessionDescriptionInterface> desc,
2229 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172230 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562231
nisse7ce109a2017-01-31 08:57:562232 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252233 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362234 return;
2235 }
Steve Anton8a006912017-12-04 23:25:562236
henrike@webrtc.org28e20752013-07-10 00:45:362237 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322238 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562239 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362240 return;
2241 }
Steve Anton8d3444d2017-10-20 22:30:512242
Steve Anton80dd7b52018-02-17 01:08:422243 // If a session error has occurred the PeerConnection is in a possibly
2244 // inconsistent state so fail right away.
2245 if (session_error() != SessionError::kNone) {
2246 std::string error_message = GetSessionErrorMsg();
2247 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2248 observer->OnSetRemoteDescriptionComplete(
2249 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2250 return;
2251 }
Steve Anton71439a62018-02-15 19:53:062252
Steve Antonba42e992018-04-09 21:10:012253 if (desc->GetType() == SdpType::kOffer) {
2254 // Report to UMA the format of the received offer.
2255 ReportSdpFormatReceived(*desc);
2256 }
2257
Steve Anton80dd7b52018-02-17 01:08:422258 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062259 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422260 std::string error_message = GetSetDescriptionErrorMessage(
2261 cricket::CS_REMOTE, desc->GetType(), error);
2262 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062263 observer->OnSetRemoteDescriptionComplete(
2264 RTCError(error.type(), std::move(error_message)));
2265 return;
2266 }
Steve Anton71439a62018-02-15 19:53:062267
Steve Anton80dd7b52018-02-17 01:08:422268 // Grab the description type before moving ownership to
2269 // ApplyRemoteDescription, which may destroy it before returning.
2270 const SdpType type = desc->GetType();
2271
2272 error = ApplyRemoteDescription(std::move(desc));
2273 // |desc| may be destroyed at this point.
2274
2275 if (!error.ok()) {
2276 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2277 // inconsistent state, so act conservatively here and set the session error
2278 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2279 SetSessionError(SessionError::kContent, error.message());
2280 std::string error_message =
2281 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2282 RTC_LOG(LS_ERROR) << error_message;
2283 observer->OnSetRemoteDescriptionComplete(
2284 RTCError(error.type(), std::move(error_message)));
2285 return;
2286 }
2287 RTC_DCHECK(remote_description());
2288
2289 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562290 // TODO(deadbeef): We already had to hop to the network thread for
2291 // MaybeStartGathering...
2292 network_thread()->Invoke<void>(
2293 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2294 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002295 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302296 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562297 }
2298
2299 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342300 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562301}
2302
2303RTCError PeerConnection::ApplyRemoteDescription(
2304 std::unique_ptr<SessionDescriptionInterface> desc) {
2305 RTC_DCHECK_RUN_ON(signaling_thread());
2306 RTC_DCHECK(desc);
2307
henrike@webrtc.org28e20752013-07-10 00:45:362308 // Update stats here so that we have the most recent stats for tracks and
2309 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262310 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562311
Steve Antondcc3c022017-12-23 00:02:542312 // Take a reference to the old remote description since it's used below to
2313 // compare against the new remote description. When setting the new remote
2314 // description, grab ownership of the replaced session description in case it
2315 // is the same as |old_remote_description|, to keep it alive for the duration
2316 // of the method.
Steve Anton8a006912017-12-04 23:25:562317 const SessionDescriptionInterface* old_remote_description =
2318 remote_description();
Steve Anton8a006912017-12-04 23:25:562319 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512320 SdpType type = desc->GetType();
2321 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562322 replaced_remote_description = pending_remote_description_
2323 ? std::move(pending_remote_description_)
2324 : std::move(current_remote_description_);
2325 current_remote_description_ = std::move(desc);
2326 pending_remote_description_ = nullptr;
2327 current_local_description_ = std::move(pending_local_description_);
2328 } else {
2329 replaced_remote_description = std::move(pending_remote_description_);
2330 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362331 }
Steve Anton8a006912017-12-04 23:25:562332 // The session description to apply now must be accessed by
2333 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442334 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362335
Zhi Huange830e682018-03-30 17:48:352336 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2337 if (!error.ok()) {
2338 return error;
2339 }
Steve Anton8a006912017-12-04 23:25:562340 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542341 if (IsUnifiedPlan()) {
2342 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482343 cricket::CS_REMOTE, *remote_description(), local_description(),
2344 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562345 if (!error.ok()) {
2346 return error;
2347 }
Steve Antondcc3c022017-12-23 00:02:542348 } else {
Zhi Huange830e682018-03-30 17:48:352349 // Media channels will be created only when offer is set. These may use new
2350 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542351 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352352 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542353 // description is applied. Restore back to old description.
2354 RTCError error = CreateChannels(*remote_description()->description());
2355 if (!error.ok()) {
2356 return error;
2357 }
2358 }
Steve Antondcc3c022017-12-23 00:02:542359 // Remove unused channels if MediaContentDescription is rejected.
2360 RemoveUnusedChannels(remote_description()->description());
2361 }
Steve Anton8a006912017-12-04 23:25:562362
Zhi Huange830e682018-03-30 17:48:352363 // NOTE: Candidates allocation will be initiated only when
2364 // SetLocalDescription is called.
2365 error = UpdateSessionState(type, cricket::CS_REMOTE,
2366 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562367 if (!error.ok()) {
2368 return error;
2369 }
2370
2371 if (local_description() &&
2372 !UseCandidatesInSessionDescription(remote_description())) {
2373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2374 }
2375
2376 if (old_remote_description) {
2377 for (const cricket::ContentInfo& content :
2378 old_remote_description->description()->contents()) {
2379 // Check if this new SessionDescription contains new ICE ufrag and
2380 // password that indicates the remote peer requests an ICE restart.
2381 // TODO(deadbeef): When we start storing both the current and pending
2382 // remote description, this should reset pending_ice_restarts and compare
2383 // against the current description.
2384 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2385 content.name)) {
Steve Anton3828c062017-12-06 18:34:512386 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562387 pending_ice_restarts_.insert(content.name);
2388 }
2389 } else {
2390 // We retain all received candidates only if ICE is not restarted.
2391 // When ICE is restarted, all previous candidates belong to an old
2392 // generation and should not be kept.
2393 // TODO(deadbeef): This goes against the W3C spec which says the remote
2394 // description should only contain candidates from the last set remote
2395 // description plus any candidates added since then. We should remove
2396 // this once we're sure it won't break anything.
2397 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2398 old_remote_description, content.name, mutable_remote_description());
2399 }
2400 }
2401 }
2402
2403 if (session_error() != SessionError::kNone) {
2404 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2405 }
2406
2407 // Set the the ICE connection state to connecting since the connection may
2408 // become writable with peer reflexive candidates before any remote candidate
2409 // is signaled.
2410 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2411 // is to have a new signal the indicates a change in checking state from the
2412 // transport and expose a new checking() member from transport that can be
2413 // read to determine the current checking state. The existing SignalConnecting
2414 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412415 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172416 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562417 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2418 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2419 }
2420
deadbeefab9b2d12015-10-14 18:33:112421 // If setting the description decided our SSL role, allocate any necessary
2422 // SCTP sids.
2423 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222424 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112425 AllocateSctpSids(role);
2426 }
2427
Steve Antondcc3c022017-12-23 00:02:542428 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422429 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182430 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362431 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132432 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182433 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542434 for (auto transceiver : transceivers_) {
2435 const ContentInfo* content =
2436 FindMediaSectionForTransceiver(transceiver, remote_description());
2437 if (!content) {
2438 continue;
2439 }
2440 const MediaContentDescription* media_desc = content->media_description();
2441 RtpTransceiverDirection local_direction =
2442 RtpTransceiverDirectionReversed(media_desc->direction());
2443 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2444 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2445 // transceiver's current direction is neither sendrecv nor recvonly,
2446 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362447 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422448 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332449 // The remote description has signaled the stream IDs.
2450 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422451 }
Steve Antondcc3c022017-12-23 00:02:542452 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362453 (!transceiver->fired_direction() ||
2454 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232455 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362456 << content->name << " (added to "
2457 << GetStreamIdsString(stream_ids) << ").";
2458
2459 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2460 for (const std::string& stream_id : stream_ids) {
2461 rtc::scoped_refptr<MediaStreamInterface> stream =
2462 remote_streams_->find(stream_id);
2463 if (!stream) {
2464 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2465 MediaStream::Create(stream_id));
2466 remote_streams_->AddStream(stream);
2467 added_streams.push_back(stream);
2468 }
2469 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202470 }
Steve Anton3172c032018-05-03 22:30:182471 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 18:51:532472 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2473 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 23:31:362474 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 22:30:182475 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542476 }
Steve Anton0f5400a2018-07-17 21:25:362477 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2478 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2479 // removal of a remote track for the media description, given transceiver,
2480 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:542481 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362482 (transceiver->fired_direction() &&
2483 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2484 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2485 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542486 }
Steve Anton0f5400a2018-07-17 21:25:362487 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2488 transceiver->internal()->set_fired_direction(local_direction);
2489 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2490 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542491 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362492 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2493 // direction.
Steve Antondcc3c022017-12-23 00:02:542494 transceiver->internal()->set_current_direction(local_direction);
2495 }
Steve Anton0f5400a2018-07-17 21:25:362496 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2497 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:542498 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232499 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2500 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542501 transceiver->Stop();
2502 }
Seth Hampson2f0d7022018-02-20 19:54:422503 if (!content->rejected &&
2504 RtpTransceiverDirectionHasRecv(local_direction)) {
2505 // Set ssrc to 0 in the case of an unsignalled ssrc.
2506 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332507 if (!media_desc->streams().empty() &&
2508 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422509 ssrc = media_desc->streams()[0].first_ssrc();
2510 }
2511 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022512 }
Steve Antondcc3c022017-12-23 00:02:542513 }
Steve Antonc49bcd92018-02-14 22:28:132514 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162515 auto observer = Observer();
Steve Anton3172c032018-05-03 22:30:182516 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162517 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162518 observer->OnTrack(transceiver);
2519 observer->OnAddTrack(transceiver->receiver(),
2520 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202521 }
Steve Antonc49bcd92018-02-14 22:28:132522 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162523 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132524 }
Steve Anton0f5400a2018-07-17 21:25:362525 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162526 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182527 }
2528 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162529 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182530 }
Steve Antondcc3c022017-12-23 00:02:542531 }
2532
Henrik Boströmfdb92012017-11-09 18:55:442533 const cricket::ContentInfo* audio_content =
2534 GetFirstAudioContent(remote_description()->description());
2535 const cricket::ContentInfo* video_content =
2536 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402537 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442538 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402539 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442540 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402541 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442542 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402543
2544 // Check if the descriptions include streams, just in case the peer supports
2545 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442546 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402547 (audio_desc && !audio_desc->streams().empty()) ||
2548 (video_desc && !video_desc->streams().empty())) {
2549 remote_peer_supports_msid_ = true;
2550 }
deadbeefab9b2d12015-10-14 18:33:112551
2552 // We wait to signal new streams until we finish processing the description,
2553 // since only at that point will new streams have all their tracks.
2554 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2555
Steve Antondcc3c022017-12-23 00:02:542556 if (!IsUnifiedPlan()) {
2557 // TODO(steveanton): When removing RTP senders/receivers in response to a
2558 // rejected media section, there is some cleanup logic that expects the
2559 // voice/ video channel to still be set. But in this method the voice/video
2560 // channel would have been destroyed by the SetRemoteDescription caller
2561 // above so the cleanup that relies on them fails to run. The RemoveSenders
2562 // calls should be moved to right before the DestroyChannel calls to fix
2563 // this.
Steve Anton8d3444d2017-10-20 22:30:512564
Steve Antondcc3c022017-12-23 00:02:542565 // Find all audio rtp streams and create corresponding remote AudioTracks
2566 // and MediaStreams.
2567 if (audio_content) {
2568 if (audio_content->rejected) {
2569 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2570 } else {
2571 bool default_audio_track_needed =
2572 !remote_peer_supports_msid_ &&
2573 RtpTransceiverDirectionHasSend(audio_desc->direction());
2574 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2575 default_audio_track_needed, audio_desc->type(),
2576 new_streams);
2577 }
deadbeeffaac4972015-11-12 23:33:072578 }
deadbeefab9b2d12015-10-14 18:33:112579
Steve Antondcc3c022017-12-23 00:02:542580 // Find all video rtp streams and create corresponding remote VideoTracks
2581 // and MediaStreams.
2582 if (video_content) {
2583 if (video_content->rejected) {
2584 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2585 } else {
2586 bool default_video_track_needed =
2587 !remote_peer_supports_msid_ &&
2588 RtpTransceiverDirectionHasSend(video_desc->direction());
2589 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2590 default_video_track_needed, video_desc->type(),
2591 new_streams);
2592 }
deadbeeffaac4972015-11-12 23:33:072593 }
deadbeefab9b2d12015-10-14 18:33:112594
Steve Antondcc3c022017-12-23 00:02:542595 // Update the DataChannels with the information from the remote peer.
2596 if (data_desc) {
2597 if (rtc::starts_with(data_desc->protocol().data(),
2598 cricket::kMediaProtocolRtpPrefix)) {
2599 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2600 }
deadbeefab9b2d12015-10-14 18:33:112601 }
deadbeefab9b2d12015-10-14 18:33:112602
Steve Antondcc3c022017-12-23 00:02:542603 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162604 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542605 for (size_t i = 0; i < new_streams->count(); ++i) {
2606 MediaStreamInterface* new_stream = new_streams->at(i);
2607 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:162608 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542609 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2610 }
deadbeefab9b2d12015-10-14 18:33:112611
Steve Antondcc3c022017-12-23 00:02:542612 UpdateEndedRemoteMediaStreams();
2613 }
deadbeefab9b2d12015-10-14 18:33:112614
Steve Anton8a006912017-12-04 23:25:562615 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332616}
2617
Steve Anton0f5400a2018-07-17 21:25:362618void PeerConnection::ProcessRemovalOfRemoteTrack(
2619 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2620 transceiver,
2621 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2622 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2623 RTC_DCHECK(transceiver->mid());
2624 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2625 << *transceiver->mid();
2626 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2627 transceiver->internal()->receiver_internal()->streams();
2628 // This will remove the remote track from the streams.
2629 transceiver->internal()->receiver_internal()->set_stream_ids({});
2630 remove_list->push_back(transceiver);
2631 // Remove any streams that no longer have tracks.
2632 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2633 // of streams, see if the stream was removed by checking if this was the
2634 // last receiver with that stream ID.
2635 for (auto stream : media_streams) {
2636 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2637 remote_streams_->RemoveStream(stream);
2638 removed_streams->push_back(stream);
2639 }
2640 }
2641}
2642
Steve Antondcc3c022017-12-23 00:02:542643RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2644 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482645 const SessionDescriptionInterface& new_session,
2646 const SessionDescriptionInterface* old_local_description,
2647 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542648 RTC_DCHECK(IsUnifiedPlan());
2649
Steve Anton7464fca2018-01-19 19:10:372650 const cricket::ContentGroup* bundle_group = nullptr;
2651 if (new_session.GetType() == SdpType::kOffer) {
2652 auto bundle_group_or_error =
2653 GetEarlyBundleGroup(*new_session.description());
2654 if (!bundle_group_or_error.ok()) {
2655 return bundle_group_or_error.MoveError();
2656 }
2657 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542658 }
Steve Antondcc3c022017-12-23 00:02:542659
Steve Antondcc3c022017-12-23 00:02:542660 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542661 for (size_t i = 0; i < new_contents.size(); ++i) {
2662 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542663 cricket::MediaType media_type = new_content.media_description()->type();
2664 seen_mids_.insert(new_content.name);
2665 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2666 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482667 const cricket::ContentInfo* old_local_content = nullptr;
2668 if (old_local_description &&
2669 i < old_local_description->description()->contents().size()) {
2670 old_local_content =
2671 &old_local_description->description()->contents()[i];
2672 }
2673 const cricket::ContentInfo* old_remote_content = nullptr;
2674 if (old_remote_description &&
2675 i < old_remote_description->description()->contents().size()) {
2676 old_remote_content =
2677 &old_remote_description->description()->contents()[i];
2678 }
Steve Antondcc3c022017-12-23 00:02:542679 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482680 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2681 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542682 if (!transceiver_or_error.ok()) {
2683 return transceiver_or_error.MoveError();
2684 }
2685 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542686 RTCError error =
2687 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2688 if (!error.ok()) {
2689 return error;
2690 }
2691 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232692 if (GetDataMid() && new_content.name != *GetDataMid()) {
2693 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232694 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2695 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232696 continue;
2697 }
2698 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2699 if (!error.ok()) {
2700 return error;
2701 }
Steve Antondcc3c022017-12-23 00:02:542702 } else {
2703 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2704 "Unknown section type.");
2705 }
2706 }
2707
2708 return RTCError::OK();
2709}
2710
2711RTCError PeerConnection::UpdateTransceiverChannel(
2712 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2713 transceiver,
2714 const cricket::ContentInfo& content,
2715 const cricket::ContentGroup* bundle_group) {
2716 RTC_DCHECK(IsUnifiedPlan());
2717 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-14 00:26:052718 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:542719 if (content.rejected) {
2720 if (channel) {
2721 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:052722 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:542723 }
2724 } else {
2725 if (!channel) {
Steve Anton69470252018-02-09 19:43:082726 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352727 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542728 } else {
Steve Anton69470252018-02-09 19:43:082729 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352730 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542731 }
2732 if (!channel) {
2733 LOG_AND_RETURN_ERROR(
2734 RTCErrorType::INTERNAL_ERROR,
2735 "Failed to create channel for mid=" + content.name);
2736 }
2737 transceiver->internal()->SetChannel(channel);
2738 }
2739 }
2740 return RTCError::OK();
2741}
2742
Steve Antonfa2260d2017-12-29 00:38:232743RTCError PeerConnection::UpdateDataChannel(
2744 cricket::ContentSource source,
2745 const cricket::ContentInfo& content,
2746 const cricket::ContentGroup* bundle_group) {
2747 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402748 // If data channels are disabled, ignore this media section. CreateAnswer
2749 // will take care of rejecting it.
2750 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232751 }
2752 if (content.rejected) {
2753 DestroyDataChannel();
2754 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:222755 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:352756 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232757 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2758 "Failed to create data channel.");
2759 }
2760 }
2761 if (source == cricket::CS_REMOTE) {
2762 const MediaContentDescription* data_desc = content.media_description();
2763 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2764 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2765 }
2766 }
2767 }
2768 return RTCError::OK();
2769}
2770
Steve Antondcc3c022017-12-23 00:02:542771RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2772PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482773 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542774 size_t mline_index,
2775 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482776 const ContentInfo* old_local_content,
2777 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542778 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482779 // If this is an offer then the m= section might be recycled. If the m=
2780 // section is being recycled (defined as: rejected in the current local or
2781 // remote description and not rejected in new description), dissociate the
2782 // currently associated RtpTransceiver by setting its mid property to null,
2783 // and discard the mapping between the transceiver and its m= section index.
2784 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2785 old_remote_content)) {
2786 // We want to dissociate the transceiver that has the rejected mid.
2787 const std::string& old_mid =
2788 (old_local_content && old_local_content->rejected)
2789 ? old_local_content->name
2790 : old_remote_content->name;
2791 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542792 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232793 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2794 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:432795 old_transceiver->internal()->set_mid(absl::nullopt);
2796 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:542797 }
2798 }
2799 const MediaContentDescription* media_desc = content.media_description();
2800 auto transceiver = GetAssociatedTransceiver(content.name);
2801 if (source == cricket::CS_LOCAL) {
2802 // Find the RtpTransceiver that corresponds to this m= section, using the
2803 // mapping between transceivers and m= section indices established when
2804 // creating the offer.
2805 if (!transceiver) {
2806 transceiver = GetTransceiverByMLineIndex(mline_index);
2807 }
2808 if (!transceiver) {
2809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2810 "Unknown transceiver");
2811 }
2812 } else {
2813 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2814 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2815 // of the same type...
2816 if (!transceiver &&
2817 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2818 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2819 }
2820 // If no RtpTransceiver was found in the previous step, create one with a
2821 // recvonly direction.
2822 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232823 RTC_LOG(LS_INFO) << "Adding "
2824 << cricket::MediaTypeToString(media_desc->type())
2825 << " transceiver for MID=" << content.name
2826 << " at i=" << mline_index
2827 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:362828 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 20:47:202829 auto sender =
2830 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 18:58:302831 std::string receiver_id;
2832 if (!media_desc->streams().empty()) {
2833 receiver_id = media_desc->streams()[0].id;
2834 } else {
2835 receiver_id = rtc::CreateRandomUuid();
2836 }
2837 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062838 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542839 transceiver->internal()->set_direction(
2840 RtpTransceiverDirection::kRecvOnly);
2841 }
2842 }
2843 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082844 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542845 LOG_AND_RETURN_ERROR(
2846 RTCErrorType::INVALID_PARAMETER,
2847 "Transceiver type does not match media description type.");
2848 }
2849 // Associate the found or created RtpTransceiver with the m= section by
2850 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2851 // section, and establish a mapping between the transceiver and the index of
2852 // the m= section.
2853 transceiver->internal()->set_mid(content.name);
2854 transceiver->internal()->set_mline_index(mline_index);
2855 return std::move(transceiver);
2856}
2857
2858rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2859PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2860 RTC_DCHECK(IsUnifiedPlan());
2861 for (auto transceiver : transceivers_) {
2862 if (transceiver->mid() == mid) {
2863 return transceiver;
2864 }
2865 }
2866 return nullptr;
2867}
2868
2869rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2870PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2871 RTC_DCHECK(IsUnifiedPlan());
2872 for (auto transceiver : transceivers_) {
2873 if (transceiver->internal()->mline_index() == mline_index) {
2874 return transceiver;
2875 }
2876 }
2877 return nullptr;
2878}
2879
2880rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2881PeerConnection::FindAvailableTransceiverToReceive(
2882 cricket::MediaType media_type) const {
2883 RTC_DCHECK(IsUnifiedPlan());
2884 // From JSEP section 5.10 (Applying a Remote Description):
2885 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2886 // the same type that were added to the PeerConnection by addTrack and are not
2887 // associated with any m= section and are not stopped, find the first such
2888 // RtpTransceiver.
2889 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082890 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542891 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2892 !transceiver->stopped()) {
2893 return transceiver;
2894 }
2895 }
2896 return nullptr;
2897}
2898
Steve Antoned10bd92017-12-05 18:52:592899const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2900 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2901 transceiver,
2902 const SessionDescriptionInterface* sdesc) const {
2903 RTC_DCHECK(transceiver);
2904 RTC_DCHECK(sdesc);
2905 if (IsUnifiedPlan()) {
2906 if (!transceiver->internal()->mid()) {
2907 // This transceiver is not associated with a media section yet.
2908 return nullptr;
2909 }
2910 return sdesc->description()->GetContentByName(
2911 *transceiver->internal()->mid());
2912 } else {
2913 // Plan B only allows at most one audio and one video section, so use the
2914 // first media section of that type.
2915 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082916 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592917 }
2918}
2919
deadbeef46c73892016-11-17 03:42:042920PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2921 return configuration_;
2922}
2923
deadbeef293e9262017-01-11 20:28:302924bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2925 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172926 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:102927 if (IsClosed()) {
2928 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2929 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2930 }
2931
Qingsi Wanga2d60672018-04-11 23:57:452932 // According to JSEP, after setLocalDescription, changing the candidate pool
2933 // size is not allowed, and changing the set of ICE servers will not result
2934 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:172935 if (local_description() && configuration.ice_candidate_pool_size !=
2936 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252937 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2938 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302939 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452940 }
Taylor Brandstettera1c30352016-05-13 15:15:112941
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:452942 if (local_description() &&
2943 configuration.use_media_transport != configuration_.use_media_transport) {
2944 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2945 "SetLocalDescription.";
2946 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2947 }
2948
2949 if (remote_description() &&
2950 configuration.use_media_transport != configuration_.use_media_transport) {
2951 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2952 "SetRemoteDescription.";
2953 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2954 }
2955
Benjamin Wright8c27cca2018-10-25 17:16:442956 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 16:07:482957 configuration.use_media_transport_for_data_channels !=
2958 configuration_.use_media_transport_for_data_channels) {
2959 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2960 "after calling SetLocalDescription.";
2961 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2962 }
2963
2964 if (remote_description() &&
2965 configuration.use_media_transport_for_data_channels !=
2966 configuration_.use_media_transport_for_data_channels) {
2967 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2968 "after calling SetRemoteDescription.";
2969 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2970 }
2971
2972 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 17:16:442973 configuration.crypto_options != configuration_.crypto_options) {
2974 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2975 "SetLocalDescription.";
2976 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2977 }
2978
Piotr (Peter) Slatala37227be2018-11-21 15:42:222979 if (configuration.use_media_transport_for_data_channels ||
2980 configuration.use_media_transport) {
2981 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
2982 << "Media transport requires MaxBundle policy.";
2983 }
2984
deadbeef293e9262017-01-11 20:28:302985 // The simplest (and most future-compatible) way to tell if the config was
2986 // modified in an invalid way is to copy each property we do support
2987 // modifying, then use operator==. There are far more properties we don't
2988 // support modifying than those we do, and more could be added.
2989 RTCConfiguration modified_config = configuration_;
2990 modified_config.servers = configuration.servers;
2991 modified_config.type = configuration.type;
2992 modified_config.ice_candidate_pool_size =
2993 configuration.ice_candidate_pool_size;
2994 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052995 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142996 modified_config.ice_check_interval_strong_connectivity =
2997 configuration.ice_check_interval_strong_connectivity;
2998 modified_config.ice_check_interval_weak_connectivity =
2999 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:573000 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3001 modified_config.ice_unwritable_min_checks =
3002 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:493003 modified_config.stun_candidate_keepalive_interval =
3004 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:403005 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:403006 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:113007 modified_config.active_reset_srtp_params =
3008 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453009 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:483010 modified_config.use_media_transport_for_data_channels =
3011 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 20:28:303012 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:253013 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:303014 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3015 }
3016
Steve Anton038834f2017-07-14 22:59:593017 // Validate the modified configuration.
3018 RTCError validate_error = ValidateConfiguration(modified_config);
3019 if (!validate_error.ok()) {
3020 return SafeSetError(std::move(validate_error), error);
3021 }
3022
deadbeef293e9262017-01-11 20:28:303023 // Note that this isn't possible through chromium, since it's an unsigned
3024 // short in WebIDL.
3025 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:173026 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:303027 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3028 }
3029
3030 // Parse ICE servers before hopping to network thread.
3031 cricket::ServerAddresses stun_servers;
3032 std::vector<cricket::RelayServerConfig> turn_servers;
3033 RTCErrorType parse_error =
3034 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3035 if (parse_error != RTCErrorType::NONE) {
3036 return SafeSetError(parse_error, error);
3037 }
Harald Alvestrand8ebba742018-05-31 12:00:343038 // Note if STUN or TURN servers were supplied.
3039 if (!stun_servers.empty()) {
3040 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3041 }
3042 if (!turn_servers.empty()) {
3043 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3044 }
deadbeef293e9262017-01-11 20:28:303045
3046 // In theory this shouldn't fail.
3047 if (!network_thread()->Invoke<bool>(
3048 RTC_FROM_HERE,
3049 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3050 stun_servers, turn_servers, modified_config.type,
3051 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:403052 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:493053 modified_config.turn_customizer,
3054 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:253055 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:303056 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3057 }
Honghai Zhang4cedf2b2016-08-31 15:18:113058
deadbeefd1a38b52016-12-10 21:15:333059 // As described in JSEP, calling setConfiguration with new ICE servers or
3060 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3061 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:303062 if (modified_config.servers != configuration_.servers ||
3063 modified_config.type != configuration_.type ||
3064 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:293065 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:333066 }
skvladd1f5fda2017-02-04 00:54:053067
Qingsi Wang9c98f0c2018-02-15 23:10:593068 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 19:57:593069 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 16:07:483070 modified_config.use_media_transport ||
3071 modified_config.use_media_transport_for_data_channels
3072 ? factory_->media_transport_factory()
3073 : nullptr);
skvladd1f5fda2017-02-04 00:54:053074
Zhi Huangb57e1692018-06-12 18:41:113075 if (configuration_.active_reset_srtp_params !=
3076 modified_config.active_reset_srtp_params) {
3077 transport_controller_->SetActiveResetSrtpParams(
3078 modified_config.active_reset_srtp_params);
3079 }
3080
deadbeef293e9262017-01-11 20:28:303081 configuration_ = modified_config;
3082 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453083}
3084
henrike@webrtc.org28e20752013-07-10 00:45:363085bool PeerConnection::AddIceCandidate(
3086 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:173087 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:253088 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:103089 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:363090 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:253091 return false;
3092 }
Steve Antond25da372017-11-06 22:50:293093
3094 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103095 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:073096 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:363097 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:293098 return false;
3099 }
3100
3101 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:103102 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:363103 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:293104 return false;
3105 }
3106
3107 bool valid = false;
3108 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3109 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:363110 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:293111 return false;
3112 }
3113
3114 // Add this candidate to the remote session description.
3115 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:103116 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:363117 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:293118 return false;
3119 }
3120
3121 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:363122 bool result = UseCandidate(ice_candidate);
3123 if (result) {
3124 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3125 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3126 } else {
3127 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3128 }
3129 return result;
Steve Antond25da372017-11-06 22:50:293130 } else {
Steve Antonc79268f2018-04-24 16:54:103131 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:363132 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:293133 return true;
3134 }
henrike@webrtc.org28e20752013-07-10 00:45:363135}
3136
Honghai Zhang7fb69db2016-03-14 18:59:183137bool PeerConnection::RemoveIceCandidates(
3138 const std::vector<cricket::Candidate>& candidates) {
3139 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:103140 if (IsClosed()) {
3141 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3142 return false;
3143 }
3144
Steve Antond25da372017-11-06 22:50:293145 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103146 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3147 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293148 return false;
3149 }
3150
3151 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103152 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293153 return false;
3154 }
3155
3156 size_t number_removed =
3157 mutable_remote_description()->RemoveCandidates(candidates);
3158 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253159 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103160 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073161 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253162 << " are removed.";
Steve Antond25da372017-11-06 22:50:293163 }
3164
3165 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353166 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3167 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103168 RTC_LOG(LS_ERROR)
3169 << "RemoveIceCandidates: Error when removing remote candidates: "
3170 << error.message();
Steve Antond25da372017-11-06 22:50:293171 }
3172 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183173}
3174
Niels Möller0c4f7be2018-05-07 12:01:373175RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023176 if (!worker_thread()->IsCurrent()) {
3177 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053178 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373179 }
3180
Niels Möller0c4f7be2018-05-07 12:01:373181 const bool has_min = bitrate.min_bitrate_bps.has_value();
3182 const bool has_start = bitrate.start_bitrate_bps.has_value();
3183 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373184 if (has_min && *bitrate.min_bitrate_bps < 0) {
3185 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3186 "min_bitrate_bps <= 0");
3187 }
Niels Möller0c4f7be2018-05-07 12:01:373188 if (has_start) {
3189 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373190 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373191 "start_bitrate_bps < min_bitrate_bps");
3192 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373193 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3194 "curent_bitrate_bps < 0");
3195 }
3196 }
3197 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053198 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373199 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373200 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373201 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3202 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3203 "max_bitrate_bps < min_bitrate_bps");
3204 } else if (*bitrate.max_bitrate_bps < 0) {
3205 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3206 "max_bitrate_bps < 0");
3207 }
3208 }
3209
zstein4b979802017-06-02 21:37:373210 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373211 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373212
3213 return RTCError::OK();
3214}
3215
Alex Narest78609d52017-10-20 08:37:473216void PeerConnection::SetBitrateAllocationStrategy(
3217 std::unique_ptr<rtc::BitrateAllocationStrategy>
3218 bitrate_allocation_strategy) {
3219 rtc::Thread* worker_thread = factory_->worker_thread();
3220 if (!worker_thread->IsCurrent()) {
3221 rtc::BitrateAllocationStrategy* strategy_raw =
3222 bitrate_allocation_strategy.release();
3223 auto functor = [this, strategy_raw]() {
3224 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 09:40:333225 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 08:37:473226 };
3227 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3228 return;
3229 }
3230 RTC_DCHECK(call_.get());
3231 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3232}
3233
henrika5f6bf242017-11-01 10:06:563234void PeerConnection::SetAudioPlayout(bool playout) {
3235 if (!worker_thread()->IsCurrent()) {
3236 worker_thread()->Invoke<void>(
3237 RTC_FROM_HERE,
3238 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3239 return;
3240 }
3241 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553242 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563243 audio_state->SetPlayout(playout);
3244}
3245
3246void PeerConnection::SetAudioRecording(bool recording) {
3247 if (!worker_thread()->IsCurrent()) {
3248 worker_thread()->Invoke<void>(
3249 RTC_FROM_HERE,
3250 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3251 return;
3252 }
3253 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 10:29:553254 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563255 audio_state->SetRecording(recording);
3256}
3257
Steve Anton8c0f7a72017-10-03 17:03:103258std::unique_ptr<rtc::SSLCertificate>
3259PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513260 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3261 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103262 return nullptr;
3263 }
Steve Antonf25303e2018-10-16 22:23:313264 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:103265}
3266
Zhi Huang70b820f2018-01-27 22:16:153267std::unique_ptr<rtc::SSLCertChain>
3268PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373269 auto audio_transceiver = GetFirstAudioTransceiver();
3270 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153271 return nullptr;
3272 }
Zhi Huang70b820f2018-01-27 22:16:153273 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373274 audio_transceiver->internal()->channel()->transport_name());
3275}
3276
3277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3278PeerConnection::GetFirstAudioTransceiver() const {
3279 for (auto transceiver : transceivers_) {
3280 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3281 return transceiver;
3282 }
3283 }
3284 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153285}
3286
ivoc14d5dbe2016-07-04 14:06:553287bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3288 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403289 // TODO(eladalon): It would be better to not allow negative values into PC.
3290 const size_t max_size = (max_size_bytes < 0)
3291 ? RtcEventLog::kUnlimitedOutput
3292 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 14:43:013293 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3294 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3295 output_period_ms = 5000;
3296 }
Elad Alon99c3fe52017-10-13 14:29:403297 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333298 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 14:43:013299 output_period_ms);
Elad Alon99c3fe52017-10-13 14:29:403300}
3301
Bjorn Tereliusde939432017-11-20 16:38:143302bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3303 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063304 // TODO(eladalon): In C++14, this can be done with a lambda.
3305 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143306 bool operator()() {
3307 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3308 }
Karl Wibergd6b48192017-10-16 21:01:063309 PeerConnection* const pc;
3310 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143311 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403312 };
Bjorn Tereliusde939432017-11-20 16:38:143313 return worker_thread()->Invoke<bool>(
3314 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553315}
3316
3317void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023318 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553319 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3320}
3321
Harald Alvestrandad88c882018-11-28 15:47:463322rtc::scoped_refptr<DtlsTransportInterface>
3323PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3324 return transport_controller_->LookupDtlsTransportByMid(mid);
3325}
3326
henrike@webrtc.org28e20752013-07-10 00:45:363327const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173328 return pending_local_description_ ? pending_local_description_.get()
3329 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363330}
3331
3332const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173333 return pending_remote_description_ ? pending_remote_description_.get()
3334 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363335}
3336
deadbeeffe4a8a42016-12-21 01:56:173337const SessionDescriptionInterface* PeerConnection::current_local_description()
3338 const {
Steve Anton75737c02017-11-06 18:37:173339 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173340}
3341
3342const SessionDescriptionInterface* PeerConnection::current_remote_description()
3343 const {
Steve Anton75737c02017-11-06 18:37:173344 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173345}
3346
3347const SessionDescriptionInterface* PeerConnection::pending_local_description()
3348 const {
Steve Anton75737c02017-11-06 18:37:173349 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173350}
3351
3352const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3353 const {
Steve Anton75737c02017-11-06 18:37:173354 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173355}
3356
henrike@webrtc.org28e20752013-07-10 00:45:363357void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173358 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363359 // Update stats here so that we have the most recent stats for tracks and
3360 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263361 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363362
Steve Anton75737c02017-11-06 18:37:173363 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343364 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083365
Steve Anton8af21862017-12-15 19:20:133366 for (auto transceiver : transceivers_) {
3367 transceiver->Stop();
3368 }
Steve Anton25cfeb92018-04-26 18:44:003369
3370 // Ensure that all asynchronous stats requests are completed before destroying
3371 // the transport controller below.
3372 if (stats_collector_) {
3373 stats_collector_->WaitForPendingRequest();
3374 }
3375
3376 // Don't destroy BaseChannels until after stats has been cleaned up so that
3377 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133378 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173379
Qingsi Wang93a84392018-01-31 01:13:093380 // The event log is used in the transport controller, which must be outlived
3381 // by the former. CreateOffer by the peer connection is implemented
3382 // asynchronously and if the peer connection is closed without resetting the
3383 // WebRTC session description factory, the session description factory would
3384 // call the transport controller.
3385 webrtc_session_desc_factory_.reset();
3386 transport_controller_.reset();
3387
deadbeef42a42632017-03-10 23:18:003388 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053389 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3390 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023391
Steve Anton978b8762017-09-29 19:15:023392 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153393 call_.reset();
3394 // The event log must outlive call (and any other object that uses it).
3395 event_log_.reset();
3396 });
Harald Alvestrand8ebba742018-05-31 12:00:343397 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163398 // The .h file says that observer can be discarded after close() returns.
3399 // Make sure this is true.
3400 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:363401}
3402
Steve Antonad182762018-09-05 20:22:403403void PeerConnection::OnMessage(rtc::Message* msg) {
3404 switch (msg->message_id) {
3405 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3406 SetSessionDescriptionMsg* param =
3407 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3408 param->observer->OnSuccess();
3409 delete param;
3410 break;
3411 }
3412 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3413 SetSessionDescriptionMsg* param =
3414 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3415 param->observer->OnFailure(std::move(param->error));
3416 delete param;
3417 break;
3418 }
3419 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3420 CreateSessionDescriptionMsg* param =
3421 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3422 param->observer->OnFailure(std::move(param->error));
3423 delete param;
3424 break;
3425 }
3426 case MSG_GETSTATS: {
3427 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3428 StatsReports reports;
3429 stats_->GetStats(param->track, &reports);
3430 param->observer->OnComplete(reports);
3431 delete param;
3432 break;
3433 }
3434 case MSG_FREE_DATACHANNELS: {
3435 sctp_data_channels_to_free_.clear();
3436 break;
3437 }
3438 case MSG_REPORT_USAGE_PATTERN: {
3439 ReportUsagePattern();
3440 break;
3441 }
3442 default:
3443 RTC_NOTREACHED() << "Not implemented";
3444 break;
3445 }
3446}
3447
Steve Antonafb0bb72018-02-20 19:35:373448cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3449 RTC_DCHECK(!IsUnifiedPlan());
3450 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3451 GetAudioTransceiver()->internal()->channel());
3452 if (voice_channel) {
3453 return voice_channel->media_channel();
3454 } else {
3455 return nullptr;
3456 }
3457}
3458
3459cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3460 RTC_DCHECK(!IsUnifiedPlan());
3461 auto* video_channel = static_cast<cricket::VideoChannel*>(
3462 GetVideoTransceiver()->internal()->channel());
3463 if (video_channel) {
3464 return video_channel->media_channel();
3465 } else {
3466 return nullptr;
3467 }
3468}
3469
Steve Anton4171afb2017-11-20 18:20:223470void PeerConnection::CreateAudioReceiver(
3471 MediaStreamInterface* stream,
3472 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513473 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3474 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533475 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3476 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023477 auto* audio_receiver = new AudioRtpReceiver(
3478 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053479 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023480 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3481 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3482 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223483 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163484 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343485 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363486}
3487
Steve Anton4171afb2017-11-20 18:20:223488void PeerConnection::CreateVideoReceiver(
3489 MediaStreamInterface* stream,
3490 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513491 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3492 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533493 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3494 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023495 auto* video_receiver = new VideoRtpReceiver(
3496 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053497 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023498 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3499 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3500 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223501 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163502 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343503 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363504}
3505
deadbeef70ab1a12015-09-28 23:53:553506// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3507// description.
Henrik Boström933d8b02017-10-10 17:05:163508rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223509 const RtpSenderInfo& remote_sender_info) {
3510 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3511 if (!receiver) {
3512 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3513 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163514 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553515 }
Steve Anton4171afb2017-11-20 18:20:223516 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3517 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3518 } else {
3519 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3520 }
Henrik Boström933d8b02017-10-10 17:05:163521 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363522}
3523
korniltsev.anatolyec390b52017-07-25 00:00:253524void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3525 MediaStreamInterface* stream) {
3526 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363527 RTC_DCHECK(track);
3528 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253529 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223530 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253531 // We already have a sender for this track, so just change the stream_id
3532 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363533 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253534 return;
3535 }
3536
3537 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363538 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203539 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053540 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223541 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253542 // If the sender has already been configured in SDP, we call SetSsrc,
3543 // which will connect the sender to the underlying transport. This can
3544 // occur if a local session description that contains the ID of the sender
3545 // is set before AddStream is called. It can also occur if the local
3546 // session description is not changed and RemoveStream is called, and
3547 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223548 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183549 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223550 if (sender_info) {
3551 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253552 }
3553}
3554
3555// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3556// indefinitely, when we have unified plan SDP.
3557void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3558 MediaStreamInterface* stream) {
3559 RTC_DCHECK(!IsClosed());
3560 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223561 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253562 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3563 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253564 return;
3565 }
Steve Anton4171afb2017-11-20 18:20:223566 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253567}
3568
3569void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3570 MediaStreamInterface* stream) {
3571 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363572 RTC_DCHECK(track);
3573 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253574 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223575 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253576 // We already have a sender for this track, so just change the stream_id
3577 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363578 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253579 return;
3580 }
3581
3582 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363583 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203584 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053585 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223586 GetVideoTransceiver()->internal()->AddSender(new_sender);
3587 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183588 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223589 if (sender_info) {
3590 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253591 }
3592}
3593
3594void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3595 MediaStreamInterface* stream) {
3596 RTC_DCHECK(!IsClosed());
3597 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223598 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253599 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3600 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253601 return;
3602 }
Steve Anton4171afb2017-11-20 18:20:223603 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253604}
3605
Steve Antonba818672017-11-06 18:21:573606void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283607 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573608 if (ice_connection_state_ == new_state) {
3609 return;
3610 }
3611
deadbeefcbecd352015-09-23 18:50:273612 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573613 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113614 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273615 return;
3616 }
Steve Antonba818672017-11-06 18:21:573617
Mirko Bonadei675513b2017-11-09 10:09:253618 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3619 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573620 RTC_DCHECK(ice_connection_state_ !=
3621 PeerConnectionInterface::kIceConnectionClosed);
3622
henrike@webrtc.org28e20752013-07-10 00:45:363623 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163624 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363625}
3626
Alex Loiko9289eda2018-11-23 16:18:593627void PeerConnection::SetStandardizedIceConnectionState(
3628 PeerConnectionInterface::IceConnectionState new_state) {
3629 RTC_DCHECK(signaling_thread()->IsCurrent());
3630 if (standardized_ice_connection_state_ == new_state)
3631 return;
3632 if (IsClosed())
3633 return;
3634 standardized_ice_connection_state_ = new_state;
3635 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3636 // the old one once disconnects are handled properly.
3637}
3638
Jonas Olsson635474e2018-10-18 13:58:173639void PeerConnection::SetConnectionState(
3640 PeerConnectionInterface::PeerConnectionState new_state) {
3641 RTC_DCHECK(signaling_thread()->IsCurrent());
3642 if (connection_state_ == new_state)
3643 return;
3644 if (IsClosed())
3645 return;
3646 connection_state_ = new_state;
3647 Observer()->OnConnectionChange(new_state);
3648}
3649
henrike@webrtc.org28e20752013-07-10 00:45:363650void PeerConnection::OnIceGatheringChange(
3651 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283652 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363653 if (IsClosed()) {
3654 return;
3655 }
3656 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163657 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363658}
3659
jbauch81bf7b02017-03-25 15:31:123660void PeerConnection::OnIceCandidate(
3661 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283662 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253663 if (IsClosed()) {
3664 return;
3665 }
Harald Alvestrand8ebba742018-05-31 12:00:343666 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:583667 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3668 candidate->candidate().address().IsPrivateIP()) {
3669 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3670 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163671 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363672}
3673
Honghai Zhang7fb69db2016-03-14 18:59:183674void PeerConnection::OnIceCandidatesRemoved(
3675 const std::vector<cricket::Candidate>& candidates) {
3676 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253677 if (IsClosed()) {
3678 return;
3679 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163680 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:183681}
3682
henrike@webrtc.org28e20752013-07-10 00:45:363683void PeerConnection::ChangeSignalingState(
3684 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573685 RTC_DCHECK(signaling_thread()->IsCurrent());
3686 if (signaling_state_ == signaling_state) {
3687 return;
3688 }
Mirko Bonadei675513b2017-11-09 10:09:253689 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3690 << GetSignalingStateString(signaling_state_)
3691 << " New state: "
3692 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363693 signaling_state_ = signaling_state;
3694 if (signaling_state == kClosed) {
3695 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:163696 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:593697 standardized_ice_connection_state_ =
3698 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:173699 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3700 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363701 if (ice_gathering_state_ != kIceGatheringComplete) {
3702 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:163703 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363704 }
3705 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163706 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363707}
3708
deadbeefeb459812015-12-16 03:24:433709void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3710 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253711 if (IsClosed()) {
3712 return;
3713 }
korniltsev.anatolyec390b52017-07-25 00:00:253714 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163715 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433716}
3717
deadbeefeb459812015-12-16 03:24:433718void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3719 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253720 if (IsClosed()) {
3721 return;
3722 }
korniltsev.anatolyec390b52017-07-25 00:00:253723 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163724 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433725}
3726
3727void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3728 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253729 if (IsClosed()) {
3730 return;
3731 }
korniltsev.anatolyec390b52017-07-25 00:00:253732 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163733 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433734}
3735
3736void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3737 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253738 if (IsClosed()) {
3739 return;
3740 }
korniltsev.anatolyec390b52017-07-25 00:00:253741 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163742 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433743}
3744
Henrik Boström31638672017-11-23 16:48:323745void PeerConnection::PostSetSessionDescriptionSuccess(
3746 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:403747 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3748 signaling_thread()->Post(RTC_FROM_HERE, this,
3749 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:323750}
3751
deadbeefab9b2d12015-10-14 18:33:113752void PeerConnection::PostSetSessionDescriptionFailure(
3753 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:403754 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:033755 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403756 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3757 msg->error = std::move(error);
3758 signaling_thread()->Post(RTC_FROM_HERE, this,
3759 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113760}
3761
3762void PeerConnection::PostCreateSessionDescriptionFailure(
3763 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033764 RTCError error) {
3765 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403766 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3767 msg->error = std::move(error);
3768 signaling_thread()->Post(RTC_FROM_HERE, this,
3769 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113770}
3771
zhihuang1c378ed2017-08-17 21:10:503772void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543773 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113774 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543775 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503776
Steve Antondcc3c022017-12-23 00:02:543777 if (IsUnifiedPlan()) {
3778 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3779 } else {
3780 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3781 }
3782
Steve Antonfa2260d2017-12-29 00:38:233783 // Intentionally unset the data channel type for RTP data channel with the
3784 // second condition. Otherwise the RTP data channels would be successfully
3785 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3786 // when building with chromium. We want to leave RTP data channels broken, so
3787 // people won't try to use them.
3788 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3789 session_options->data_channel_type = data_channel_type();
3790 }
3791
Steve Antondcc3c022017-12-23 00:02:543792 // Apply ICE restart flag and renomination flag.
3793 for (auto& options : session_options->media_description_options) {
3794 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3795 options.transport_options.enable_ice_renomination =
3796 configuration_.enable_ice_renomination;
3797 }
3798
3799 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:443800 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 20:22:163801 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 05:47:123802 session_options->pooled_ice_credentials =
3803 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3804 RTC_FROM_HERE,
3805 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3806 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 09:25:483807 session_options->offer_extmap_allow_mixed =
3808 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-23 00:02:543809}
3810
3811void PeerConnection::GetOptionsForPlanBOffer(
3812 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3813 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503814 // Figure out transceiver directional preferences.
3815 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3816 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3817
3818 // By default, generate sendrecv/recvonly m= sections.
3819 bool recv_audio = true;
3820 bool recv_video = true;
3821
3822 // By default, only offer a new m= section if we have media to send with it.
3823 bool offer_new_audio_description = send_audio;
3824 bool offer_new_video_description = send_video;
3825 bool offer_new_data_description = HasDataChannels();
3826
3827 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543828 if (offer_answer_options.offer_to_receive_audio !=
3829 RTCOfferAnswerOptions::kUndefined) {
3830 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503831 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543832 offer_new_audio_description ||
3833 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503834 }
Steve Antondcc3c022017-12-23 00:02:543835 if (offer_answer_options.offer_to_receive_video !=
3836 RTCOfferAnswerOptions::kUndefined) {
3837 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503838 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543839 offer_new_video_description ||
3840 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503841 }
3842
Danil Chapovalov66cadcc2018-06-19 14:47:433843 absl::optional<size_t> audio_index;
3844 absl::optional<size_t> video_index;
3845 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:503846 // If a current description exists, generate m= sections in the same order,
3847 // using the first audio/video/data section that appears and rejecting
3848 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173849 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503850 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173851 local_description(),
Steve Anton1d03a752017-11-27 22:30:093852 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3853 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3854 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113855 }
3856
zhihuang1c378ed2017-08-17 21:10:503857 // Add audio/video/data m= sections to the end if needed.
3858 if (!audio_index && offer_new_audio_description) {
3859 session_options->media_description_options.push_back(
3860 cricket::MediaDescriptionOptions(
3861 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093862 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3863 false));
Oskar Sundbom9b28a032017-11-16 09:53:303864 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453865 }
zhihuang1c378ed2017-08-17 21:10:503866 if (!video_index && offer_new_video_description) {
3867 session_options->media_description_options.push_back(
3868 cricket::MediaDescriptionOptions(
3869 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093870 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3871 false));
Oskar Sundbom9b28a032017-11-16 09:53:303872 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453873 }
zhihuang1c378ed2017-08-17 21:10:503874 if (!data_index && offer_new_data_description) {
3875 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233876 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303877 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503878 }
3879
3880 cricket::MediaDescriptionOptions* audio_media_description_options =
3881 !audio_index ? nullptr
3882 : &session_options->media_description_options[*audio_index];
3883 cricket::MediaDescriptionOptions* video_media_description_options =
3884 !video_index ? nullptr
3885 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503886
Steve Anton4171afb2017-11-20 18:20:223887 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:373888 video_media_description_options,
3889 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:543890}
3891
3892// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3893// and return a reference to it.
3894// Generated MIDs should be no more than 3 bytes long to take up less space in
3895// the RTP packet.
3896static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3897 RTC_DCHECK(used_mids);
3898 // We're boring: just generate MIDs 0, 1, 2, ...
3899 size_t i = 0;
3900 std::set<std::string>::iterator it;
3901 bool inserted;
3902 do {
3903 std::string mid = rtc::ToString(i++);
3904 auto insert_result = used_mids->insert(mid);
3905 it = insert_result.first;
3906 inserted = insert_result.second;
3907 } while (!inserted);
3908 return *it;
3909}
3910
3911static cricket::MediaDescriptionOptions
3912GetMediaDescriptionOptionsForTransceiver(
3913 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3914 transceiver,
3915 const std::string& mid) {
3916 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083917 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543918 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303919 // This behavior is specified in JSEP. The gist is that:
3920 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3921 // sendrecv.
3922 // 2. If the MSID is included, then it must be included in any subsequent
3923 // offer/answer exactly the same until the RtpTransceiver is stopped.
3924 if (!transceiver->stopped() &&
3925 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3926 transceiver->internal()->has_ever_been_used_to_send())) {
3927 cricket::SenderOptions sender_options;
3928 sender_options.track_id = transceiver->sender()->id();
3929 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 20:47:203930 int num_send_encoding_layers =
3931 transceiver->sender()->init_send_encodings().size();
3932 sender_options.num_sim_layers =
3933 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 18:58:303934 media_description_options.sender_options.push_back(sender_options);
3935 }
Steve Antondcc3c022017-12-23 00:02:543936 return media_description_options;
3937}
3938
3939void PeerConnection::GetOptionsForUnifiedPlanOffer(
3940 const RTCOfferAnswerOptions& offer_answer_options,
3941 cricket::MediaSessionOptions* session_options) {
3942 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3943 // Offers) and 5.2.2 (Subsequent Offers).
3944 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3945 const ContentInfos& local_contents =
3946 (local_description() ? local_description()->description()->contents()
3947 : ContentInfos());
3948 const ContentInfos& remote_contents =
3949 (remote_description() ? remote_description()->description()->contents()
3950 : ContentInfos());
3951 // The mline indices that can be recycled. New transceivers should reuse these
3952 // slots first.
3953 std::queue<size_t> recycleable_mline_indices;
3954 // Track the MIDs used in previous offer/answer exchanges and the current
3955 // offer so that new, unique MIDs are generated.
3956 std::set<std::string> used_mids = seen_mids_;
3957 // First, go through each media section that exists in either the local or
3958 // remote description and generate a media section in this offer for the
3959 // associated transceiver. If a media section can be recycled, generate a
3960 // default, rejected media section here that can be later overwritten.
3961 for (size_t i = 0;
3962 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3963 // Either |local_content| or |remote_content| is non-null.
3964 const ContentInfo* local_content =
3965 (i < local_contents.size() ? &local_contents[i] : nullptr);
3966 const ContentInfo* remote_content =
3967 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3968 bool had_been_rejected = (local_content && local_content->rejected) ||
3969 (remote_content && remote_content->rejected);
3970 const std::string& mid =
3971 (local_content ? local_content->name : remote_content->name);
3972 cricket::MediaType media_type =
3973 (local_content ? local_content->media_description()->type()
3974 : remote_content->media_description()->type());
3975 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3976 media_type == cricket::MEDIA_TYPE_VIDEO) {
3977 auto transceiver = GetAssociatedTransceiver(mid);
3978 RTC_CHECK(transceiver);
3979 // A media section is considered eligible for recycling if it is marked as
3980 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483981 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543982 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083983 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3984 RtpTransceiverDirection::kInactive,
3985 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543986 recycleable_mline_indices.push(i);
3987 } else {
3988 session_options->media_description_options.push_back(
3989 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3990 // CreateOffer shouldn't really cause any state changes in
3991 // PeerConnection, but we need a way to match new transceivers to new
3992 // media sections in SetLocalDescription and JSEP specifies this is done
3993 // by recording the index of the media section generated for the
3994 // transceiver in the offer.
3995 transceiver->internal()->set_mline_index(i);
3996 }
3997 } else {
3998 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233999 RTC_CHECK(GetDataMid());
4000 if (had_been_rejected || mid != *GetDataMid()) {
4001 session_options->media_description_options.push_back(
4002 GetMediaDescriptionOptionsForRejectedData(mid));
4003 } else {
4004 session_options->media_description_options.push_back(
4005 GetMediaDescriptionOptionsForActiveData(mid));
4006 }
Steve Antondcc3c022017-12-23 00:02:544007 }
4008 }
4009 // Next, look for transceivers that are newly added (that is, are not stopped
4010 // and not associated). Reuse media sections marked as recyclable first,
4011 // otherwise append to the end of the offer. New media sections should be
4012 // added in the order they were added to the PeerConnection.
4013 for (auto transceiver : transceivers_) {
4014 if (transceiver->mid() || transceiver->stopped()) {
4015 continue;
4016 }
4017 size_t mline_index;
4018 if (!recycleable_mline_indices.empty()) {
4019 mline_index = recycleable_mline_indices.front();
4020 recycleable_mline_indices.pop();
4021 session_options->media_description_options[mline_index] =
4022 GetMediaDescriptionOptionsForTransceiver(transceiver,
4023 AllocateMid(&used_mids));
4024 } else {
4025 mline_index = session_options->media_description_options.size();
4026 session_options->media_description_options.push_back(
4027 GetMediaDescriptionOptionsForTransceiver(transceiver,
4028 AllocateMid(&used_mids)));
4029 }
4030 // See comment above for why CreateOffer changes the transceiver's state.
4031 transceiver->internal()->set_mline_index(mline_index);
4032 }
Steve Antonfa2260d2017-12-29 00:38:234033 // Lastly, add a m-section if we have local data channels and an m section
4034 // does not already exist.
4035 if (!GetDataMid() && HasDataChannels()) {
4036 session_options->media_description_options.push_back(
4037 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4038 }
Steve Antondcc3c022017-12-23 00:02:544039}
4040
4041void PeerConnection::GetOptionsForAnswer(
4042 const RTCOfferAnswerOptions& offer_answer_options,
4043 cricket::MediaSessionOptions* session_options) {
4044 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4045
4046 if (IsUnifiedPlan()) {
4047 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4048 } else {
4049 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4050 }
4051
Steve Antonfa2260d2017-12-29 00:38:234052 // Intentionally unset the data channel type for RTP data channel. Otherwise
4053 // the RTP data channels would be successfully negotiated by default and the
4054 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4055 // We want to leave RTP data channels broken, so people won't try to use them.
4056 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4057 session_options->data_channel_type = data_channel_type();
4058 }
4059
Steve Antondcc3c022017-12-23 00:02:544060 // Apply ICE renomination flag.
4061 for (auto& options : session_options->media_description_options) {
4062 options.transport_options.enable_ice_renomination =
4063 configuration_.enable_ice_renomination;
4064 }
zhihuang8f65cdf2016-05-07 01:40:304065
4066 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444067 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 20:22:164068 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 05:47:124069 session_options->pooled_ice_credentials =
4070 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4071 RTC_FROM_HERE,
4072 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4073 port_allocator_.get()));
deadbeefab9b2d12015-10-14 18:33:114074}
4075
Steve Antondcc3c022017-12-23 00:02:544076void PeerConnection::GetOptionsForPlanBAnswer(
4077 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:114078 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504079 // Figure out transceiver directional preferences.
4080 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4081 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4082
4083 // By default, generate sendrecv/recvonly m= sections. The direction is also
4084 // restricted by the direction in the offer.
4085 bool recv_audio = true;
4086 bool recv_video = true;
4087
4088 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:544089 if (offer_answer_options.offer_to_receive_audio !=
4090 RTCOfferAnswerOptions::kUndefined) {
4091 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:524092 }
Steve Antondcc3c022017-12-23 00:02:544093 if (offer_answer_options.offer_to_receive_video !=
4094 RTCOfferAnswerOptions::kUndefined) {
4095 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:504096 }
4097
Danil Chapovalov66cadcc2018-06-19 14:47:434098 absl::optional<size_t> audio_index;
4099 absl::optional<size_t> video_index;
4100 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:294101
4102 // Generate m= sections that match those in the offer.
4103 // Note that mediasession.cc will handle intersection our preferred
4104 // direction with the offered direction.
4105 GenerateMediaDescriptionOptions(
4106 remote_description(),
4107 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4108 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4109 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:504110
4111 cricket::MediaDescriptionOptions* audio_media_description_options =
4112 !audio_index ? nullptr
4113 : &session_options->media_description_options[*audio_index];
4114 cricket::MediaDescriptionOptions* video_media_description_options =
4115 !video_index ? nullptr
4116 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:504117
Steve Anton4171afb2017-11-20 18:20:224118 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:374119 video_media_description_options,
4120 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544121}
zhihuangaf388472016-11-02 23:49:484122
Steve Antondcc3c022017-12-23 00:02:544123void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4124 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4125 cricket::MediaSessionOptions* session_options) {
4126 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4127 // Answers) and 5.3.2 (Subsequent Answers).
4128 RTC_DCHECK(remote_description());
4129 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4130 for (const ContentInfo& content :
4131 remote_description()->description()->contents()) {
4132 cricket::MediaType media_type = content.media_description()->type();
4133 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4134 media_type == cricket::MEDIA_TYPE_VIDEO) {
4135 auto transceiver = GetAssociatedTransceiver(content.name);
4136 RTC_CHECK(transceiver);
4137 session_options->media_description_options.push_back(
4138 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4139 } else {
4140 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:404141 // Reject all data sections if data channels are disabled.
4142 // Reject a data section if it has already been rejected.
4143 // Reject all data sections except for the first one.
4144 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4145 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:234146 session_options->media_description_options.push_back(
4147 GetMediaDescriptionOptionsForRejectedData(content.name));
4148 } else {
4149 session_options->media_description_options.push_back(
4150 GetMediaDescriptionOptionsForActiveData(content.name));
4151 }
Steve Antondcc3c022017-12-23 00:02:544152 }
4153 }
htaa2a49d92016-03-04 10:51:394154}
4155
zhihuang1c378ed2017-08-17 21:10:504156void PeerConnection::GenerateMediaDescriptionOptions(
4157 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:094158 RtpTransceiverDirection audio_direction,
4159 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:434160 absl::optional<size_t>* audio_index,
4161 absl::optional<size_t>* video_index,
4162 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:394163 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504164 for (const cricket::ContentInfo& content :
4165 session_desc->description()->contents()) {
4166 if (IsAudioContent(&content)) {
4167 // If we already have an audio m= section, reject this extra one.
4168 if (*audio_index) {
4169 session_options->media_description_options.push_back(
4170 cricket::MediaDescriptionOptions(
4171 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:094172 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504173 } else {
4174 session_options->media_description_options.push_back(
4175 cricket::MediaDescriptionOptions(
4176 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:094177 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304178 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504179 }
4180 } else if (IsVideoContent(&content)) {
4181 // If we already have an video m= section, reject this extra one.
4182 if (*video_index) {
4183 session_options->media_description_options.push_back(
4184 cricket::MediaDescriptionOptions(
4185 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:094186 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504187 } else {
4188 session_options->media_description_options.push_back(
4189 cricket::MediaDescriptionOptions(
4190 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:094191 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304192 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504193 }
4194 } else {
4195 RTC_DCHECK(IsDataContent(&content));
4196 // If we already have an data m= section, reject this extra one.
4197 if (*data_index) {
4198 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234199 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504200 } else {
4201 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234202 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304203 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504204 }
4205 }
htaa2a49d92016-03-04 10:51:394206 }
deadbeefab9b2d12015-10-14 18:33:114207}
4208
Steve Antonfa2260d2017-12-29 00:38:234209cricket::MediaDescriptionOptions
4210PeerConnection::GetMediaDescriptionOptionsForActiveData(
4211 const std::string& mid) const {
4212 // Direction for data sections is meaningless, but legacy endpoints might
4213 // expect sendrecv.
4214 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4215 RtpTransceiverDirection::kSendRecv,
4216 /*stopped=*/false);
4217 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4218 return options;
4219}
4220
4221cricket::MediaDescriptionOptions
4222PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4223 const std::string& mid) const {
4224 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4225 RtpTransceiverDirection::kInactive,
4226 /*stopped=*/true);
4227 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4228 return options;
4229}
4230
Danil Chapovalov66cadcc2018-06-19 14:47:434231absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234232 switch (data_channel_type_) {
4233 case cricket::DCT_RTP:
4234 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434235 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234236 }
4237 return rtp_data_channel_->content_name();
4238 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354239 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 19:23:224240 case cricket::DCT_MEDIA_TRANSPORT:
4241 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-29 00:38:234242 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434243 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234244 }
4245}
4246
Steve Anton4171afb2017-11-20 18:20:224247void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4248 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4249 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404250 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074251}
4252
Steve Anton4171afb2017-11-20 18:20:224253void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114254 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224255 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114256 cricket::MediaType media_type,
4257 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364258 RTC_DCHECK(!IsUnifiedPlan());
4259
Steve Anton4171afb2017-11-20 18:20:224260 std::vector<RtpSenderInfo>* current_senders =
4261 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114262
Steve Anton4171afb2017-11-20 18:20:224263 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014264 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224265 for (auto sender_it = current_senders->begin();
4266 sender_it != current_senders->end();
4267 /* incremented manually */) {
4268 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114269 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224270 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094271 std::string params_stream_id;
4272 if (params) {
4273 params_stream_id =
4274 (!params->first_stream_id().empty() ? params->first_stream_id()
4275 : kDefaultStreamId);
4276 }
Seth Hampson5b4f0752018-04-02 23:31:364277 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094278 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404279 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104280 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224281 sender_exists) {
4282 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404283 } else {
Steve Anton4171afb2017-11-20 18:20:224284 OnRemoteSenderRemoved(info, media_type);
4285 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114286 }
4287 }
4288
Steve Anton4171afb2017-11-20 18:20:224289 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114290 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334291 if (!params.has_ssrcs()) {
4292 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4293 // sender, this means it is coming from a Unified Plan endpoint,so we just
4294 // create a default.
4295 default_sender_needed = true;
4296 break;
4297 }
4298
Seth Hampson845e8782018-03-02 19:34:104299 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364300 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334301 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4302 // not supported in Plan B, we just take the first here and create the
4303 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104304 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094305 (!params.first_stream_id().empty() ? params.first_stream_id()
4306 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224307 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114308 uint32_t ssrc = params.first_ssrc();
4309
4310 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104311 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114312 if (!stream) {
4313 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194314 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104315 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114316 remote_streams_->AddStream(stream);
4317 new_streams->AddStream(stream);
4318 }
4319
Steve Anton4171afb2017-11-20 18:20:224320 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184321 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224322 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104323 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224324 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114325 }
4326 }
deadbeefbda7e0b2015-12-09 01:13:404327
Steve Anton4171afb2017-11-20 18:20:224328 // Add default sender if necessary.
4329 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404330 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104331 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404332 if (!default_stream) {
4333 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194334 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104335 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404336 remote_streams_->AddStream(default_stream);
4337 new_streams->AddStream(default_stream);
4338 }
Steve Anton4171afb2017-11-20 18:20:224339 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4340 ? kDefaultAudioSenderId
4341 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104342 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184343 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224344 if (!default_sender_info) {
4345 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104346 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224347 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404348 }
4349 }
deadbeefab9b2d12015-10-14 18:33:114350}
4351
Steve Anton4171afb2017-11-20 18:20:224352void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4353 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234354 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4355 << " receiver for track_id=" << sender_info.sender_id
4356 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114357
Steve Anton3d954a62018-04-02 18:27:234358 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114359 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224360 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114361 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224362 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114363 } else {
nisseeb4ca4e2017-01-12 10:24:274364 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114365 }
4366}
4367
Steve Anton4171afb2017-11-20 18:20:224368void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4369 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094370 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4371 << " receiver for track_id=" << sender_info.sender_id
4372 << " and stream_id=" << sender_info.stream_id;
4373
Seth Hampson845e8782018-03-02 19:34:104374 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114375
Henrik Boström933d8b02017-10-10 17:05:164376 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114377 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194378 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4379 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224380 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114381 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224382 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114383 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114384 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114385 }
4386 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194387 // Stopping or destroying a VideoRtpReceiver will end the
4388 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224389 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114390 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224391 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114392 if (video_track) {
perkjd61bf802016-03-24 10:16:194393 // There's no guarantee the track is still available, e.g. the track may
4394 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114395 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114396 }
4397 } else {
nisseede5da42017-01-12 13:15:364398 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114399 }
Henrik Boström933d8b02017-10-10 17:05:164400 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164401 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164402 }
deadbeefab9b2d12015-10-14 18:33:114403}
4404
4405void PeerConnection::UpdateEndedRemoteMediaStreams() {
4406 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4407 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4408 MediaStreamInterface* stream = remote_streams_->at(i);
4409 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4410 streams_to_remove.push_back(stream);
4411 }
4412 }
4413
Taylor Brandstetter98cde262016-05-31 20:02:214414 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114415 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164416 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114417 }
4418}
4419
Steve Anton4171afb2017-11-20 18:20:224420void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114421 const std::vector<cricket::StreamParams>& streams,
4422 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224423 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114424
Seth Hampson845e8782018-03-02 19:34:104425 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114426 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224427 for (auto sender_it = current_senders->begin();
4428 sender_it != current_senders->end();
4429 /* incremented manually */) {
4430 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114431 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224432 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4433 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104434 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224435 OnLocalSenderRemoved(info, media_type);
4436 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114437 } else {
Steve Anton4171afb2017-11-20 18:20:224438 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114439 }
4440 }
4441
Steve Anton4171afb2017-11-20 18:20:224442 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114443 for (const cricket::StreamParams& params : streams) {
4444 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224445 // sender id.
Seth Hampson845e8782018-03-02 19:34:104446 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224447 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114448 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224449 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184450 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224451 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104452 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224453 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114454 }
4455 }
4456}
4457
Steve Anton4171afb2017-11-20 18:20:224458void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4459 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364460 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224461 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014462 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224463 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4464 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254465 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114466 return;
4467 }
4468
deadbeeffac06552015-11-25 19:26:014469 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254470 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074471 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014472 return;
deadbeefab9b2d12015-10-14 18:33:114473 }
deadbeeffac06552015-11-25 19:26:014474
Seth Hampson5b4f0752018-04-02 23:31:364475 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224476 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114477}
4478
Steve Anton4171afb2017-11-20 18:20:224479void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4480 cricket::MediaType media_type) {
4481 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014482 if (!sender) {
4483 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114484 // SessionDescriptions has been renegotiated.
4485 return;
4486 }
deadbeeffac06552015-11-25 19:26:014487
4488 // A sender has been removed from the SessionDescription but it's still
4489 // associated with the PeerConnection. This only occurs if the SDP doesn't
4490 // match with the calls to CreateSender, AddStream and RemoveStream.
4491 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254492 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074493 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014494 return;
deadbeefab9b2d12015-10-14 18:33:114495 }
deadbeeffac06552015-11-25 19:26:014496
Steve Anton4171afb2017-11-20 18:20:224497 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114498}
4499
4500void PeerConnection::UpdateLocalRtpDataChannels(
4501 const cricket::StreamParamsVec& streams) {
4502 std::vector<std::string> existing_channels;
4503
4504 // Find new and active data channels.
4505 for (const cricket::StreamParams& params : streams) {
4506 // |it->sync_label| is actually the data channel label. The reason is that
4507 // we use the same naming of data channels as we do for
4508 // MediaStreams and Tracks.
4509 // For MediaStreams, the sync_label is the MediaStream label and the
4510 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104511 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114512 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564513 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254514 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114515 continue;
4516 }
4517 // Set the SSRC the data channel should use for sending.
4518 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4519 existing_channels.push_back(data_channel_it->first);
4520 }
4521
4522 UpdateClosingRtpDataChannels(existing_channels, true);
4523}
4524
4525void PeerConnection::UpdateRemoteRtpDataChannels(
4526 const cricket::StreamParamsVec& streams) {
4527 std::vector<std::string> existing_channels;
4528
4529 // Find new and active data channels.
4530 for (const cricket::StreamParams& params : streams) {
4531 // The data channel label is either the mslabel or the SSRC if the mslabel
4532 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104533 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114534 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104535 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114536 auto data_channel_it = rtp_data_channels_.find(label);
4537 if (data_channel_it == rtp_data_channels_.end()) {
4538 // This is a new data channel.
4539 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4540 } else {
4541 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4542 }
4543 existing_channels.push_back(label);
4544 }
4545
4546 UpdateClosingRtpDataChannels(existing_channels, false);
4547}
4548
4549void PeerConnection::UpdateClosingRtpDataChannels(
4550 const std::vector<std::string>& active_channels,
4551 bool is_local_update) {
4552 auto it = rtp_data_channels_.begin();
4553 while (it != rtp_data_channels_.end()) {
4554 DataChannel* data_channel = it->second;
4555 if (std::find(active_channels.begin(), active_channels.end(),
4556 data_channel->label()) != active_channels.end()) {
4557 ++it;
4558 continue;
4559 }
4560
4561 if (is_local_update) {
4562 data_channel->SetSendSsrc(0);
4563 } else {
4564 data_channel->RemotePeerRequestClose();
4565 }
4566
4567 if (data_channel->state() == DataChannel::kClosed) {
4568 rtp_data_channels_.erase(it);
4569 it = rtp_data_channels_.begin();
4570 } else {
4571 ++it;
4572 }
4573 }
4574}
4575
4576void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4577 uint32_t remote_ssrc) {
4578 rtc::scoped_refptr<DataChannel> channel(
4579 InternalCreateDataChannel(label, nullptr));
4580 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254581 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074582 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114583 return;
4584 }
4585 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394586 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4587 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164588 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114589}
4590
4591rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4592 const std::string& label,
4593 const InternalDataChannelInit* config) {
4594 if (IsClosed()) {
4595 return nullptr;
4596 }
Steve Anton75737c02017-11-06 18:37:174597 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254598 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114599 << "InternalCreateDataChannel: Data is not supported in this call.";
4600 return nullptr;
4601 }
4602 InternalDataChannelInit new_config =
4603 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 19:23:224604 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 18:33:114605 if (new_config.id < 0) {
4606 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174607 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114608 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254609 RTC_LOG(LS_ERROR)
4610 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114611 return nullptr;
4612 }
4613 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254614 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074615 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114616 return nullptr;
4617 }
4618 }
4619
Steve Anton75737c02017-11-06 18:37:174620 rtc::scoped_refptr<DataChannel> channel(
4621 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114622 if (!channel) {
4623 sid_allocator_.ReleaseSid(new_config.id);
4624 return nullptr;
4625 }
4626
4627 if (channel->data_channel_type() == cricket::DCT_RTP) {
4628 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254629 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4630 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114631 return nullptr;
4632 }
4633 rtp_data_channels_[channel->label()] = channel;
4634 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:224635 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 18:33:114636 sctp_data_channels_.push_back(channel);
4637 channel->SignalClosed.connect(this,
4638 &PeerConnection::OnSctpDataChannelClosed);
4639 }
4640
Steve Anton2d8609c2018-01-24 00:38:464641 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114642 return channel;
4643}
4644
4645bool PeerConnection::HasDataChannels() const {
4646 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4647}
4648
4649void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4650 for (const auto& channel : sctp_data_channels_) {
4651 if (channel->id() < 0) {
4652 int sid;
4653 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254654 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114655 continue;
4656 }
4657 channel->SetSctpSid(sid);
4658 }
4659 }
4660}
4661
4662void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294663 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114664 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4665 ++it) {
4666 if (it->get() == channel) {
4667 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:324668 // After the closing procedure is done, it's safe to use this ID for
4669 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114670 sid_allocator_.ReleaseSid(channel->id());
4671 }
deadbeefbd292462015-12-15 02:15:294672 // Since this method is triggered by a signal from the DataChannel,
4673 // we can't free it directly here; we need to free it asynchronously.
4674 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114675 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:404676 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4677 nullptr);
deadbeefab9b2d12015-10-14 18:33:114678 return;
4679 }
4680 }
4681}
4682
deadbeefab9b2d12015-10-14 18:33:114683void PeerConnection::OnDataChannelDestroyed() {
4684 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4685 // DataChannel may callback to us and try to modify the list.
4686 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4687 temp_rtp_dcs.swap(rtp_data_channels_);
4688 for (const auto& kv : temp_rtp_dcs) {
4689 kv.second->OnTransportChannelDestroyed();
4690 }
4691
4692 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4693 temp_sctp_dcs.swap(sctp_data_channels_);
4694 for (const auto& channel : temp_sctp_dcs) {
4695 channel->OnTransportChannelDestroyed();
4696 }
4697}
4698
4699void PeerConnection::OnDataChannelOpenMessage(
4700 const std::string& label,
4701 const InternalDataChannelInit& config) {
4702 rtc::scoped_refptr<DataChannel> channel(
4703 InternalCreateDataChannel(label, &config));
4704 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254705 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114706 return;
4707 }
4708
deadbeefa601f5c2016-06-06 21:27:394709 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4710 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164711 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:414712 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:114713}
4714
Bjorn Mellem175aa2e2018-11-08 19:23:224715bool PeerConnection::HandleOpenMessage_s(
4716 const cricket::ReceiveDataParams& params,
4717 const rtc::CopyOnWriteBuffer& buffer) {
4718 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4719 // Received OPEN message; parse and signal that a new data channel should
4720 // be created.
4721 std::string label;
4722 InternalDataChannelInit config;
4723 config.id = params.ssrc;
4724 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4725 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4726 << params.ssrc;
4727 return true;
4728 }
4729 config.open_handshake_role = InternalDataChannelInit::kAcker;
4730 OnDataChannelOpenMessage(label, config);
4731 return true;
4732 }
4733 return false;
4734}
4735
Steve Anton4171afb2017-11-20 18:20:224736rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4737PeerConnection::GetAudioTransceiver() const {
4738 // This method only works with Plan B SDP, where there is a single
4739 // audio/video transceiver.
4740 RTC_DCHECK(!IsUnifiedPlan());
4741 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084742 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224743 return transceiver;
4744 }
4745 }
4746 RTC_NOTREACHED();
4747 return nullptr;
4748}
4749
4750rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4751PeerConnection::GetVideoTransceiver() const {
4752 // This method only works with Plan B SDP, where there is a single
4753 // audio/video transceiver.
4754 RTC_DCHECK(!IsUnifiedPlan());
4755 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084756 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224757 return transceiver;
4758 }
4759 }
4760 RTC_NOTREACHED();
4761 return nullptr;
4762}
4763
4764// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4765// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504766bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224767 switch (type) {
4768 case cricket::MEDIA_TYPE_AUDIO:
4769 return !GetAudioTransceiver()->internal()->senders().empty();
4770 case cricket::MEDIA_TYPE_VIDEO:
4771 return !GetVideoTransceiver()->internal()->senders().empty();
4772 case cricket::MEDIA_TYPE_DATA:
4773 return false;
4774 }
4775 RTC_NOTREACHED();
4776 return false;
zhihuang1c378ed2017-08-17 21:10:504777}
4778
Steve Anton4171afb2017-11-20 18:20:224779rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4780PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4781 for (auto transceiver : transceivers_) {
4782 for (auto sender : transceiver->internal()->senders()) {
4783 if (sender->track() == track) {
4784 return sender;
4785 }
4786 }
4787 }
4788 return nullptr;
deadbeeffac06552015-11-25 19:26:014789}
4790
Steve Anton4171afb2017-11-20 18:20:224791rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4792PeerConnection::FindSenderById(const std::string& sender_id) const {
4793 for (auto transceiver : transceivers_) {
4794 for (auto sender : transceiver->internal()->senders()) {
4795 if (sender->id() == sender_id) {
4796 return sender;
4797 }
4798 }
4799 }
4800 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554801}
4802
Steve Anton4171afb2017-11-20 18:20:224803rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4804PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4805 for (auto transceiver : transceivers_) {
4806 for (auto receiver : transceiver->internal()->receivers()) {
4807 if (receiver->id() == receiver_id) {
4808 return receiver;
4809 }
4810 }
4811 }
4812 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554813}
4814
Steve Anton4171afb2017-11-20 18:20:224815std::vector<PeerConnection::RtpSenderInfo>*
4816PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4817 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4818 media_type == cricket::MEDIA_TYPE_VIDEO);
4819 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4820 ? &remote_audio_sender_infos_
4821 : &remote_video_sender_infos_;
4822}
4823
4824std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114825 cricket::MediaType media_type) {
4826 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4827 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224828 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4829 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114830}
4831
Steve Anton4171afb2017-11-20 18:20:224832const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4833 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184834 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224835 const std::string sender_id) const {
4836 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184837 if (sender_info.stream_id == stream_id &&
4838 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224839 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114840 }
4841 }
4842 return nullptr;
4843}
4844
4845DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4846 for (const auto& channel : sctp_data_channels_) {
4847 if (channel->id() == sid) {
4848 return channel;
4849 }
4850 }
4851 return nullptr;
4852}
4853
deadbeef91dd5672016-05-18 23:55:304854bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:074855 const cricket::ServerAddresses& stun_servers,
4856 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:114857 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-28 00:20:154858 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114859 // To handle both internal and externally created port allocator, we will
4860 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454861 port_allocator_flags_ = port_allocator_->flags();
4862 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4863 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4864 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114865 // If the disable-IPv6 flag was specified, we'll not override it
4866 // by experiment.
4867 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454868 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474869 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4870 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454871 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114872 }
4873
zhihuangb09b3f92017-03-07 22:40:514874 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:454875 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254876 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514877 }
4878
Taylor Brandstettera1c30352016-05-13 15:15:114879 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:454880 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254881 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114882 }
4883
honghaiz60347052016-06-01 01:29:124884 if (configuration.candidate_network_policy ==
4885 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:454886 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254887 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124888 }
4889
Daniel Lazarenko2870b0a2018-01-25 09:30:224890 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:454891 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224892 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4893 }
4894
Qingsi Wanga2d60672018-04-11 23:57:454895 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:114896 // No step delay is used while allocating ports.
4897 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4898 port_allocator_->set_candidate_filter(
4899 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114900 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114901
Harald Alvestrandb2a74782018-06-28 11:54:074902 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:264903 for (auto& turn_server : turn_servers_copy) {
4904 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:254905 }
Taylor Brandstettera1c30352016-05-13 15:15:114906 // Call this last since it may create pooled allocator sessions using the
4907 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494908 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264909 stun_servers, std::move(turn_servers_copy),
4910 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4911 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:494912 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114913 return true;
4914}
4915
deadbeef91dd5672016-05-18 23:55:304916bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304917 const cricket::ServerAddresses& stun_servers,
4918 const std::vector<cricket::RelayServerConfig>& turn_servers,
4919 IceTransportsType type,
4920 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404921 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494922 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 14:47:434923 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114924 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304925 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:454926 // According to JSEP, after setLocalDescription, changing the candidate pool
4927 // size is not allowed, and changing the set of ICE servers will not result
4928 // in new candidates being gathered.
4929 if (local_description()) {
4930 port_allocator_->FreezeCandidatePool();
4931 }
Benjamin Wright6f80f092018-08-14 00:06:264932 // Add the custom tls turn servers if they exist.
4933 auto turn_servers_copy = turn_servers;
4934 for (auto& turn_server : turn_servers_copy) {
4935 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4936 }
Taylor Brandstettera1c30352016-05-13 15:15:114937 // Call this last since it may create pooled allocator sessions using the
4938 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324939 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264940 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4941 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114942}
4943
Steve Antonba818672017-11-06 18:21:574944cricket::ChannelManager* PeerConnection::channel_manager() const {
4945 return factory_->channel_manager();
4946}
4947
Elad Alon99c3fe52017-10-13 14:29:404948bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144949 std::unique_ptr<RtcEventLogOutput> output,
4950 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164951 if (!event_log_) {
4952 return false;
4953 }
Bjorn Tereliusde939432017-11-20 16:38:144954 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554955}
4956
4957void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164958 if (event_log_) {
4959 event_log_->StopLogging();
4960 }
ivoc14d5dbe2016-07-04 14:06:554961}
nisseeaabdf62017-05-05 09:23:024962
Amit Hilbuchdd9390c2018-11-14 00:26:054963cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:174964 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544965 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:054966 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:544967 if (channel && channel->content_name() == content_name) {
4968 return channel;
4969 }
Steve Anton75737c02017-11-06 18:37:174970 }
4971 if (rtp_data_channel() &&
4972 rtp_data_channel()->content_name() == content_name) {
4973 return rtp_data_channel();
4974 }
4975 return nullptr;
4976}
4977
4978bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 19:23:224979 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174980 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254981 RTC_LOG(LS_INFO)
4982 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074983 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174984 return false;
4985 }
Bjorn Mellem175aa2e2018-11-08 19:23:224986 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254987 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074988 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174989 return false;
4990 }
4991
Bjorn Mellem175aa2e2018-11-08 19:23:224992 absl::optional<rtc::SSLRole> dtls_role;
4993 if (sctp_mid_) {
4994 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4995 } else if (is_caller_) {
4996 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
4997 }
Zhi Huange830e682018-03-30 17:48:354998 if (dtls_role) {
4999 *role = *dtls_role;
5000 return true;
5001 }
5002 return false;
Steve Anton75737c02017-11-06 18:37:175003}
5004
5005bool PeerConnection::GetSslRole(const std::string& content_name,
5006 rtc::SSLRole* role) {
5007 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255008 RTC_LOG(LS_INFO)
5009 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075010 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:175011 return false;
5012 }
5013
Zhi Huange830e682018-03-30 17:48:355014 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5015 if (dtls_role) {
5016 *role = *dtls_role;
5017 return true;
5018 }
5019 return false;
Steve Anton75737c02017-11-06 18:37:175020}
5021
Steve Antonf8470812017-12-04 18:46:215022void PeerConnection::SetSessionError(SessionError error,
5023 const std::string& error_desc) {
5024 RTC_DCHECK_RUN_ON(signaling_thread());
5025 if (error != session_error_) {
5026 session_error_ = error;
5027 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:175028 }
5029}
5030
Zhi Huange830e682018-03-30 17:48:355031RTCError PeerConnection::UpdateSessionState(
5032 SdpType type,
5033 cricket::ContentSource source,
5034 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:565035 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175036
5037 // If there's already a pending error then no state transition should happen.
5038 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:215039 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:475040
Steve Anton6d6a2ae2017-12-05 01:19:475041 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:515042 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:595043 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:475044 }
5045
5046 // Update the signaling state according to the specified state machine (see
5047 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:515048 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:475049 ChangeSignalingState(source == cricket::CS_LOCAL
5050 ? PeerConnectionInterface::kHaveLocalOffer
5051 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:515052 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:475053 ChangeSignalingState(source == cricket::CS_LOCAL
5054 ? PeerConnectionInterface::kHaveLocalPrAnswer
5055 : PeerConnectionInterface::kHaveRemotePrAnswer);
5056 } else {
Steve Anton3828c062017-12-06 18:34:515057 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:475058 ChangeSignalingState(PeerConnectionInterface::kStable);
5059 }
5060
5061 // Update internal objects according to the session description's media
5062 // descriptions.
Zhi Huange830e682018-03-30 17:48:355063 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:475064 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:425065 return error;
Steve Anton6d6a2ae2017-12-05 01:19:475066 }
5067
Steve Anton8a006912017-12-04 23:25:565068 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175069}
5070
Steve Anton8a006912017-12-04 23:25:565071RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:515072 SdpType type,
Steve Anton8a006912017-12-04 23:25:565073 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:595074 const SessionDescriptionInterface* sdesc =
5075 (source == cricket::CS_LOCAL ? local_description()
5076 : remote_description());
Steve Anton75737c02017-11-06 18:37:175077 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:595078
5079 // Push down the new SDP media section for each audio/video transceiver.
5080 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:175081 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:595082 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:055083 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595084 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:175085 continue;
5086 }
5087 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:305088 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:595089 if (!content_desc) {
5090 continue;
5091 }
5092 std::string error;
Yves Gerey665174f2018-06-19 13:03:055093 bool success = (source == cricket::CS_LOCAL)
5094 ? channel->SetLocalContent(content_desc, type, &error)
5095 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595096 if (!success) {
5097 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5098 }
5099 }
5100
5101 // If using the RtpDataChannel, push down the new SDP section for it too.
5102 if (rtp_data_channel_) {
5103 const ContentInfo* data_content =
5104 cricket::GetFirstDataContent(sdesc->description());
5105 if (data_content && !data_content->rejected) {
5106 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:305107 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:595108 if (data_desc) {
5109 std::string error;
5110 bool success =
5111 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:515112 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:055113 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595114 if (!success) {
5115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5116 std::move(error));
5117 }
Steve Anton75737c02017-11-06 18:37:175118 }
5119 }
5120 }
Steve Antoned10bd92017-12-05 18:52:595121
Steve Anton75737c02017-11-06 18:37:175122 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5123 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5124 if (sctp_transport_ && local_description() && remote_description() &&
5125 cricket::GetFirstDataContent(local_description()->description()) &&
5126 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:565127 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:175128 RTC_FROM_HERE,
5129 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:565130 if (!success) {
5131 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5132 "Failed to push down SCTP parameters.");
5133 }
Steve Anton75737c02017-11-06 18:37:175134 }
Steve Antoned10bd92017-12-05 18:52:595135
Steve Anton8a006912017-12-04 23:25:565136 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175137}
5138
5139bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5140 RTC_DCHECK(network_thread()->IsCurrent());
5141 RTC_DCHECK(local_description());
5142 RTC_DCHECK(remote_description());
5143 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5144 // When we support "max-message-size", that would also be pushed down here.
5145 return sctp_transport_->Start(
5146 GetSctpPort(local_description()->description()),
5147 GetSctpPort(remote_description()->description()));
5148}
5149
Steve Anton8a006912017-12-04 23:25:565150RTCError PeerConnection::PushdownTransportDescription(
5151 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:515152 SdpType type) {
Steve Anton8a006912017-12-04 23:25:565153 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175154
Zhi Huange830e682018-03-30 17:48:355155 if (source == cricket::CS_LOCAL) {
5156 const SessionDescriptionInterface* sdesc = local_description();
5157 RTC_DCHECK(sdesc);
5158 return transport_controller_->SetLocalDescription(type,
5159 sdesc->description());
5160 } else {
5161 const SessionDescriptionInterface* sdesc = remote_description();
5162 RTC_DCHECK(sdesc);
5163 return transport_controller_->SetRemoteDescription(type,
5164 sdesc->description());
Steve Anton75737c02017-11-06 18:37:175165 }
Steve Anton75737c02017-11-06 18:37:175166}
5167
5168bool PeerConnection::GetTransportDescription(
5169 const SessionDescription* description,
5170 const std::string& content_name,
5171 cricket::TransportDescription* tdesc) {
5172 if (!description || !tdesc) {
5173 return false;
5174 }
5175 const TransportInfo* transport_info =
5176 description->GetTransportInfoByName(content_name);
5177 if (!transport_info) {
5178 return false;
5179 }
5180 *tdesc = transport_info->description;
5181 return true;
5182}
5183
Steve Anton75737c02017-11-06 18:37:175184cricket::IceConfig PeerConnection::ParseIceConfig(
5185 const PeerConnectionInterface::RTCConfiguration& config) const {
5186 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:175187 switch (config.continual_gathering_policy) {
5188 case PeerConnectionInterface::GATHER_ONCE:
5189 gathering_policy = cricket::GATHER_ONCE;
5190 break;
5191 case PeerConnectionInterface::GATHER_CONTINUALLY:
5192 gathering_policy = cricket::GATHER_CONTINUALLY;
5193 break;
5194 default:
5195 RTC_NOTREACHED();
5196 gathering_policy = cricket::GATHER_ONCE;
5197 }
Qingsi Wang9a5c6f82018-02-01 18:38:405198
Steve Anton75737c02017-11-06 18:37:175199 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235200 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5201 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175202 ice_config.prioritize_most_likely_candidate_pairs =
5203 config.prioritize_most_likely_ice_candidate_pairs;
5204 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:235205 RTCConfigurationToIceConfigOptionalInt(
5206 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175207 ice_config.continual_gathering_policy = gathering_policy;
5208 ice_config.presume_writable_when_fully_relayed =
5209 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:145210 ice_config.ice_check_interval_strong_connectivity =
5211 config.ice_check_interval_strong_connectivity;
5212 ice_config.ice_check_interval_weak_connectivity =
5213 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:175214 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-30 07:08:515215 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5216 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:495217 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175218 ice_config.regather_all_networks_interval_range =
5219 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405220 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175221 return ice_config;
5222}
5223
Steve Antona41959e2018-11-28 19:15:335224static absl::string_view GetTrackIdBySsrc(
5225 const SessionDescriptionInterface* session_description,
5226 uint32_t ssrc) {
5227 if (!session_description) {
5228 return {};
Steve Anton75737c02017-11-06 18:37:175229 }
Steve Antona41959e2018-11-28 19:15:335230 for (const cricket::ContentInfo& content :
5231 session_description->description()->contents()) {
5232 const cricket::MediaContentDescription& media =
5233 *content.media_description();
5234 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5235 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5236 const cricket::StreamParams* stream_params =
5237 cricket::GetStreamBySsrc(media.streams(), ssrc);
5238 if (stream_params) {
5239 return stream_params->id;
5240 }
5241 }
5242 }
5243 return {};
Steve Anton75737c02017-11-06 18:37:175244}
5245
Steve Antona41959e2018-11-28 19:15:335246absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5247 return GetTrackIdBySsrc(local_description(), ssrc);
5248}
5249
5250absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5251 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 18:37:175252}
5253
5254bool PeerConnection::SendData(const cricket::SendDataParams& params,
5255 const rtc::CopyOnWriteBuffer& payload,
5256 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 19:23:225257 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5258 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5259 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175260 return false;
5261 }
Bjorn Mellem175aa2e2018-11-08 19:23:225262 if (media_transport_) {
5263 SendDataParams send_params;
5264 send_params.type = ToWebrtcDataMessageType(params.type);
5265 send_params.ordered = params.ordered;
5266 if (params.max_rtx_count >= 0) {
5267 send_params.max_rtx_count = params.max_rtx_count;
5268 } else if (params.max_rtx_ms >= 0) {
5269 send_params.max_rtx_ms = params.max_rtx_ms;
5270 }
5271 return media_transport_->SendData(params.sid, send_params, payload).ok();
5272 }
Steve Anton75737c02017-11-06 18:37:175273 return rtp_data_channel_
5274 ? rtp_data_channel_->SendData(params, payload, result)
5275 : network_thread()->Invoke<bool>(
5276 RTC_FROM_HERE,
5277 Bind(&cricket::SctpTransportInternal::SendData,
5278 sctp_transport_.get(), params, payload, result));
5279}
5280
5281bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225282 RTC_DCHECK_RUN_ON(signaling_thread());
5283 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 18:37:175284 // Don't log an error here, because DataChannels are expected to call
5285 // ConnectDataChannel in this state. It's the only way to initially tell
5286 // whether or not the underlying transport is ready.
5287 return false;
5288 }
Bjorn Mellem175aa2e2018-11-08 19:23:225289 if (media_transport_) {
5290 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5291 &DataChannel::OnChannelReady);
5292 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5293 &DataChannel::OnDataReceived);
5294 SignalMediaTransportChannelClosing_s.connect(
5295 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5296 SignalMediaTransportChannelClosed_s.connect(
5297 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5298 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175299 rtp_data_channel_->SignalReadyToSendData.connect(
5300 webrtc_data_channel, &DataChannel::OnChannelReady);
5301 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5302 &DataChannel::OnDataReceived);
5303 } else {
5304 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5305 &DataChannel::OnChannelReady);
5306 SignalSctpDataReceived.connect(webrtc_data_channel,
5307 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325308 SignalSctpClosingProcedureStartedRemotely.connect(
5309 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5310 SignalSctpClosingProcedureComplete.connect(
5311 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175312 }
5313 return true;
5314}
5315
5316void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225317 RTC_DCHECK_RUN_ON(signaling_thread());
5318 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255319 RTC_LOG(LS_ERROR)
5320 << "DisconnectDataChannel called when rtp_data_channel_ and "
5321 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175322 return;
5323 }
Bjorn Mellem175aa2e2018-11-08 19:23:225324 if (media_transport_) {
5325 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5326 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5327 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5328 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5329 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175330 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5331 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5332 } else {
5333 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5334 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325335 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5336 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175337 }
5338}
5339
5340void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225341 if (media_transport_) {
5342 // No-op. Media transport does not need to add streams.
5343 return;
5344 }
Steve Anton75737c02017-11-06 18:37:175345 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255346 RTC_LOG(LS_ERROR)
5347 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175348 return;
5349 }
5350 network_thread()->Invoke<void>(
5351 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5352 sctp_transport_.get(), sid));
5353}
5354
5355void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225356 if (media_transport_) {
5357 media_transport_->CloseChannel(sid);
5358 return;
5359 }
Steve Anton75737c02017-11-06 18:37:175360 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255361 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075362 "NULL.";
Steve Anton75737c02017-11-06 18:37:175363 return;
5364 }
5365 network_thread()->Invoke<void>(
5366 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5367 sctp_transport_.get(), sid));
5368}
5369
5370bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 19:23:225371 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175372 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 19:23:225373 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 18:37:175374 sctp_ready_to_send_data_;
5375}
5376
Bjorn Mellem175aa2e2018-11-08 19:23:225377void PeerConnection::OnDataReceived(int channel_id,
5378 DataMessageType type,
5379 const rtc::CopyOnWriteBuffer& buffer) {
5380 cricket::ReceiveDataParams params;
5381 params.sid = channel_id;
5382 params.type = ToCricketDataMessageType(type);
5383 media_transport_invoker_->AsyncInvoke<void>(
5384 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5385 RTC_DCHECK_RUN_ON(signaling_thread());
5386 if (!HandleOpenMessage_s(params, buffer)) {
5387 SignalMediaTransportReceivedData_s(params, buffer);
5388 }
5389 });
5390}
5391
5392void PeerConnection::OnChannelClosing(int channel_id) {
5393 media_transport_invoker_->AsyncInvoke<void>(
5394 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5395 RTC_DCHECK_RUN_ON(signaling_thread());
5396 SignalMediaTransportChannelClosing_s(channel_id);
5397 });
5398}
5399
5400void PeerConnection::OnChannelClosed(int channel_id) {
5401 media_transport_invoker_->AsyncInvoke<void>(
5402 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5403 RTC_DCHECK_RUN_ON(signaling_thread());
5404 SignalMediaTransportChannelClosed_s(channel_id);
5405 });
5406}
5407
Danil Chapovalov66cadcc2018-06-19 14:47:435408absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 17:48:355409 if (sctp_mid_ && transport_controller_) {
5410 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5411 if (dtls_transport) {
5412 return dtls_transport->transport_name();
5413 }
Danil Chapovalov66cadcc2018-06-19 14:47:435414 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355415 }
Danil Chapovalov66cadcc2018-06-19 14:47:435416 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355417}
5418
Qingsi Wang72a43a12018-02-21 00:03:185419cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5420 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455421 network_thread()->Invoke<void>(
5422 RTC_FROM_HERE,
5423 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5424 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185425 return candidate_states_list;
5426}
5427
Steve Anton5dfde182018-02-06 18:34:405428std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5429 const {
5430 std::map<std::string, std::string> transport_names_by_mid;
5431 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055432 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:405433 if (channel) {
5434 transport_names_by_mid[channel->content_name()] =
5435 channel->transport_name();
5436 }
Steve Anton75737c02017-11-06 18:37:175437 }
Steve Anton5dfde182018-02-06 18:34:405438 if (rtp_data_channel_) {
5439 transport_names_by_mid[rtp_data_channel_->content_name()] =
5440 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175441 }
5442 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435443 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355444 RTC_DCHECK(transport_name);
5445 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175446 }
Steve Anton5dfde182018-02-06 18:34:405447 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175448}
5449
Steve Anton5dfde182018-02-06 18:34:405450std::map<std::string, cricket::TransportStats>
5451PeerConnection::GetTransportStatsByNames(
5452 const std::set<std::string>& transport_names) {
5453 if (!network_thread()->IsCurrent()) {
5454 return network_thread()
5455 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5456 RTC_FROM_HERE,
5457 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175458 }
Steve Anton5dfde182018-02-06 18:34:405459 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5460 for (const std::string& transport_name : transport_names) {
5461 cricket::TransportStats transport_stats;
5462 bool success =
5463 transport_controller_->GetStats(transport_name, &transport_stats);
5464 if (success) {
5465 transport_stats_by_name[transport_name] = std::move(transport_stats);
5466 } else {
5467 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5468 << transport_name;
5469 }
5470 }
5471 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175472}
5473
5474bool PeerConnection::GetLocalCertificate(
5475 const std::string& transport_name,
5476 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355477 if (!certificate) {
5478 return false;
5479 }
5480 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5481 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175482}
5483
Taylor Brandstetterc3928662018-02-23 21:04:515484std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175485 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515486 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175487}
5488
5489cricket::DataChannelType PeerConnection::data_channel_type() const {
5490 return data_channel_type_;
5491}
5492
5493bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5494 return pending_ice_restarts_.find(content_name) !=
5495 pending_ice_restarts_.end();
5496}
5497
Steve Anton75737c02017-11-06 18:37:175498bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5499 return transport_controller_->NeedsIceRestart(content_name);
5500}
5501
5502void PeerConnection::OnCertificateReady(
5503 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5504 transport_controller_->SetLocalCertificate(certificate);
5505}
5506
5507void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215508 SetSessionError(SessionError::kTransport,
5509 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175510}
5511
Alex Loiko9289eda2018-11-23 16:18:595512void PeerConnection::OnTransportControllerConnectionState(
5513 cricket::IceConnectionState state) {
5514 switch (state) {
5515 case cricket::kIceConnectionConnecting:
5516 // If the current state is Connected or Completed, then there were
5517 // writable channels but now there are not, so the next state must
5518 // be Disconnected.
5519 // kIceConnectionConnecting is currently used as the default,
5520 // un-connected state by the TransportController, so its only use is
5521 // detecting disconnections.
5522 if (ice_connection_state_ ==
5523 PeerConnectionInterface::kIceConnectionConnected ||
5524 ice_connection_state_ ==
5525 PeerConnectionInterface::kIceConnectionCompleted) {
5526 SetIceConnectionState(
5527 PeerConnectionInterface::kIceConnectionDisconnected);
5528 }
5529 break;
5530 case cricket::kIceConnectionFailed:
5531 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5532 break;
5533 case cricket::kIceConnectionConnected:
5534 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5535 "all transports are writable.";
5536 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5537 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5538 break;
5539 case cricket::kIceConnectionCompleted:
5540 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5541 "all transports are complete.";
5542 if (ice_connection_state_ !=
5543 PeerConnectionInterface::kIceConnectionConnected) {
5544 // If jumping directly from "checking" to "connected",
5545 // signal "connected" first.
5546 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5547 }
5548 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5549 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5550 ReportTransportStats();
5551 break;
5552 default:
5553 RTC_NOTREACHED();
5554 }
5555}
5556
Steve Anton75737c02017-11-06 18:37:175557void PeerConnection::OnTransportControllerCandidatesGathered(
5558 const std::string& transport_name,
5559 const cricket::Candidates& candidates) {
5560 RTC_DCHECK(signaling_thread()->IsCurrent());
5561 int sdp_mline_index;
5562 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255563 RTC_LOG(LS_ERROR)
5564 << "OnTransportControllerCandidatesGathered: content name "
5565 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175566 return;
5567 }
5568
5569 for (cricket::Candidates::const_iterator citer = candidates.begin();
5570 citer != candidates.end(); ++citer) {
5571 // Use transport_name as the candidate media id.
5572 std::unique_ptr<JsepIceCandidate> candidate(
5573 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5574 if (local_description()) {
5575 mutable_local_description()->AddCandidate(candidate.get());
5576 }
5577 OnIceCandidate(std::move(candidate));
5578 }
5579}
5580
5581void PeerConnection::OnTransportControllerCandidatesRemoved(
5582 const std::vector<cricket::Candidate>& candidates) {
5583 RTC_DCHECK(signaling_thread()->IsCurrent());
5584 // Sanity check.
5585 for (const cricket::Candidate& candidate : candidates) {
5586 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255587 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075588 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255589 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175590 return;
5591 }
5592 }
5593
5594 if (local_description()) {
5595 mutable_local_description()->RemoveCandidates(candidates);
5596 }
5597 OnIceCandidatesRemoved(candidates);
5598}
5599
5600void PeerConnection::OnTransportControllerDtlsHandshakeError(
5601 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:535602 RTC_HISTOGRAM_ENUMERATION(
5603 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5604 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:175605}
5606
Steve Antoned10bd92017-12-05 18:52:595607void PeerConnection::EnableSending() {
5608 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055609 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595610 if (channel && !channel->enabled()) {
5611 channel->Enable(true);
5612 }
Steve Anton75737c02017-11-06 18:37:175613 }
5614
Steve Anton4171afb2017-11-20 18:20:225615 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175616 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225617 }
Steve Anton75737c02017-11-06 18:37:175618}
5619
5620// Returns the media index for a local ice candidate given the content name.
5621bool PeerConnection::GetLocalCandidateMediaIndex(
5622 const std::string& content_name,
5623 int* sdp_mline_index) {
5624 if (!local_description() || !sdp_mline_index) {
5625 return false;
5626 }
5627
5628 bool content_found = false;
5629 const ContentInfos& contents = local_description()->description()->contents();
5630 for (size_t index = 0; index < contents.size(); ++index) {
5631 if (contents[index].name == content_name) {
5632 *sdp_mline_index = static_cast<int>(index);
5633 content_found = true;
5634 break;
5635 }
5636 }
5637 return content_found;
5638}
5639
5640bool PeerConnection::UseCandidatesInSessionDescription(
5641 const SessionDescriptionInterface* remote_desc) {
5642 if (!remote_desc) {
5643 return true;
5644 }
5645 bool ret = true;
5646
5647 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5648 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5649 for (size_t n = 0; n < candidates->count(); ++n) {
5650 const IceCandidateInterface* candidate = candidates->at(n);
5651 bool valid = false;
5652 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5653 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255654 RTC_LOG(LS_INFO)
5655 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075656 "candidate.";
Steve Anton75737c02017-11-06 18:37:175657 }
5658 continue;
5659 }
5660 ret = UseCandidate(candidate);
5661 if (!ret) {
5662 break;
5663 }
5664 }
5665 }
5666 return ret;
5667}
5668
5669bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5670 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5671 size_t remote_content_size =
5672 remote_description()->description()->contents().size();
5673 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255674 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175675 return false;
5676 }
5677
5678 cricket::ContentInfo content =
5679 remote_description()->description()->contents()[mediacontent_index];
5680 std::vector<cricket::Candidate> candidates;
5681 candidates.push_back(candidate->candidate());
5682 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355683 RTCError error =
5684 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505685 if (error.ok()) {
5686 // Candidates successfully submitted for checking.
5687 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5688 ice_connection_state_ ==
5689 PeerConnectionInterface::kIceConnectionDisconnected) {
5690 // If state is New, then the session has just gotten its first remote ICE
5691 // candidates, so go to Checking.
5692 // If state is Disconnected, the session is re-using old candidates or
5693 // receiving additional ones, so go to Checking.
5694 // If state is Connected, stay Connected.
5695 // TODO(bemasc): If state is Connected, and the new candidates are for a
5696 // newly added transport, then the state actually _should_ move to
5697 // checking. Add a way to distinguish that case.
5698 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5699 }
5700 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:075701 } else {
Zhi Huange830e682018-03-30 17:48:355702 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175703 }
5704 return true;
5705}
5706
5707void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175708 // Destroy video channel first since it may have a pointer to the
5709 // voice channel.
5710 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295711 if (!video_info || video_info->rejected) {
5712 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175713 }
5714
Steve Anton6fec8802017-12-04 18:37:295715 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5716 if (!audio_info || audio_info->rejected) {
5717 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175718 }
5719
5720 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5721 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295722 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175723 }
5724}
5725
Steve Antondcc3c022017-12-23 00:02:545726RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5727 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175728 const cricket::ContentGroup* bundle_group = nullptr;
5729 if (configuration_.bundle_policy ==
5730 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545731 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175732 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565733 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5734 "max-bundle configured but session description "
5735 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175736 }
5737 }
Steve Antondcc3c022017-12-23 00:02:545738 return std::move(bundle_group);
5739}
5740
5741RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355742 // Creating the media channels. Transports should already have been created
5743 // at this point.
Steve Antondcc3c022017-12-23 00:02:545744 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555745 if (voice && !voice->rejected &&
5746 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355747 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555748 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565749 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5750 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555751 }
5752 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5753 }
5754
Steve Antondcc3c022017-12-23 00:02:545755 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555756 if (video && !video->rejected &&
5757 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355758 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555759 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565760 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5761 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175762 }
Steve Antoneda6ccd2017-12-04 18:21:555763 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175764 }
5765
Steve Antondcc3c022017-12-23 00:02:545766 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175767 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 19:23:225768 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:355769 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565770 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5771 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175772 }
5773 }
5774
Steve Anton8a006912017-12-04 23:25:565775 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175776}
5777
Steve Anton4171afb2017-11-20 18:20:225778// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555779cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355780 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425781 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 16:07:485782 MediaTransportInterface* media_transport = nullptr;
5783 if (configuration_.use_media_transport) {
5784 media_transport = GetMediaTransport(mid);
5785 }
Anton Sukhanov98a462c2018-10-17 20:15:425786
Steve Anton75737c02017-11-06 18:37:175787 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 20:15:425788 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445789 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5790 audio_options_);
Steve Anton75737c02017-11-06 18:37:175791 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555792 return nullptr;
Steve Anton75737c02017-11-06 18:37:175793 }
Steve Anton75737c02017-11-06 18:37:175794 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5795 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175796 voice_channel->SignalSentPacket.connect(this,
5797 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355798 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225799
Steve Antoneda6ccd2017-12-04 18:21:555800 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175801}
5802
Steve Anton4171afb2017-11-20 18:20:225803// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555804cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355805 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425806 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5807
5808 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 18:37:175809 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355810 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445811 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5812 video_options_);
Steve Anton75737c02017-11-06 18:37:175813 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555814 return nullptr;
Steve Anton75737c02017-11-06 18:37:175815 }
Steve Anton75737c02017-11-06 18:37:175816 video_channel->SignalDtlsSrtpSetupFailure.connect(
5817 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175818 video_channel->SignalSentPacket.connect(this,
5819 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355820 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225821
Steve Antoneda6ccd2017-12-04 18:21:555822 return video_channel;
Steve Anton75737c02017-11-06 18:37:175823}
5824
Zhi Huange830e682018-03-30 17:48:355825bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225826 switch (data_channel_type_) {
5827 case cricket::DCT_MEDIA_TRANSPORT:
5828 if (network_thread()->Invoke<bool>(
5829 RTC_FROM_HERE,
5830 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5831 this, mid))) {
5832 for (const auto& channel : sctp_data_channels_) {
5833 channel->OnTransportChannelCreated();
5834 }
5835 return true;
5836 }
Steve Anton75737c02017-11-06 18:37:175837 return false;
Bjorn Mellem175aa2e2018-11-08 19:23:225838 case cricket::DCT_SCTP:
5839 if (!sctp_factory_) {
5840 RTC_LOG(LS_ERROR)
5841 << "Trying to create SCTP transport, but didn't compile with "
5842 "SCTP support (HAVE_SCTP)";
5843 return false;
5844 }
5845 if (!network_thread()->Invoke<bool>(
5846 RTC_FROM_HERE,
5847 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5848 return false;
5849 }
5850 for (const auto& channel : sctp_data_channels_) {
5851 channel->OnTransportChannelCreated();
5852 }
5853 return true;
5854 case cricket::DCT_RTP:
5855 default:
5856 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5857 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5858 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5859 SrtpRequired(), GetCryptoOptions());
5860 if (!rtp_data_channel_) {
5861 return false;
5862 }
5863 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5864 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5865 rtp_data_channel_->SignalSentPacket.connect(
5866 this, &PeerConnection::OnSentPacket_w);
5867 rtp_data_channel_->SetRtpTransport(rtp_transport);
5868 return true;
Steve Anton75737c02017-11-06 18:37:175869 }
5870
Steve Anton75737c02017-11-06 18:37:175871 return true;
5872}
5873
5874Call::Stats PeerConnection::GetCallStats() {
5875 if (!worker_thread()->IsCurrent()) {
5876 return worker_thread()->Invoke<Call::Stats>(
5877 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5878 }
5879 if (call_) {
5880 return call_->GetStats();
5881 } else {
5882 return Call::Stats();
5883 }
5884}
5885
Zhi Huange830e682018-03-30 17:48:355886bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175887 RTC_DCHECK(network_thread()->IsCurrent());
5888 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265889 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355890 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265891 RTC_DCHECK(dtls_transport);
5892 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175893 RTC_DCHECK(sctp_transport_);
5894 sctp_invoker_.reset(new rtc::AsyncInvoker());
5895 sctp_transport_->SignalReadyToSendData.connect(
5896 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5897 sctp_transport_->SignalDataReceived.connect(
5898 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:325899 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5900 // another thread. Would be nice if there was a helper class similar to
5901 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5902 // code.
5903 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5904 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5905 sctp_transport_->SignalClosingProcedureComplete.connect(
5906 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:355907 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265908 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355909 return true;
Steve Anton75737c02017-11-06 18:37:175910}
5911
5912void PeerConnection::DestroySctpTransport_n() {
5913 RTC_DCHECK(network_thread()->IsCurrent());
5914 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355915 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175916 sctp_invoker_.reset(nullptr);
5917 sctp_ready_to_send_data_ = false;
5918}
5919
5920void PeerConnection::OnSctpTransportReadyToSendData_n() {
5921 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5922 RTC_DCHECK(network_thread()->IsCurrent());
5923 // Note: Cannot use rtc::Bind here because it will grab a reference to
5924 // PeerConnection and potentially cause PeerConnection to live longer than
5925 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5926 // be destroyed before PeerConnection is destroyed, and at that point all
5927 // pending tasks will be cleared.
5928 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5929 OnSctpTransportReadyToSendData_s(true);
5930 });
5931}
5932
5933void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5934 RTC_DCHECK(signaling_thread()->IsCurrent());
5935 sctp_ready_to_send_data_ = ready;
5936 SignalSctpReadyToSendData(ready);
5937}
5938
5939void PeerConnection::OnSctpTransportDataReceived_n(
5940 const cricket::ReceiveDataParams& params,
5941 const rtc::CopyOnWriteBuffer& payload) {
5942 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5943 RTC_DCHECK(network_thread()->IsCurrent());
5944 // Note: Cannot use rtc::Bind here because it will grab a reference to
5945 // PeerConnection and potentially cause PeerConnection to live longer than
5946 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5947 // be destroyed before PeerConnection is destroyed, and at that point all
5948 // pending tasks will be cleared.
5949 sctp_invoker_->AsyncInvoke<void>(
5950 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5951 OnSctpTransportDataReceived_s(params, payload);
5952 });
5953}
5954
5955void PeerConnection::OnSctpTransportDataReceived_s(
5956 const cricket::ReceiveDataParams& params,
5957 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 19:23:225958 RTC_DCHECK_RUN_ON(signaling_thread());
5959 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 18:37:175960 SignalSctpDataReceived(params, payload);
5961 }
5962}
5963
Taylor Brandstettercdd05f02018-05-31 20:23:325964void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:175965 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5966 RTC_DCHECK(network_thread()->IsCurrent());
5967 sctp_invoker_->AsyncInvoke<void>(
5968 RTC_FROM_HERE, signaling_thread(),
5969 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:325970 &SignalSctpClosingProcedureStartedRemotely, sid));
5971}
5972
5973void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5974 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5975 RTC_DCHECK(network_thread()->IsCurrent());
5976 sctp_invoker_->AsyncInvoke<void>(
5977 RTC_FROM_HERE, signaling_thread(),
5978 rtc::Bind(&sigslot::signal1<int>::operator(),
5979 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:175980}
5981
Bjorn Mellem175aa2e2018-11-08 19:23:225982bool PeerConnection::SetupMediaTransportForDataChannels_n(
5983 const std::string& mid) {
5984 media_transport_ = transport_controller_->GetMediaTransport(mid);
5985 if (!media_transport_) {
5986 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5987 return false;
5988 }
5989
5990 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5991 media_transport_->SetDataSink(this);
5992 media_transport_data_mid_ = mid;
5993 transport_controller_->SignalMediaTransportStateChanged.connect(
5994 this, &PeerConnection::OnMediaTransportStateChanged_n);
5995 // Check the initial state right away, in case transport is already writable.
5996 OnMediaTransportStateChanged_n();
5997 return true;
5998}
5999
6000void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6001 if (!media_transport_) {
6002 return;
6003 }
6004 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6005 media_transport_data_mid_.reset();
6006 media_transport_->SetDataSink(nullptr);
6007 media_transport_invoker_ = nullptr;
6008 media_transport_ = nullptr;
6009}
6010
6011void PeerConnection::OnMediaTransportStateChanged_n() {
6012 if (!media_transport_data_mid_ ||
6013 transport_controller_->GetMediaTransportState(
6014 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6015 return;
6016 }
6017 media_transport_invoker_->AsyncInvoke<void>(
6018 RTC_FROM_HERE, signaling_thread(), [this] {
6019 RTC_DCHECK_RUN_ON(signaling_thread());
6020 media_transport_ready_to_send_data_ = true;
6021 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6022 });
6023}
6024
Steve Anton75737c02017-11-06 18:37:176025// Returns false if bundle is enabled and rtcp_mux is disabled.
6026bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6027 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6028 if (!bundle_enabled)
6029 return true;
6030
6031 const cricket::ContentGroup* bundle_group =
6032 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6033 RTC_DCHECK(bundle_group != NULL);
6034
6035 const cricket::ContentInfos& contents = desc->contents();
6036 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6037 citer != contents.end(); ++citer) {
6038 const cricket::ContentInfo* content = (&*citer);
6039 RTC_DCHECK(content != NULL);
6040 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:006041 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:176042 if (!HasRtcpMuxEnabled(content))
6043 return false;
6044 }
6045 }
6046 // RTCP-MUX is enabled in all the contents.
6047 return true;
6048}
6049
6050bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:306051 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:176052}
6053
Steve Anton8a006912017-12-04 23:25:566054RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:176055 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:566056 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:216057 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:566058 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:176059 }
6060
6061 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:566062 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:176063 }
6064
Steve Anton3828c062017-12-06 18:34:516065 SdpType type = sdesc->GetType();
6066 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6067 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:566068 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:036069 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:566070 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:176071 }
6072
6073 // Verify crypto settings.
6074 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:566075 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6076 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:536077 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:566078 if (!crypto_error.ok()) {
6079 return crypto_error;
6080 }
Steve Anton75737c02017-11-06 18:37:176081 }
6082
6083 // Verify ice-ufrag and ice-pwd.
6084 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566085 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6086 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:176087 }
6088
6089 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566090 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6091 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:176092 }
6093
6094 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6095 // m-lines that do not rtcp-mux enabled.
6096
6097 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:516098 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:486099 // With an answer we want to compare the new answer session description with
6100 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:176101 const cricket::SessionDescription* offer_desc =
6102 (source == cricket::CS_LOCAL) ? remote_description()->description()
6103 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:486104 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6105 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6106 type)) {
Steve Anton8a006912017-12-04 23:25:566107 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6108 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:176109 }
6110 } else {
Steve Anton75737c02017-11-06 18:37:176111 // The re-offers should respect the order of m= sections in current
6112 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:486113 // With a re-offer, either the current local or current remote descriptions
6114 // could be the most up to date, so we would like to check against both of
6115 // them if they exist. It could be the case that one of them has a 0 port
6116 // for a media section, but the other does not. This is important to check
6117 // against in the case that we are recycling an m= section.
6118 const cricket::SessionDescription* current_desc = nullptr;
6119 const cricket::SessionDescription* secondary_current_desc = nullptr;
6120 if (local_description()) {
6121 current_desc = local_description()->description();
6122 if (remote_description()) {
6123 secondary_current_desc = remote_description()->description();
6124 }
6125 } else if (remote_description()) {
6126 current_desc = remote_description()->description();
6127 }
Steve Anton75737c02017-11-06 18:37:176128 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:486129 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6130 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:566131 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6132 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:176133 }
6134 }
6135
Steve Antonba42e992018-04-09 21:10:016136 if (IsUnifiedPlan()) {
6137 // Ensure that each audio and video media section has at most one
6138 // "StreamParams". This will return an error if receiving a session
6139 // description from a "Plan B" endpoint which adds multiple tracks of the
6140 // same type. With Unified Plan, there can only be at most one track per
6141 // media section.
6142 for (const ContentInfo& content : sdesc->description()->contents()) {
6143 const MediaContentDescription& desc = *content.description;
6144 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6145 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6146 desc.streams().size() > 1u) {
6147 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6148 "Media section has more than one track specified "
6149 "with a=ssrc lines which is not supported with "
6150 "Unified Plan.");
6151 }
6152 }
6153 }
6154
Steve Anton8a006912017-12-04 23:25:566155 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176156}
6157
Steve Anton3828c062017-12-06 18:34:516158bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176159 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516160 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176161 return (state == PeerConnectionInterface::kStable) ||
6162 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:526163 } else {
Steve Anton3828c062017-12-06 18:34:516164 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176165 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6166 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6167 }
6168}
6169
Steve Anton3828c062017-12-06 18:34:516170bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176171 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516172 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176173 return (state == PeerConnectionInterface::kStable) ||
6174 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:526175 } else {
Steve Anton3828c062017-12-06 18:34:516176 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176177 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6178 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6179 }
6180}
6181
Steve Antonf8470812017-12-04 18:46:216182const char* PeerConnection::SessionErrorToString(SessionError error) const {
6183 switch (error) {
6184 case SessionError::kNone:
6185 return "ERROR_NONE";
6186 case SessionError::kContent:
6187 return "ERROR_CONTENT";
6188 case SessionError::kTransport:
6189 return "ERROR_TRANSPORT";
6190 }
6191 RTC_NOTREACHED();
6192 return "";
6193}
6194
Steve Anton75737c02017-11-06 18:37:176195std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:306196 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:216197 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6198 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:326199 return desc.Release();
Steve Anton75737c02017-11-06 18:37:176200}
6201
Steve Anton8e20f172018-03-06 18:55:046202void PeerConnection::ReportSdpFormatReceived(
6203 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:046204 int num_audio_mlines = 0;
6205 int num_video_mlines = 0;
6206 int num_audio_tracks = 0;
6207 int num_video_tracks = 0;
6208 for (const ContentInfo& content : remote_offer.description()->contents()) {
6209 cricket::MediaType media_type = content.media_description()->type();
6210 int num_tracks = std::max(
6211 1, static_cast<int>(content.media_description()->streams().size()));
6212 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6213 num_audio_mlines += 1;
6214 num_audio_tracks += num_tracks;
6215 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6216 num_video_mlines += 1;
6217 num_video_tracks += num_tracks;
6218 }
6219 }
6220 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6221 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6222 format = kSdpFormatReceivedComplexUnifiedPlan;
6223 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6224 format = kSdpFormatReceivedComplexPlanB;
6225 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6226 format = kSdpFormatReceivedSimple;
6227 }
Qingsi Wang7fc821d2018-07-12 19:54:536228 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6229 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:046230}
6231
Harald Alvestrand8ebba742018-05-31 12:00:346232void PeerConnection::NoteUsageEvent(UsageEvent event) {
6233 RTC_DCHECK_RUN_ON(signaling_thread());
6234 usage_event_accumulator_ |= static_cast<int>(event);
6235}
6236
6237void PeerConnection::ReportUsagePattern() const {
6238 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:536239 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6240 usage_event_accumulator_,
6241 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:556242 const int bad_bits =
6243 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6244 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6245 const int good_bits =
6246 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6247 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6248 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6249 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6250 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:166251 // If called after close(), we can't report, because observer may have
6252 // been deallocated, and therefore pointer is null. Write to log instead.
6253 if (observer_) {
6254 Observer()->OnInterestingUsage(usage_event_accumulator_);
6255 } else {
6256 RTC_LOG(LS_INFO) << "Interesting usage signature "
6257 << usage_event_accumulator_
6258 << " observed after observer shutdown";
6259 }
Harald Alvestrandc0e97252018-07-26 08:39:556260 }
Harald Alvestrand8ebba742018-05-31 12:00:346261}
6262
Steve Anton0ffaaa22018-02-23 18:31:306263void PeerConnection::ReportNegotiatedSdpSemantics(
6264 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:536265 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:306266 switch (answer.description()->msid_signaling()) {
6267 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:536268 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:306269 break;
6270 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:536271 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:306272 break;
6273 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536274 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:306275 break;
6276 case cricket::kMsidSignalingMediaSection |
6277 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536278 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:306279 break;
6280 default:
6281 RTC_NOTREACHED();
6282 }
Qingsi Wang7fc821d2018-07-12 19:54:536283 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6284 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:306285}
6286
Steve Anton75737c02017-11-06 18:37:176287// We need to check the local/remote description for the Transport instead of
6288// the session, because a new Transport added during renegotiation may have
6289// them unset while the session has them set from the previous negotiation.
6290// Not doing so may trigger the auto generation of transport description and
6291// mess up DTLS identity information, ICE credential, etc.
6292bool PeerConnection::ReadyToUseRemoteCandidate(
6293 const IceCandidateInterface* candidate,
6294 const SessionDescriptionInterface* remote_desc,
6295 bool* valid) {
6296 *valid = true;
6297
6298 const SessionDescriptionInterface* current_remote_desc =
6299 remote_desc ? remote_desc : remote_description();
6300
6301 if (!current_remote_desc) {
6302 return false;
6303 }
6304
6305 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6306 size_t remote_content_size =
6307 current_remote_desc->description()->contents().size();
6308 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:256309 RTC_LOG(LS_ERROR)
6310 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6311 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176312
6313 *valid = false;
6314 return false;
6315 }
6316
6317 cricket::ContentInfo content =
6318 current_remote_desc->description()->contents()[mediacontent_index];
6319
6320 const std::string transport_name = GetTransportName(content.name);
6321 if (transport_name.empty()) {
6322 return false;
6323 }
Zhi Huange830e682018-03-30 17:48:356324 return true;
Steve Anton75737c02017-11-06 18:37:176325}
6326
6327bool PeerConnection::SrtpRequired() const {
6328 return dtls_enabled_ ||
6329 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6330}
6331
6332void PeerConnection::OnTransportControllerGatheringState(
6333 cricket::IceGatheringState state) {
6334 RTC_DCHECK(signaling_thread()->IsCurrent());
6335 if (state == cricket::kIceGatheringGathering) {
6336 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6337 } else if (state == cricket::kIceGatheringComplete) {
6338 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6339 }
6340}
6341
6342void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:456343 std::map<std::string, std::set<cricket::MediaType>>
6344 media_types_by_transport_name;
6345 for (auto transceiver : transceivers_) {
6346 if (transceiver->internal()->channel()) {
6347 const std::string& transport_name =
6348 transceiver->internal()->channel()->transport_name();
6349 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086350 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456351 }
Steve Anton75737c02017-11-06 18:37:176352 }
6353 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456354 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6355 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176356 }
Zhi Huange830e682018-03-30 17:48:356357
Danil Chapovalov66cadcc2018-06-19 14:47:436358 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356359 if (transport_name) {
6360 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456361 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176362 }
Zhi Huange830e682018-03-30 17:48:356363
Steve Antonc7b964c2018-02-01 22:39:456364 for (const auto& entry : media_types_by_transport_name) {
6365 const std::string& transport_name = entry.first;
6366 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176367 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456368 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176369 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456370 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176371 }
6372 }
6373}
6374// Walk through the ConnectionInfos to gather best connection usage
6375// for IPv4 and IPv6.
6376void PeerConnection::ReportBestConnectionState(
6377 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:456378 for (const cricket::TransportChannelStats& channel_stats :
6379 stats.channel_stats) {
6380 for (const cricket::ConnectionInfo& connection_info :
6381 channel_stats.connection_infos) {
6382 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176383 continue;
6384 }
6385
Steve Antonc7b964c2018-02-01 22:39:456386 const cricket::Candidate& local = connection_info.local_candidate;
6387 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176388
6389 // Increment the counter for IceCandidatePairType.
6390 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6391 (local.type() == RELAY_PORT_TYPE &&
6392 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:536393 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6394 GetIceCandidatePairCounter(local, remote),
6395 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176396 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536397 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6398 GetIceCandidatePairCounter(local, remote),
6399 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176400 } else {
6401 RTC_CHECK(0);
6402 }
Steve Anton75737c02017-11-06 18:37:176403
6404 // Increment the counter for IP type.
6405 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536406 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6407 kBestConnections_IPv4,
6408 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176409 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536410 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6411 kBestConnections_IPv6,
6412 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176413 } else {
6414 RTC_CHECK(0);
6415 }
6416
6417 return;
6418 }
6419 }
6420}
6421
6422void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456423 const cricket::TransportStats& stats,
6424 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176425 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6426 return;
6427 }
6428
6429 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6430 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6431 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6432 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6433 return;
6434 }
6435
Qingsi Wang7fc821d2018-07-12 19:54:536436 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6437 for (cricket::MediaType media_type : media_types) {
6438 switch (media_type) {
6439 case cricket::MEDIA_TYPE_AUDIO:
6440 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6441 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6442 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6443 break;
6444 case cricket::MEDIA_TYPE_VIDEO:
6445 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6446 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6447 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6448 break;
6449 case cricket::MEDIA_TYPE_DATA:
6450 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6451 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6452 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6453 break;
6454 default:
6455 RTC_NOTREACHED();
6456 continue;
6457 }
Steve Antonc7b964c2018-02-01 22:39:456458 }
Qingsi Wang7fc821d2018-07-12 19:54:536459 }
6460
6461 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6462 for (cricket::MediaType media_type : media_types) {
6463 switch (media_type) {
6464 case cricket::MEDIA_TYPE_AUDIO:
6465 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6466 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6467 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6468 break;
6469 case cricket::MEDIA_TYPE_VIDEO:
6470 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6471 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6472 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6473 break;
6474 case cricket::MEDIA_TYPE_DATA:
6475 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6476 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6477 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6478 break;
6479 default:
6480 RTC_NOTREACHED();
6481 continue;
6482 }
Steve Antonc7b964c2018-02-01 22:39:456483 }
Steve Anton75737c02017-11-06 18:37:176484 }
6485}
6486
6487void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6488 RTC_DCHECK(worker_thread()->IsCurrent());
6489 RTC_DCHECK(call_);
6490 call_->OnSentPacket(sent_packet);
6491}
6492
6493const std::string PeerConnection::GetTransportName(
6494 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-14 00:26:056495 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296496 if (channel) {
6497 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176498 }
Steve Anton6fec8802017-12-04 18:37:296499 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356500 RTC_DCHECK(sctp_mid_);
6501 if (content_name == *sctp_mid_) {
6502 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296503 }
6504 }
6505 // Return an empty string if failed to retrieve the transport name.
6506 return "";
Steve Anton75737c02017-11-06 18:37:176507}
6508
Steve Anton6fec8802017-12-04 18:37:296509void PeerConnection::DestroyTransceiverChannel(
6510 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6511 transceiver) {
6512 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176513
Amit Hilbuchdd9390c2018-11-14 00:26:056514 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:296515 if (channel) {
6516 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:056517 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:176518 }
6519}
6520
6521void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296522 if (rtp_data_channel_) {
6523 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-14 00:26:056524 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 18:37:296525 rtp_data_channel_ = nullptr;
6526 }
6527
6528 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6529 // grab a reference to this PeerConnection. If this is called from the
6530 // PeerConnection destructor, the RefCountedObject vtable will have already
6531 // been destroyed (since it is a subclass of PeerConnection) and using
6532 // rtc::Bind will cause "Pure virtual function called" error to appear.
6533
6534 if (sctp_transport_) {
6535 OnDataChannelDestroyed();
6536 network_thread()->Invoke<void>(RTC_FROM_HERE,
6537 [this] { DestroySctpTransport_n(); });
6538 }
Bjorn Mellem175aa2e2018-11-08 19:23:226539
6540 if (media_transport_) {
6541 OnDataChannelDestroyed();
6542 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6543 RTC_DCHECK_RUN_ON(network_thread());
6544 TeardownMediaTransportForDataChannels_n();
6545 });
6546 }
Steve Anton6fec8802017-12-04 18:37:296547}
6548
Amit Hilbuchdd9390c2018-11-14 00:26:056549void PeerConnection::DestroyChannelInterface(
6550 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:296551 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296552 switch (channel->media_type()) {
6553 case cricket::MEDIA_TYPE_AUDIO:
6554 channel_manager()->DestroyVoiceChannel(
6555 static_cast<cricket::VoiceChannel*>(channel));
6556 break;
6557 case cricket::MEDIA_TYPE_VIDEO:
6558 channel_manager()->DestroyVideoChannel(
6559 static_cast<cricket::VideoChannel*>(channel));
6560 break;
6561 case cricket::MEDIA_TYPE_DATA:
6562 channel_manager()->DestroyRtpDataChannel(
6563 static_cast<cricket::RtpDataChannel*>(channel));
6564 break;
6565 default:
6566 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6567 break;
6568 }
Zhi Huange830e682018-03-30 17:48:356569}
Steve Anton6fec8802017-12-04 18:37:296570
Taylor Brandstettercbaa2542018-04-16 23:42:146571bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356572 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146573 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196574 cricket::DtlsTransportInternal* dtls_transport,
6575 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 23:42:146576 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356577 auto base_channel = GetChannel(mid);
6578 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146579 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356580 }
Taylor Brandstettercbaa2542018-04-16 23:42:146581 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266582 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176583 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196584
6585 call_->MediaTransportChange(media_transport);
6586
Taylor Brandstettercbaa2542018-04-16 23:42:146587 return ret;
Steve Anton75737c02017-11-06 18:37:176588}
6589
Harald Alvestrand7a1c7f72018-08-01 08:50:166590PeerConnectionObserver* PeerConnection::Observer() const {
6591 // In earlier production code, the pointer was not cleared on close,
6592 // which might have led to undefined behavior if the observer was not
6593 // deallocated, or strange crashes if it was.
6594 // We use CHECK in order to catch such behavior if it exists.
6595 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6596 RTC_CHECK(observer_);
6597 return observer_;
6598}
6599
Benjamin Wright8c27cca2018-10-25 17:16:446600CryptoOptions PeerConnection::GetCryptoOptions() {
6601 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6602 // after it has been removed.
6603 return configuration_.crypto_options.has_value()
6604 ? *configuration_.crypto_options
6605 : factory_->options().crypto_options;
6606}
6607
Harald Alvestrand89061872018-01-02 13:08:346608void PeerConnection::ClearStatsCache() {
6609 if (stats_collector_) {
6610 stats_collector_->ClearCachedStatsReport();
6611 }
6612}
6613
Harald Alvestrand7a1c7f72018-08-01 08:50:166614void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:406615 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6616 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:166617}
6618
henrike@webrtc.org28e20752013-07-10 00:45:366619} // namespace webrtc