blob: 7ad2e3d973fd339e1fe563bd4b33779ea801d0dc [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"
25#include "call/call.h"
Qingsi Wang93a84392018-01-31 01:13:0926#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 11:18:2627#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3128#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1731#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 22:30:0937#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3138#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1740#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4141#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3142#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 09:42:2648#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3149#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 11:41:3050#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3151#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 19:54:5355#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3656
Steve Anton75737c02017-11-06 18:37:1757using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1762using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 18:21:5769namespace webrtc {
70
Steve Anton75737c02017-11-06 18:37:1771// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1775const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1783const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:3694
Steve Anton75737c02017-11-06 18:37:1795namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3696
Seth Hampson845e8782018-03-02 19:34:1097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2298static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11100
zhihuang8f65cdf2016-05-07 01:40:30101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
Steve Antonad182762018-09-05 20:22:40104enum {
105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
106 MSG_SET_SESSIONDESCRIPTION_FAILED,
107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
108 MSG_GETSTATS,
109 MSG_FREE_DATACHANNELS,
110 MSG_REPORT_USAGE_PATTERN,
111};
112
Harald Alvestrand19793842018-06-25 10:03:50113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
Steve Antonad182762018-09-05 20:22:40115struct SetSessionDescriptionMsg : public rtc::MessageData {
116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
118 : observer(observer) {}
119
120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
121 RTCError error;
122};
123
124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct GetStatsMsg : public rtc::MessageData {
134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
136 : observer(observer), track(track) {}
137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
139};
140
deadbeefab9b2d12015-10-14 18:33:11141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 23:05:28147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25149 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 19:49:08155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 18:33:11165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 21:10:50171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50175 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37176 cricket::MediaDescriptionOptions* video_media_description_options,
177 int num_sim_layers) {
olka3c747662017-08-17 13:50:32178 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50179 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
180 if (audio_media_description_options) {
181 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38182 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50183 }
184 } else {
185 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
186 if (video_media_description_options) {
187 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 08:58:37188 sender->id(), sender->internal()->stream_ids(),
189 num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50190 }
191 }
zhihuanga77e6bb2017-08-15 01:17:48192 }
zhihuang1c378ed2017-08-17 21:10:50193}
olka3c747662017-08-17 13:50:32194
zhihuang1c378ed2017-08-17 21:10:50195// Add options to |session_options| from |rtp_data_channels|.
196void AddRtpDataChannelOptions(
197 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
198 rtp_data_channels,
199 cricket::MediaDescriptionOptions* data_media_description_options) {
200 if (!data_media_description_options) {
201 return;
202 }
deadbeefab9b2d12015-10-14 18:33:11203 // Check for data channels.
204 for (const auto& kv : rtp_data_channels) {
205 const DataChannel* channel = kv.second;
206 if (channel->state() == DataChannel::kConnecting ||
207 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50208 // Legacy RTP data channels are signaled with the track/stream ID set to
209 // the data channel's label.
210 data_media_description_options->AddRtpDataChannel(channel->label(),
211 channel->label());
deadbeefab9b2d12015-10-14 18:33:11212 }
213 }
214}
215
Taylor Brandstettera1c30352016-05-13 15:15:11216uint32_t ConvertIceTransportTypeToCandidateFilter(
217 PeerConnectionInterface::IceTransportsType type) {
218 switch (type) {
219 case PeerConnectionInterface::kNone:
220 return cricket::CF_NONE;
221 case PeerConnectionInterface::kRelay:
222 return cricket::CF_RELAY;
223 case PeerConnectionInterface::kNoHost:
224 return (cricket::CF_ALL & ~cricket::CF_HOST);
225 case PeerConnectionInterface::kAll:
226 return cricket::CF_ALL;
227 default:
nissec80e7412017-01-11 13:56:46228 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11229 }
230 return cricket::CF_NONE;
231}
232
deadbeef293e9262017-01-11 20:28:30233// Helper to set an error and return from a method.
234bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
235 if (error) {
236 error->set_type(type);
237 }
238 return type == webrtc::RTCErrorType::NONE;
239}
240
Steve Anton038834f2017-07-14 22:59:59241bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 17:22:52242 bool ok = error.ok();
Steve Anton038834f2017-07-14 22:59:59243 if (error_out) {
244 *error_out = std::move(error);
245 }
Steve Antonf820a5e2018-08-10 17:22:52246 return ok;
Steve Anton038834f2017-07-14 22:59:59247}
248
Steve Antonba818672017-11-06 18:21:57249std::string GetSignalingStateString(
250 PeerConnectionInterface::SignalingState state) {
251 switch (state) {
252 case PeerConnectionInterface::kStable:
253 return "kStable";
254 case PeerConnectionInterface::kHaveLocalOffer:
255 return "kHaveLocalOffer";
256 case PeerConnectionInterface::kHaveLocalPrAnswer:
257 return "kHavePrAnswer";
258 case PeerConnectionInterface::kHaveRemoteOffer:
259 return "kHaveRemoteOffer";
260 case PeerConnectionInterface::kHaveRemotePrAnswer:
261 return "kHaveRemotePrAnswer";
262 case PeerConnectionInterface::kClosed:
263 return "kClosed";
264 }
265 RTC_NOTREACHED();
266 return "";
267}
deadbeef0a6c4ca2015-10-06 18:38:28268
Steve Anton75737c02017-11-06 18:37:17269IceCandidatePairType GetIceCandidatePairCounter(
270 const cricket::Candidate& local,
271 const cricket::Candidate& remote) {
272 const auto& l = local.type();
273 const auto& r = remote.type();
274 const auto& host = LOCAL_PORT_TYPE;
275 const auto& srflx = STUN_PORT_TYPE;
276 const auto& relay = RELAY_PORT_TYPE;
277 const auto& prflx = PRFLX_PORT_TYPE;
278 if (l == host && r == host) {
279 bool local_private = IPIsPrivate(local.address().ipaddr());
280 bool remote_private = IPIsPrivate(remote.address().ipaddr());
281 if (local_private) {
282 if (remote_private) {
283 return kIceCandidatePairHostPrivateHostPrivate;
284 } else {
285 return kIceCandidatePairHostPrivateHostPublic;
286 }
287 } else {
288 if (remote_private) {
289 return kIceCandidatePairHostPublicHostPrivate;
290 } else {
291 return kIceCandidatePairHostPublicHostPublic;
292 }
293 }
294 }
295 if (l == host && r == srflx)
296 return kIceCandidatePairHostSrflx;
297 if (l == host && r == relay)
298 return kIceCandidatePairHostRelay;
299 if (l == host && r == prflx)
300 return kIceCandidatePairHostPrflx;
301 if (l == srflx && r == host)
302 return kIceCandidatePairSrflxHost;
303 if (l == srflx && r == srflx)
304 return kIceCandidatePairSrflxSrflx;
305 if (l == srflx && r == relay)
306 return kIceCandidatePairSrflxRelay;
307 if (l == srflx && r == prflx)
308 return kIceCandidatePairSrflxPrflx;
309 if (l == relay && r == host)
310 return kIceCandidatePairRelayHost;
311 if (l == relay && r == srflx)
312 return kIceCandidatePairRelaySrflx;
313 if (l == relay && r == relay)
314 return kIceCandidatePairRelayRelay;
315 if (l == relay && r == prflx)
316 return kIceCandidatePairRelayPrflx;
317 if (l == prflx && r == host)
318 return kIceCandidatePairPrflxHost;
319 if (l == prflx && r == srflx)
320 return kIceCandidatePairPrflxSrflx;
321 if (l == prflx && r == relay)
322 return kIceCandidatePairPrflxRelay;
323 return kIceCandidatePairMax;
324}
325
Seth Hampsonae8a90a2018-02-13 23:33:48326// Logic to decide if an m= section can be recycled. This means that the new
327// m= section is not rejected, but the old local or remote m= section is
328// rejected. |old_content_one| and |old_content_two| refer to the m= section
329// of the old remote and old local descriptions in no particular order.
330// We need to check both the old local and remote because either
331// could be the most current from the latest negotation.
332bool IsMediaSectionBeingRecycled(SdpType type,
333 const ContentInfo& content,
334 const ContentInfo* old_content_one,
335 const ContentInfo* old_content_two) {
336 return type == SdpType::kOffer && !content.rejected &&
337 ((old_content_one && old_content_one->rejected) ||
338 (old_content_two && old_content_two->rejected));
339}
340
Steve Anton75737c02017-11-06 18:37:17341// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48342// |current_desc|. The number of m= sections in |new_desc| should be no
343// less than |current_desc|. In the case of checking an answer's
344// |new_desc|, the |current_desc| is the last offer that was set as the
345// local or remote. In the case of checking an offer's |new_desc| we
346// check against the local and remote descriptions stored from the last
347// negotiation, because either of these could be the most up to date for
348// possible rejected m sections. These are the |current_desc| and
349// |secondary_current_desc|.
350bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
351 const SessionDescription* secondary_current_desc,
352 const SessionDescription& new_desc,
353 const SdpType type) {
354 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 18:37:17355 return false;
356 }
357
Seth Hampsonae8a90a2018-02-13 23:33:48358 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
359 const cricket::ContentInfo* secondary_content_info = nullptr;
360 if (secondary_current_desc &&
361 i < secondary_current_desc->contents().size()) {
362 secondary_content_info = &secondary_current_desc->contents()[i];
363 }
364 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
365 &current_desc.contents()[i],
366 secondary_content_info)) {
367 // For new offer descriptions, if the media section can be recycled, it's
368 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-23 00:02:54369 continue;
370 }
Seth Hampsonae8a90a2018-02-13 23:33:48371 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17372 return false;
373 }
374 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48375 new_desc.contents()[i].media_description();
376 const MediaContentDescription* current_desc_mdesc =
377 current_desc.contents()[i].media_description();
378 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 18:37:17379 return false;
380 }
381 }
382 return true;
383}
384
Seth Hampsonae8a90a2018-02-13 23:33:48385bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
386 const SessionDescription& desc2) {
387 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17388}
389
Qingsi Wang7fc821d2018-07-12 19:54:53390void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
391 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20392 // Array of structs needed to map {KeyExchangeProtocolType,
393 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
394 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
395 static constexpr struct {
396 KeyExchangeProtocolType protocol_type;
397 cricket::MediaType media_type;
398 KeyExchangeProtocolMedia protocol_media;
399 } kEnumCounterKeyProtocolMediaMap[] = {
400 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
401 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
402 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
403 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
404 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
405 kEnumCounterKeyProtocolMediaTypeDtlsData},
406 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
407 kEnumCounterKeyProtocolMediaTypeSdesAudio},
408 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
409 kEnumCounterKeyProtocolMediaTypeSdesVideo},
410 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
411 kEnumCounterKeyProtocolMediaTypeSdesData},
412 };
413
Qingsi Wang7fc821d2018-07-12 19:54:53414 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
415 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26416
Mirko Bonadeiab499822018-09-11 08:43:20417 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
418 if (i.protocol_type == protocol_type && i.media_type == media_type) {
419 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
420 i.protocol_media,
421 kEnumCounterKeyProtocolMediaTypeMax);
422 }
Harald Alvestrandf9d0f1d2018-03-02 13:15:26423 }
424}
425
Harald Alvestrand76829d72018-07-18 21:24:36426void NoteAddIceCandidateResult(int result) {
427 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
428 kAddIceCandidateMax);
429}
430
Steve Anton75737c02017-11-06 18:37:17431// Checks that each non-rejected content has SDES crypto keys or a DTLS
432// fingerprint, unless it's in a BUNDLE group, in which case only the
433// BUNDLE-tag section (first media section/description in the BUNDLE group)
434// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
435// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
436// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 19:54:53437RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17438 const cricket::ContentGroup* bundle =
439 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56440 for (const cricket::ContentInfo& content_info : desc->contents()) {
441 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17442 continue;
443 }
Harald Alvestrand2e180612018-03-07 09:56:14444 // Note what media is used with each crypto protocol, for all sections.
445 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
446 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 19:54:53447 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56448 const std::string& mid = content_info.name;
449 if (bundle && bundle->HasContentName(mid) &&
450 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17451 // This isn't the first media section in the BUNDLE group, so it's not
452 // required to have crypto attributes, since only the crypto attributes
453 // from the first section actually get used.
454 continue;
455 }
456
457 // If the content isn't rejected or bundled into another m= section, crypto
458 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30459 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56460 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17461 if (!media || !tinfo) {
462 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56463 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17464 }
465 if (dtls_enabled) {
466 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25467 RTC_LOG(LS_WARNING)
468 << "Session description must have DTLS fingerprint if "
469 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56470 return RTCError(RTCErrorType::INVALID_PARAMETER,
471 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17472 }
473 } else {
474 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25475 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17476 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56477 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17478 }
479 }
480 }
Steve Anton8a006912017-12-04 23:25:56481 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17482}
483
484// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
485// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
486// media section/description in the BUNDLE group) needs a ufrag and pwd.
487bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
488 const cricket::ContentGroup* bundle =
489 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56490 for (const cricket::ContentInfo& content_info : desc->contents()) {
491 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17492 continue;
493 }
Steve Anton8a006912017-12-04 23:25:56494 const std::string& mid = content_info.name;
495 if (bundle && bundle->HasContentName(mid) &&
496 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17497 // This isn't the first media section in the BUNDLE group, so it's not
498 // required to have ufrag/password, since only the ufrag/password from
499 // the first section actually get used.
500 continue;
501 }
502
503 // If the content isn't rejected or bundled into another m= section,
504 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56505 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17506 if (!tinfo) {
507 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25508 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17509 return false;
510 }
511 if (tinfo->description.ice_ufrag.empty() ||
512 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25513 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17514 return false;
515 }
516 }
517 return true;
518}
519
520bool GetTrackIdBySsrc(const SessionDescription* session_description,
521 uint32_t ssrc,
522 std::string* track_id) {
523 RTC_DCHECK(track_id != NULL);
524
Steve Antonb1c1de12017-12-21 23:14:30525 const cricket::AudioContentDescription* audio_desc =
526 cricket::GetFirstAudioContentDescription(session_description);
527 if (audio_desc) {
528 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534
Steve Antonb1c1de12017-12-21 23:14:30535 const cricket::VideoContentDescription* video_desc =
536 cricket::GetFirstVideoContentDescription(session_description);
537 if (video_desc) {
538 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17539 if (found) {
540 *track_id = found->id;
541 return true;
542 }
543 }
544 return false;
545}
546
547// Get the SCTP port out of a SessionDescription.
548// Return -1 if not found.
549int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30550 const cricket::DataContentDescription* data_desc =
551 GetFirstDataContentDescription(session_description);
552 RTC_DCHECK(data_desc);
553 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17554 return -1;
555 }
Steve Anton75737c02017-11-06 18:37:17556 std::string value;
557 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
558 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30559 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17560 if (!codec.Matches(match_pattern)) {
561 continue;
562 }
563 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
564 return rtc::FromString<int>(value);
565 }
566 }
567 return -1;
568}
569
Steve Anton75737c02017-11-06 18:37:17570// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
571bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
572 const SessionDescriptionInterface* new_desc,
573 const std::string& content_name) {
574 if (!old_desc) {
575 return false;
576 }
577 const SessionDescription* new_sd = new_desc->description();
578 const SessionDescription* old_sd = old_desc->description();
579 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
580 if (!cinfo || cinfo->rejected) {
581 return false;
582 }
583 // If the content isn't rejected, check if ufrag and password has changed.
584 const cricket::TransportDescription* new_transport_desc =
585 new_sd->GetTransportDescriptionByName(content_name);
586 const cricket::TransportDescription* old_transport_desc =
587 old_sd->GetTransportDescriptionByName(content_name);
588 if (!new_transport_desc || !old_transport_desc) {
589 // No transport description exists. This is not an ICE restart.
590 return false;
591 }
592 if (cricket::IceCredentialsChanged(
593 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
594 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25595 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
596 << ".";
Steve Anton75737c02017-11-06 18:37:17597 return true;
598 }
599 return false;
600}
601
Steve Anton80dd7b52018-02-17 01:08:42602// Generates a string error message for SetLocalDescription/SetRemoteDescription
603// from an RTCError.
604std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
605 SdpType type,
606 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 11:41:30607 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42608 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
609 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32610 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42611}
612
Seth Hampson5b4f0752018-04-02 23:31:36613std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
614 std::string output = "streams=[";
615 const char* separator = "";
616 for (const auto& stream_id : stream_ids) {
617 output.append(separator).append(stream_id);
618 separator = ", ";
619 }
620 output.append("]");
621 return output;
622}
623
Danil Chapovalov66cadcc2018-06-19 14:47:43624absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23625 int rtc_configuration_parameter) {
626 if (rtc_configuration_parameter ==
627 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43628 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23629 }
630 return rtc_configuration_parameter;
631}
632
Steve Anton75737c02017-11-06 18:37:17633} // namespace
634
Henrik Boström31638672017-11-23 16:48:32635// Upon completion, posts a task to execute the callback of the
636// SetSessionDescriptionObserver asynchronously on the same thread. At this
637// point, the state of the peer connection might no longer reflect the effects
638// of the SetRemoteDescription operation, as the peer connection could have been
639// modified during the post.
640// TODO(hbos): Remove this class once we remove the version of
641// PeerConnectionInterface::SetRemoteDescription() that takes a
642// SetSessionDescriptionObserver as an argument.
643class PeerConnection::SetRemoteDescriptionObserverAdapter
644 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
645 public:
646 SetRemoteDescriptionObserverAdapter(
647 rtc::scoped_refptr<PeerConnection> pc,
648 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
649 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
650
651 // SetRemoteDescriptionObserverInterface implementation.
652 void OnSetRemoteDescriptionComplete(RTCError error) override {
653 if (error.ok())
654 pc_->PostSetSessionDescriptionSuccess(wrapper_);
655 else
Harald Alvestrand5081c0c2018-03-09 14:18:03656 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32657 }
658
659 private:
660 rtc::scoped_refptr<PeerConnection> pc_;
661 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
662};
663
deadbeef293e9262017-01-11 20:28:30664bool PeerConnectionInterface::RTCConfiguration::operator==(
665 const PeerConnectionInterface::RTCConfiguration& o) const {
666 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10667 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30668 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56669 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10670 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30671 BundlePolicy bundle_policy;
672 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10673 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
674 int ice_candidate_pool_size;
675 bool disable_ipv6;
676 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11677 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22678 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10679 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43680 absl::optional<int> screencast_min_bitrate;
681 absl::optional<bool> combined_audio_video_bwe;
682 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30683 TcpCandidatePolicy tcp_candidate_policy;
684 CandidateNetworkPolicy candidate_network_policy;
685 int audio_jitter_buffer_max_packets;
686 bool audio_jitter_buffer_fast_accelerate;
687 int ice_connection_receiving_timeout;
688 int ice_backup_candidate_pair_ping_interval;
689 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30690 bool prioritize_most_likely_ice_candidate_pairs;
691 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30692 bool prune_turn_ports;
693 bool presume_writable_when_fully_relayed;
694 bool enable_ice_renomination;
695 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 14:47:43696 absl::optional<int> ice_check_interval_strong_connectivity;
697 absl::optional<int> ice_check_interval_weak_connectivity;
698 absl::optional<int> ice_check_min_interval;
699 absl::optional<int> ice_unwritable_timeout;
700 absl::optional<int> ice_unwritable_min_checks;
701 absl::optional<int> stun_candidate_keepalive_interval;
702 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40703 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56704 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43705 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11706 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30707 };
708 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
709 "Did you add something to RTCConfiguration and forget to "
710 "update operator==?");
711 return type == o.type && servers == o.servers &&
712 bundle_policy == o.bundle_policy &&
713 rtcp_mux_policy == o.rtcp_mux_policy &&
714 tcp_candidate_policy == o.tcp_candidate_policy &&
715 candidate_network_policy == o.candidate_network_policy &&
716 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
717 audio_jitter_buffer_fast_accelerate ==
718 o.audio_jitter_buffer_fast_accelerate &&
719 ice_connection_receiving_timeout ==
720 o.ice_connection_receiving_timeout &&
721 ice_backup_candidate_pair_ping_interval ==
722 o.ice_backup_candidate_pair_ping_interval &&
723 continual_gathering_policy == o.continual_gathering_policy &&
724 certificates == o.certificates &&
725 prioritize_most_likely_ice_candidate_pairs ==
726 o.prioritize_most_likely_ice_candidate_pairs &&
727 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51728 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11729 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22730 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30731 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30732 screencast_min_bitrate == o.screencast_min_bitrate &&
733 combined_audio_video_bwe == o.combined_audio_video_bwe &&
734 enable_dtls_srtp == o.enable_dtls_srtp &&
735 ice_candidate_pool_size == o.ice_candidate_pool_size &&
736 prune_turn_ports == o.prune_turn_ports &&
737 presume_writable_when_fully_relayed ==
738 o.presume_writable_when_fully_relayed &&
739 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14740 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14741 ice_check_interval_strong_connectivity ==
742 o.ice_check_interval_strong_connectivity &&
743 ice_check_interval_weak_connectivity ==
744 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10745 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57746 ice_unwritable_timeout == o.ice_unwritable_timeout &&
747 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49748 stun_candidate_keepalive_interval ==
749 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40750 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56751 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40752 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11753 network_preference == o.network_preference &&
754 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30755}
756
757bool PeerConnectionInterface::RTCConfiguration::operator!=(
758 const PeerConnectionInterface::RTCConfiguration& o) const {
759 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26760}
761
zhihuang8f65cdf2016-05-07 01:40:30762// Generate a RTCP CNAME when a PeerConnection is created.
763std::string GenerateRtcpCname() {
764 std::string cname;
765 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25766 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27767 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30768 }
769 return cname;
770}
771
zhihuang1c378ed2017-08-17 21:10:50772bool ValidateOfferAnswerOptions(
773 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
774 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
775 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32776}
777
zhihuang1c378ed2017-08-17 21:10:50778// From |rtc_options|, fill parts of |session_options| shared by all generated
779// m= sections (in other words, nothing that involves a map/array).
780void ExtractSharedMediaSessionOptions(
781 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
782 cricket::MediaSessionOptions* session_options) {
783 session_options->vad_enabled = rtc_options.voice_activity_detection;
784 session_options->bundle_enabled = rtc_options.use_rtp_mux;
785}
zhihuanga77e6bb2017-08-15 01:17:48786
zhihuang38ede132017-06-15 19:52:32787PeerConnection::PeerConnection(PeerConnectionFactory* factory,
788 std::unique_ptr<RtcEventLog> event_log,
789 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36790 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32791 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30792 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11793 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32794 remote_streams_(StreamCollection::Create()),
795 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36796
797PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17798 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22799 RTC_DCHECK_RUN_ON(signaling_thread());
800
Steve Anton8af21862017-12-15 19:20:13801 // Need to stop transceivers before destroying the stats collector because
802 // AudioRtpSender has a reference to the StatsCollector it will update when
803 // stopping.
804 for (auto transceiver : transceivers_) {
805 transceiver->Stop();
806 }
Steve Anton4171afb2017-11-20 18:20:22807
Taylor Brandstettera1c30352016-05-13 15:15:11808 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57809 if (stats_collector_) {
810 stats_collector_->WaitForPendingRequest();
811 stats_collector_ = nullptr;
812 }
Steve Anton75737c02017-11-06 18:37:17813
Steve Anton8af21862017-12-15 19:20:13814 // Don't destroy BaseChannels until after stats has been cleaned up so that
815 // the last stats request can still read from the channels.
816 DestroyAllChannels();
817
Mirko Bonadei675513b2017-11-09 10:09:25818 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17819
820 webrtc_session_desc_factory_.reset();
821 sctp_invoker_.reset();
822 sctp_factory_.reset();
823 transport_controller_.reset();
824
deadbeef91dd5672016-05-18 23:55:30825 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27826 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02827 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15828 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02829 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15830 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09831 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15832 event_log_.reset();
833 });
henrike@webrtc.org28e20752013-07-10 00:45:36834}
835
Steve Anton8af21862017-12-15 19:20:13836void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08837 // Destroy video channels first since they may have a pointer to a voice
838 // channel.
839 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08840 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08841 DestroyTransceiverChannel(transceiver);
842 }
843 }
844 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08845 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08846 DestroyTransceiverChannel(transceiver);
847 }
848 }
849 DestroyDataChannel();
850}
851
henrike@webrtc.org28e20752013-07-10 00:45:36852bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45853 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47854 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17855 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59856
857 RTCError config_error = ValidateConfiguration(configuration);
858 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25859 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59860 return false;
861 }
862
Benjamin Wrightcab588882018-05-02 22:12:47863 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25864 RTC_LOG(LS_ERROR)
865 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07866 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30867 return false;
868 }
Jonas Orelandbdcee282017-10-10 12:01:40869
Benjamin Wrightcab588882018-05-02 22:12:47870 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30871 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25872 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07873 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10874 return false;
875 }
Benjamin Wrightd6f86e82018-05-08 20:12:25876
Benjamin Wrightcab588882018-05-02 22:12:47877 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15878 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47879 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25880 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10881
Harald Alvestrandb2a74782018-06-28 11:54:07882 cricket::ServerAddresses stun_servers;
883 std::vector<cricket::RelayServerConfig> turn_servers;
884
885 RTCErrorType parse_error =
886 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
887 if (parse_error != RTCErrorType::NONE) {
888 return false;
889 }
890
deadbeef91dd5672016-05-18 23:55:30891 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11892 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27893 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 11:54:07894 RTC_FROM_HERE,
895 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
896 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36897 return false;
898 }
Harald Alvestrandb2a74782018-06-28 11:54:07899 // If initialization was successful, note if STUN or TURN servers
900 // were supplied.
901 if (!stun_servers.empty()) {
902 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
903 }
904 if (!turn_servers.empty()) {
905 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
906 }
henrike@webrtc.org28e20752013-07-10 00:45:36907
Qingsi Wang7fc821d2018-07-12 19:54:53908 // Send information about IPv4/IPv6 status.
909 PeerConnectionAddressFamilyCounter address_family;
910 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
911 address_family = kPeerConnection_IPv6;
912 } else {
913 address_family = kPeerConnection_IPv4;
914 }
915 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
916 kPeerConnectionAddressFamilyCounter_Max);
917
Zhi Huange830e682018-03-30 17:48:35918 const PeerConnectionFactoryInterface::Options& options = factory_->options();
919
Steve Anton75737c02017-11-06 18:37:17920 // RFC 3264: The numeric value of the session id and version in the
921 // o line MUST be representable with a "64 bit signed integer".
922 // Due to this constraint session id |session_id_| is max limited to
923 // LLONG_MAX.
924 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35925 JsepTransportController::Config config;
926 config.redetermine_role_on_ice_restart =
927 configuration.redetermine_role_on_ice_restart;
928 config.ssl_max_version = factory_->options().ssl_max_version;
929 config.disable_encryption = options.disable_encryption;
930 config.bundle_policy = configuration.bundle_policy;
931 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
932 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:34933 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46934 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35935#if defined(ENABLE_EXTERNAL_AUTH)
936 config.enable_external_auth = true;
937#endif
Zhi Huangb57e1692018-06-12 18:41:11938 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 17:48:35939 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:15940 signaling_thread(), network_thread(), port_allocator_.get(),
941 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:35942 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 18:37:17943 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 17:48:35944 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17945 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35946 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17947 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35948 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17949 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
950 transport_controller_->SignalDtlsHandshakeError.connect(
951 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
952
953 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25954
deadbeefab9b2d12015-10-14 18:33:11955 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01956 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36957
Steve Antonba818672017-11-06 18:21:57958 configuration_ = configuration;
959
Steve Anton75737c02017-11-06 18:37:17960 // Obtain a certificate from RTCConfiguration if any were provided (optional).
961 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
962 if (!configuration.certificates.empty()) {
963 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
964 // just picking the first one. The decision should be made based on the DTLS
965 // handshake. The DTLS negotiations need to know about all certificates.
966 certificate = configuration.certificates[0];
967 }
968
Steve Antond25da372017-11-06 22:50:29969 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:17970
971 if (options.disable_encryption) {
972 dtls_enabled_ = false;
973 } else {
974 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:47975 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:17976 // |configuration| can override the default |dtls_enabled_| value.
977 if (configuration.enable_dtls_srtp) {
978 dtls_enabled_ = *(configuration.enable_dtls_srtp);
979 }
980 }
981
982 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
983 // It takes precendence over the disable_sctp_data_channels
984 // PeerConnectionFactoryInterface::Options.
985 if (configuration.enable_rtp_data_channel) {
986 data_channel_type_ = cricket::DCT_RTP;
987 } else {
988 // DTLS has to be enabled to use SCTP.
989 if (!options.disable_sctp_data_channels && dtls_enabled_) {
990 data_channel_type_ = cricket::DCT_SCTP;
991 }
992 }
993
994 video_options_.screencast_min_bitrate_kbps =
995 configuration.screencast_min_bitrate;
996 audio_options_.combined_audio_video_bwe =
997 configuration.combined_audio_video_bwe;
998
999 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301000 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171001
1002 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301003 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171004
1005 // Whether the certificate generator/certificate is null or not determines
1006 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1007 // the right instructions by clearing the variables if needed.
1008 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471009 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171010 certificate = nullptr;
1011 } else if (certificate) {
1012 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171014 }
1015
1016 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1017 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471018 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171019 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1020 this, &PeerConnection::OnCertificateReady);
1021
1022 if (options.disable_encryption) {
1023 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1024 }
1025
1026 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1027 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361028
Steve Anton4171afb2017-11-20 18:20:221029 // Add default audio/video transceivers for Plan B SDP.
1030 if (!IsUnifiedPlan()) {
1031 transceivers_.push_back(
1032 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1033 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1037 }
Harald Alvestrand183e09d2018-06-28 10:04:411038 int delay_ms =
1039 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401040 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1041 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:361042 return true;
1043}
1044
Steve Anton038834f2017-07-14 22:59:591045RTCError PeerConnection::ValidateConfiguration(
1046 const RTCConfiguration& config) const {
1047 if (config.ice_regather_interval_range &&
1048 config.continual_gathering_policy == GATHER_ONCE) {
1049 return RTCError(RTCErrorType::INVALID_PARAMETER,
1050 "ice_regather_interval_range specified but continual "
1051 "gathering policy is GATHER_ONCE");
1052 }
Qingsi Wangdea68892018-03-27 17:55:211053 auto result =
1054 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1055 return result;
Steve Anton038834f2017-07-14 22:59:591056}
1057
Yves Gerey665174f2018-06-19 13:03:051058rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581059 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1060 "Plan SdpSemantics. Please use GetSenders "
1061 "instead.";
deadbeefab9b2d12015-10-14 18:33:111062 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361063}
1064
Yves Gerey665174f2018-06-19 13:03:051065rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581066 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1067 "Plan SdpSemantics. Please use GetReceivers "
1068 "instead.";
deadbeefab9b2d12015-10-14 18:33:111069 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361070}
1071
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291072bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581073 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1074 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171075 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361076 if (IsClosed()) {
1077 return false;
1078 }
deadbeefab9b2d12015-10-14 18:33:111079 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361080 return false;
1081 }
deadbeefab9b2d12015-10-14 18:33:111082
1083 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431084 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1085 observer->SignalAudioTrackAdded.connect(this,
1086 &PeerConnection::OnAudioTrackAdded);
1087 observer->SignalAudioTrackRemoved.connect(
1088 this, &PeerConnection::OnAudioTrackRemoved);
1089 observer->SignalVideoTrackAdded.connect(this,
1090 &PeerConnection::OnVideoTrackAdded);
1091 observer->SignalVideoTrackRemoved.connect(
1092 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291093 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111094
deadbeefab9b2d12015-10-14 18:33:111095 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251096 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111097 }
1098 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251099 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111100 }
1101
tommi@webrtc.org03505bc2014-07-14 20:15:261102 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:161103 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361104 return true;
1105}
1106
1107void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581108 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1109 "Plan SdpSemantics. Please use RemoveTrack "
1110 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171111 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251112 if (!IsClosed()) {
1113 for (const auto& track : local_stream->GetAudioTracks()) {
1114 RemoveAudioTrack(track.get(), local_stream);
1115 }
1116 for (const auto& track : local_stream->GetVideoTracks()) {
1117 RemoveVideoTrack(track.get(), local_stream);
1118 }
deadbeefab9b2d12015-10-14 18:33:111119 }
deadbeefab9b2d12015-10-14 18:33:111120 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431121 stream_observers_.erase(
1122 std::remove_if(
1123 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291124 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281125 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431126 }),
1127 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111128
henrike@webrtc.org28e20752013-07-10 00:45:361129 if (IsClosed()) {
1130 return;
1131 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161132 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361133}
1134
Steve Anton2d6c76a2018-01-06 01:10:521135RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571136 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101137 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521138 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571139 if (!track) {
1140 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1141 }
1142 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1143 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1144 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1145 "Track has invalid kind: " + track->kind());
1146 }
Steve Antonf9381f02017-12-14 18:23:571147 if (IsClosed()) {
1148 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1149 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421150 }
Steve Anton4171afb2017-11-20 18:20:221151 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571152 LOG_AND_RETURN_ERROR(
1153 RTCErrorType::INVALID_PARAMETER,
1154 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421155 }
Steve Antonf9381f02017-12-14 18:23:571156 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361157 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1158 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571159 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161160 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171161 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571162 }
1163 return sender_or_error;
1164}
deadbeefe1f9d832016-01-14 23:35:421165
Steve Antonf9381f02017-12-14 18:23:571166RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1167PeerConnection::AddTrackPlanB(
1168 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101169 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361170 if (stream_ids.size() > 1u) {
1171 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1172 "AddTrack with more than one stream is not "
1173 "supported with Plan B semantics.");
1174 }
1175 std::vector<std::string> adjusted_stream_ids = stream_ids;
1176 if (adjusted_stream_ids.empty()) {
1177 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1178 }
Steve Anton02ee47c2018-01-11 00:26:061179 cricket::MediaType media_type =
1180 (track->kind() == MediaStreamTrackInterface::kAudioKind
1181 ? cricket::MEDIA_TYPE_AUDIO
1182 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361183 auto new_sender =
1184 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 23:35:421185 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 23:19:501186 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221187 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221188 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181189 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361190 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221191 if (sender_info) {
1192 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421193 }
Steve Antonf9381f02017-12-14 18:23:571194 } else {
1195 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 23:19:501196 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221197 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221198 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181199 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361200 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221201 if (sender_info) {
1202 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421203 }
deadbeefe1f9d832016-01-14 23:35:421204 }
Steve Anton02ee47c2018-01-11 00:26:061205 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571206}
deadbeefe1f9d832016-01-14 23:35:421207
Steve Antonf9381f02017-12-14 18:23:571208RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1209PeerConnection::AddTrackUnifiedPlan(
1210 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101211 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571212 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1213 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231214 RTC_LOG(LS_INFO) << "Reusing an existing "
1215 << cricket::MediaTypeToString(transceiver->media_type())
1216 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571217 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121218 transceiver->internal()->set_direction(
1219 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571220 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121221 transceiver->internal()->set_direction(
1222 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571223 }
Steve Anton02ee47c2018-01-11 00:26:061224 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101225 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571226 } else {
1227 cricket::MediaType media_type =
1228 (track->kind() == MediaStreamTrackInterface::kAudioKind
1229 ? cricket::MEDIA_TYPE_AUDIO
1230 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231231 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1232 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501233 std::string sender_id = track->id();
1234 // Avoid creating a sender with an existing ID by generating a random ID.
1235 // This can happen if this is the second time AddTrack has created a sender
1236 // for this track.
1237 if (FindSenderById(sender_id)) {
1238 sender_id = rtc::CreateRandomUuid();
1239 }
1240 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061241 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1242 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571243 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121244 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571245 }
Steve Antonf9381f02017-12-14 18:23:571246 return transceiver->sender();
1247}
1248
1249rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1250PeerConnection::FindFirstTransceiverForAddedTrack(
1251 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1252 RTC_DCHECK(track);
1253 for (auto transceiver : transceivers_) {
1254 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081255 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571256 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421257 !transceiver->internal()->has_ever_been_used_to_send() &&
1258 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571259 return transceiver;
1260 }
1261 }
1262 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421263}
1264
1265bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1266 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331267 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571268}
1269
Steve Anton24db5732018-07-23 17:27:331270RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571271 rtc::scoped_refptr<RtpSenderInterface> sender) {
1272 if (!sender) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1274 }
deadbeefe1f9d832016-01-14 23:35:421275 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1277 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421278 }
Steve Antonf9381f02017-12-14 18:23:571279 if (IsUnifiedPlan()) {
1280 auto transceiver = FindTransceiverBySender(sender);
1281 if (!transceiver || !sender->track()) {
1282 return RTCError::OK();
1283 }
1284 sender->SetTrack(nullptr);
1285 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121286 transceiver->internal()->set_direction(
1287 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571288 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571291 }
Steve Anton4171afb2017-11-20 18:20:221292 } else {
Steve Antonf9381f02017-12-14 18:23:571293 bool removed;
1294 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1295 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1296 } else {
1297 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1298 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1299 }
1300 if (!removed) {
1301 LOG_AND_RETURN_ERROR(
1302 RTCErrorType::INVALID_PARAMETER,
1303 "Couldn't find sender " + sender->id() + " to remove.");
1304 }
Steve Anton4171afb2017-11-20 18:20:221305 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161306 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571307 return RTCError::OK();
1308}
1309
1310rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1311PeerConnection::FindTransceiverBySender(
1312 rtc::scoped_refptr<RtpSenderInterface> sender) {
1313 for (auto transceiver : transceivers_) {
1314 if (transceiver->sender() == sender) {
1315 return transceiver;
1316 }
1317 }
1318 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421319}
1320
Steve Anton9158ef62017-11-27 21:01:521321RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1322PeerConnection::AddTransceiver(
1323 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1324 return AddTransceiver(track, RtpTransceiverInit());
1325}
1326
1327RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1328PeerConnection::AddTransceiver(
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1330 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581331 RTC_CHECK(IsUnifiedPlan())
1332 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521333 if (!track) {
1334 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1335 }
1336 cricket::MediaType media_type;
1337 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1338 media_type = cricket::MEDIA_TYPE_AUDIO;
1339 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1340 media_type = cricket::MEDIA_TYPE_VIDEO;
1341 } else {
1342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1343 "Track kind is not audio or video");
1344 }
1345 return AddTransceiver(media_type, track, init);
1346}
1347
1348RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1349PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1350 return AddTransceiver(media_type, RtpTransceiverInit());
1351}
1352
1353RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1354PeerConnection::AddTransceiver(cricket::MediaType media_type,
1355 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581356 RTC_CHECK(IsUnifiedPlan())
1357 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521358 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1359 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1361 "media type is not audio or video");
1362 }
1363 return AddTransceiver(media_type, nullptr, init);
1364}
1365
1366RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1367PeerConnection::AddTransceiver(
1368 cricket::MediaType media_type,
1369 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071370 const RtpTransceiverInit& init,
1371 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521372 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1373 media_type == cricket::MEDIA_TYPE_VIDEO));
1374 if (track) {
1375 RTC_DCHECK_EQ(media_type,
1376 (track->kind() == MediaStreamTrackInterface::kAudioKind
1377 ? cricket::MEDIA_TYPE_AUDIO
1378 : cricket::MEDIA_TYPE_VIDEO));
1379 }
1380
1381 // TODO(bugs.webrtc.org/7600): Verify init.
1382
Steve Anton3d954a62018-04-02 18:27:231383 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1384 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501385 // Set the sender ID equal to the track ID if the track is specified unless
1386 // that sender ID is already in use.
1387 std::string sender_id =
1388 (track && !FindSenderById(track->id()) ? track->id()
1389 : rtc::CreateRandomUuid());
1390 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061391 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1392 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1393 transceiver->internal()->set_direction(init.direction);
1394
Steve Anton22da89f2018-01-25 21:58:071395 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161396 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071397 }
Steve Antonf9381f02017-12-14 18:23:571398
1399 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1400}
1401
Steve Anton02ee47c2018-01-11 00:26:061402rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1403PeerConnection::CreateSender(
1404 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361405 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061406 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101407 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 21:01:521408 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061409 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1410 RTC_DCHECK(!track ||
1411 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1412 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1413 signaling_thread(),
Steve Anton111fdfd2018-06-25 20:03:361414 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341415 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061416 } else {
1417 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1418 RTC_DCHECK(!track ||
1419 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1420 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 20:03:361421 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341422 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061423 }
Steve Anton111fdfd2018-06-25 20:03:361424 bool set_track_succeeded = sender->SetTrack(track);
1425 RTC_DCHECK(set_track_succeeded);
1426 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061427 return sender;
1428}
1429
1430rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1431PeerConnection::CreateReceiver(cricket::MediaType media_type,
1432 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521433 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1434 receiver;
Steve Anton9158ef62017-11-27 21:01:521435 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521436 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531437 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1438 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341439 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521440 } else {
Steve Anton02ee47c2018-01-11 00:26:061441 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521442 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531443 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1444 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341445 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521446 }
Steve Anton02ee47c2018-01-11 00:26:061447 return receiver;
1448}
1449
1450rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1451PeerConnection::CreateAndAddTransceiver(
1452 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1453 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1454 receiver) {
Steve Anton07563732018-06-26 18:13:501455 // Ensure that the new sender does not have an ID that is already in use by
1456 // another sender.
1457 // Allow receiver IDs to conflict since those come from remote SDP (which
1458 // could be invalid, but should not cause a crash).
1459 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-11 00:26:061460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571465 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521466}
1467
Steve Anton52d86772018-02-20 23:48:121468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 08:50:161471 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121472}
1473
deadbeeffac06552015-11-25 19:26:011474rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441475 const std::string& kind,
1476 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581477 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1478 "Plan SdpSemantics. Please use AddTransceiver "
1479 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171480 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251481 if (IsClosed()) {
1482 return nullptr;
1483 }
Steve Anton4171afb2017-11-20 18:20:221484
Seth Hampson5b4f0752018-04-02 23:31:361485 // Internally we need to have one stream with Plan B semantics, so we
1486 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101487 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361488 if (stream_id.empty()) {
1489 stream_ids.push_back(rtc::CreateRandomUuid());
1490 RTC_LOG(LS_INFO)
1491 << "No stream_id specified for sender. Generated stream ID: "
1492 << stream_ids[0];
1493 } else {
Seth Hampson845e8782018-03-02 19:34:101494 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061495 }
1496
Steve Anton4171afb2017-11-20 18:20:221497 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391498 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011499 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 20:03:361500 auto* audio_sender = new AudioRtpSender(
1501 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 23:19:501502 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391503 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061504 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221505 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011506 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351507 auto* video_sender =
Steve Anton111fdfd2018-06-25 20:03:361508 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 23:19:501509 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391510 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061511 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221512 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011513 } else {
Mirko Bonadei675513b2017-11-09 10:09:251514 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221515 return nullptr;
deadbeeffac06552015-11-25 19:26:011516 }
Steve Anton111fdfd2018-06-25 20:03:361517 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221518
deadbeefe1f9d832016-01-14 23:35:421519 return new_sender;
deadbeeffac06552015-11-25 19:26:011520}
1521
deadbeef70ab1a12015-09-28 23:53:551522std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1523 const {
deadbeefa601f5c2016-06-06 21:27:391524 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221525 for (auto sender : GetSendersInternal()) {
1526 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391527 }
1528 return ret;
deadbeef70ab1a12015-09-28 23:53:551529}
1530
Steve Anton4171afb2017-11-20 18:20:221531std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1532PeerConnection::GetSendersInternal() const {
1533 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1534 all_senders;
1535 for (auto transceiver : transceivers_) {
1536 auto senders = transceiver->internal()->senders();
1537 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1538 }
1539 return all_senders;
1540}
1541
deadbeef70ab1a12015-09-28 23:53:551542std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1543PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391544 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221545 for (const auto& receiver : GetReceiversInternal()) {
1546 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391547 }
1548 return ret;
deadbeef70ab1a12015-09-28 23:53:551549}
1550
Steve Anton4171afb2017-11-20 18:20:221551std::vector<
1552 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1553PeerConnection::GetReceiversInternal() const {
1554 std::vector<
1555 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1556 all_receivers;
1557 for (auto transceiver : transceivers_) {
1558 auto receivers = transceiver->internal()->receivers();
1559 all_receivers.insert(all_receivers.end(), receivers.begin(),
1560 receivers.end());
1561 }
1562 return all_receivers;
1563}
1564
Steve Anton9158ef62017-11-27 21:01:521565std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1566PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581567 RTC_CHECK(IsUnifiedPlan())
1568 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521569 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1570 for (auto transceiver : transceivers_) {
1571 all_transceivers.push_back(transceiver);
1572 }
1573 return all_transceivers;
1574}
1575
henrike@webrtc.org28e20752013-07-10 00:45:361576bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491577 MediaStreamTrackInterface* track,
1578 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171579 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281580 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561581 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251582 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361583 return false;
1584 }
1585
tommi@webrtc.org03505bc2014-07-14 20:15:261586 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151587 // The StatsCollector is used to tell if a track is valid because it may
1588 // remember tracks that the PeerConnection previously removed.
1589 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251590 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1591 << track->id();
zhihuange9e94c32016-11-04 18:38:151592 return false;
1593 }
Steve Antonad182762018-09-05 20:22:401594 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1595 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361596 return true;
1597}
1598
hbos74e1a4f2016-09-16 06:33:011599void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201600 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011601 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201602 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011603 stats_collector_->GetStatsReport(callback);
1604}
1605
Henrik Boström1df1bf82018-03-20 12:24:201606void PeerConnection::GetStats(
1607 rtc::scoped_refptr<RtpSenderInterface> selector,
1608 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1609 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1610 RTC_DCHECK(callback);
1611 RTC_DCHECK(stats_collector_);
1612 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1613 if (selector) {
1614 for (const auto& proxy_transceiver : transceivers_) {
1615 for (const auto& proxy_sender :
1616 proxy_transceiver->internal()->senders()) {
1617 if (proxy_sender == selector) {
1618 internal_sender = proxy_sender->internal();
1619 break;
1620 }
1621 }
1622 if (internal_sender)
1623 break;
1624 }
1625 }
1626 // If there is no |internal_sender| then |selector| is either null or does not
1627 // belong to the PeerConnection (in Plan B, senders can be removed from the
1628 // PeerConnection). This means that "all the stats objects representing the
1629 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1630 // produces an empty stats report.
1631 stats_collector_->GetStatsReport(internal_sender, callback);
1632}
1633
1634void PeerConnection::GetStats(
1635 rtc::scoped_refptr<RtpReceiverInterface> selector,
1636 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1637 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1638 RTC_DCHECK(callback);
1639 RTC_DCHECK(stats_collector_);
1640 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1641 if (selector) {
1642 for (const auto& proxy_transceiver : transceivers_) {
1643 for (const auto& proxy_receiver :
1644 proxy_transceiver->internal()->receivers()) {
1645 if (proxy_receiver == selector) {
1646 internal_receiver = proxy_receiver->internal();
1647 break;
1648 }
1649 }
1650 if (internal_receiver)
1651 break;
1652 }
1653 }
1654 // If there is no |internal_receiver| then |selector| is either null or does
1655 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1656 // the PeerConnection). This means that "all the stats objects representing
1657 // the selector" is an empty set. Invoking GetStatsReport() with a null
1658 // selector produces an empty stats report.
1659 stats_collector_->GetStatsReport(internal_receiver, callback);
1660}
1661
henrike@webrtc.org28e20752013-07-10 00:45:361662PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1663 return signaling_state_;
1664}
1665
henrike@webrtc.org28e20752013-07-10 00:45:361666PeerConnectionInterface::IceConnectionState
1667PeerConnection::ice_connection_state() {
1668 return ice_connection_state_;
1669}
1670
1671PeerConnectionInterface::IceGatheringState
1672PeerConnection::ice_gathering_state() {
1673 return ice_gathering_state_;
1674}
1675
Yves Gerey665174f2018-06-19 13:03:051676rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361677 const std::string& label,
1678 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171679 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501680
deadbeefab9b2d12015-10-14 18:33:111681 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111682
kwibergd1fe2812016-04-27 13:47:291683 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581684 if (config) {
1685 internal_config.reset(new InternalDataChannelInit(*config));
1686 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521687 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111688 InternalCreateDataChannel(label, internal_config.get()));
1689 if (!channel.get()) {
1690 return nullptr;
1691 }
henrike@webrtc.org28e20752013-07-10 00:45:361692
jiayl@webrtc.org001fd2d2014-05-29 15:31:111693 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1694 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171695 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161696 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111697 }
Harald Alvestrand8ebba742018-05-31 12:00:341698 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361699 return DataChannelProxy::Create(signaling_thread(), channel.get());
1700}
1701
1702void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161703 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171704 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511705
nisse7ce109a2017-01-31 08:57:561706 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251707 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161708 return;
1709 }
deadbeefab9b2d12015-10-14 18:33:111710
Steve Anton8d3444d2017-10-20 22:30:511711 if (IsClosed()) {
1712 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251713 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031714 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101715 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511716 return;
1717 }
1718
zhihuang1c378ed2017-08-17 21:10:501719 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111720 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251721 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031722 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101723 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111724 return;
1725 }
1726
Steve Anton22da89f2018-01-25 21:58:071727 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1728 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1729 if (IsUnifiedPlan()) {
1730 RTCError error = HandleLegacyOfferOptions(options);
1731 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031732 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071733 return;
1734 }
1735 }
1736
zhihuang1c378ed2017-08-17 21:10:501737 cricket::MediaSessionOptions session_options;
1738 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291739 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361740}
1741
Steve Anton22da89f2018-01-25 21:58:071742RTCError PeerConnection::HandleLegacyOfferOptions(
1743 const RTCOfferAnswerOptions& options) {
1744 RTC_DCHECK(IsUnifiedPlan());
1745
1746 if (options.offer_to_receive_audio == 0) {
1747 RemoveRecvDirectionFromReceivingTransceiversOfType(
1748 cricket::MEDIA_TYPE_AUDIO);
1749 } else if (options.offer_to_receive_audio == 1) {
1750 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1751 } else if (options.offer_to_receive_audio > 1) {
1752 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1753 "offer_to_receive_audio > 1 is not supported.");
1754 }
1755
1756 if (options.offer_to_receive_video == 0) {
1757 RemoveRecvDirectionFromReceivingTransceiversOfType(
1758 cricket::MEDIA_TYPE_VIDEO);
1759 } else if (options.offer_to_receive_video == 1) {
1760 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1761 } else if (options.offer_to_receive_video > 1) {
1762 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1763 "offer_to_receive_video > 1 is not supported.");
1764 }
1765
1766 return RTCError::OK();
1767}
1768
1769void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1770 cricket::MediaType media_type) {
1771 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231772 RtpTransceiverDirection new_direction =
1773 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1774 if (new_direction != transceiver->direction()) {
1775 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1776 << " transceiver (MID="
1777 << transceiver->mid().value_or("<not set>") << ") from "
1778 << RtpTransceiverDirectionToString(
1779 transceiver->direction())
1780 << " to "
1781 << RtpTransceiverDirectionToString(new_direction)
1782 << " since CreateOffer specified offer_to_receive=0";
1783 transceiver->internal()->set_direction(new_direction);
1784 }
Steve Anton22da89f2018-01-25 21:58:071785 }
1786}
1787
1788void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1789 cricket::MediaType media_type) {
1790 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231791 RTC_LOG(LS_INFO)
1792 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1793 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071794 RtpTransceiverInit init;
1795 init.direction = RtpTransceiverDirection::kRecvOnly;
1796 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1797 }
1798}
1799
1800std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1801PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1802 std::vector<
1803 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1804 receiving_transceivers;
1805 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081806 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071807 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1808 receiving_transceivers.push_back(transceiver);
1809 }
1810 }
1811 return receiving_transceivers;
1812}
1813
htaa2a49d92016-03-04 10:51:391814void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1815 const RTCOfferAnswerOptions& options) {
1816 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561817 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251818 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391819 return;
1820 }
1821
Steve Antondffead82018-02-06 18:31:291822 if (!(signaling_state_ == kHaveRemoteOffer ||
1823 signaling_state_ == kHaveLocalPrAnswer)) {
1824 std::string error =
1825 "PeerConnection cannot create an answer in a state other than "
1826 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251827 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031828 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101829 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511830 return;
1831 }
1832
Steve Antondffead82018-02-06 18:31:291833 // The remote description should be set if we're in the right state.
1834 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511835
Steve Anton22da89f2018-01-25 21:58:071836 if (IsUnifiedPlan()) {
1837 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1838 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1839 "supported with Unified Plan semantics. Use the "
1840 "RtpTransceiver API instead.";
1841 }
1842 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1843 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1844 "supported with Unified Plan semantics. Use the "
1845 "RtpTransceiver API instead.";
1846 }
1847 }
1848
htaa2a49d92016-03-04 10:51:391849 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501850 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391851
Steve Antond25da372017-11-06 22:50:291852 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361853}
1854
1855void PeerConnection::SetLocalDescription(
1856 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421857 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171858 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561859
Steve Anton80dd7b52018-02-17 01:08:421860 // The SetLocalDescription contract is that we take ownership of the session
1861 // description regardless of the outcome, so wrap it in a unique_ptr right
1862 // away. Ideally, SetLocalDescription's signature will be changed to take the
1863 // description as a unique_ptr argument to formalize this agreement.
1864 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1865
nisse7ce109a2017-01-31 08:57:561866 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251867 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361868 return;
1869 }
Steve Anton8a006912017-12-04 23:25:561870
henrike@webrtc.org28e20752013-07-10 00:45:361871 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031872 PostSetSessionDescriptionFailure(
1873 observer,
1874 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361875 return;
1876 }
Steve Anton8d3444d2017-10-20 22:30:511877
Steve Anton80dd7b52018-02-17 01:08:421878 // If a session error has occurred the PeerConnection is in a possibly
1879 // inconsistent state so fail right away.
1880 if (session_error() != SessionError::kNone) {
1881 std::string error_message = GetSessionErrorMsg();
1882 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031883 PostSetSessionDescriptionFailure(
1884 observer,
1885 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421886 return;
1887 }
Steve Anton8d3444d2017-10-20 22:30:511888
Steve Anton80dd7b52018-02-17 01:08:421889 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1890 if (!error.ok()) {
1891 std::string error_message = GetSetDescriptionErrorMessage(
1892 cricket::CS_LOCAL, desc->GetType(), error);
1893 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031894 PostSetSessionDescriptionFailure(
1895 observer,
1896 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421897 return;
1898 }
1899
1900 // Grab the description type before moving ownership to ApplyLocalDescription,
1901 // which may destroy it before returning.
1902 const SdpType type = desc->GetType();
1903
1904 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561905 // |desc| may be destroyed at this point.
1906
1907 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421908 // If ApplyLocalDescription fails, the PeerConnection could be in an
1909 // inconsistent state, so act conservatively here and set the session error
1910 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1911 SetSessionError(SessionError::kContent, error.message());
1912 std::string error_message =
1913 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1914 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031915 PostSetSessionDescriptionFailure(
1916 observer,
1917 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511918 return;
1919 }
Steve Anton8a006912017-12-04 23:25:561920 RTC_DCHECK(local_description());
1921
1922 PostSetSessionDescriptionSuccess(observer);
1923
Steve Antonad182762018-09-05 20:22:401924 // MaybeStartGathering needs to be called after posting
1925 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1926 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 23:25:561927 transport_controller_->MaybeStartGathering();
1928
Steve Antona3a92c22017-12-07 18:27:411929 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561930 // TODO(deadbeef): We already had to hop to the network thread for
1931 // MaybeStartGathering...
1932 network_thread()->Invoke<void>(
1933 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1934 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:301935 // Make UMA notes about what was agreed to.
1936 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:561937 }
Harald Alvestrand8ebba742018-05-31 12:00:341938 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:561939}
1940
1941RTCError PeerConnection::ApplyLocalDescription(
1942 std::unique_ptr<SessionDescriptionInterface> desc) {
1943 RTC_DCHECK_RUN_ON(signaling_thread());
1944 RTC_DCHECK(desc);
1945
henrike@webrtc.org28e20752013-07-10 00:45:361946 // Update stats here so that we have the most recent stats for tracks and
1947 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:261948 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:561949
Steve Antondcc3c022017-12-23 00:02:541950 // Take a reference to the old local description since it's used below to
1951 // compare against the new local description. When setting the new local
1952 // description, grab ownership of the replaced session description in case it
1953 // is the same as |old_local_description|, to keep it alive for the duration
1954 // of the method.
1955 const SessionDescriptionInterface* old_local_description =
1956 local_description();
1957 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:351958 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:511959 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:541960 replaced_local_description = pending_local_description_
1961 ? std::move(pending_local_description_)
1962 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:561963 current_local_description_ = std::move(desc);
1964 pending_local_description_ = nullptr;
1965 current_remote_description_ = std::move(pending_remote_description_);
1966 } else {
Steve Antondcc3c022017-12-23 00:02:541967 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:561968 pending_local_description_ = std::move(desc);
1969 }
1970 // The session description to apply now must be accessed by
1971 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:441972 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:111973
Zhi Huange830e682018-03-30 17:48:351974 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1975 if (!error.ok()) {
1976 return error;
1977 }
1978
Steve Antondcc3c022017-12-23 00:02:541979 if (IsUnifiedPlan()) {
1980 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:481981 cricket::CS_LOCAL, *local_description(), old_local_description,
1982 remote_description());
Steve Anton8a006912017-12-04 23:25:561983 if (!error.ok()) {
1984 return error;
1985 }
Steve Anton0f5400a2018-07-17 21:25:361986 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1987 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:541988 for (auto transceiver : transceivers_) {
1989 const ContentInfo* content =
1990 FindMediaSectionForTransceiver(transceiver, local_description());
1991 if (!content) {
1992 continue;
1993 }
1994 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 21:25:361995 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1996 // the following steps:
Steve Antondcc3c022017-12-23 00:02:541997 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:361998 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1999 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2000 // "recvonly", process the removal of a remote track for the media
2001 // description, given transceiver, removeList, and muteTracks.
2002 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2003 (transceiver->internal()->fired_direction() &&
2004 RtpTransceiverDirectionHasRecv(
2005 *transceiver->internal()->fired_direction()))) {
2006 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2007 &removed_streams);
2008 }
2009 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2010 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-23 00:02:542011 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362012 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542013 }
Steve Anton0f5400a2018-07-17 21:25:362014 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162015 auto observer = Observer();
Steve Anton0f5400a2018-07-17 21:25:362016 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162017 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362018 }
2019 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162020 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542021 }
2022 } else {
Zhi Huange830e682018-03-30 17:48:352023 // Media channels will be created only when offer is set. These may use new
2024 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542025 if (type == SdpType::kOffer) {
2026 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2027 // description is applied. Restore back to old description.
2028 RTCError error = CreateChannels(*local_description()->description());
2029 if (!error.ok()) {
2030 return error;
2031 }
2032 }
Steve Antondcc3c022017-12-23 00:02:542033 // Remove unused channels if MediaContentDescription is rejected.
2034 RemoveUnusedChannels(local_description()->description());
2035 }
Steve Anton8a006912017-12-04 23:25:562036
Zhi Huange830e682018-03-30 17:48:352037 error = UpdateSessionState(type, cricket::CS_LOCAL,
2038 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562039 if (!error.ok()) {
2040 return error;
2041 }
Steve Antondcc3c022017-12-23 00:02:542042
Steve Anton8a006912017-12-04 23:25:562043 if (remote_description()) {
2044 // Now that we have a local description, we can push down remote candidates.
2045 UseCandidatesInSessionDescription(remote_description());
2046 }
2047
2048 pending_ice_restarts_.clear();
2049 if (session_error() != SessionError::kNone) {
2050 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2051 }
2052
deadbeefab9b2d12015-10-14 18:33:112053 // If setting the description decided our SSL role, allocate any necessary
2054 // SCTP sids.
2055 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172056 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112057 AllocateSctpSids(role);
2058 }
2059
Steve Antond3679212018-01-18 01:41:022060 if (IsUnifiedPlan()) {
2061 for (auto transceiver : transceivers_) {
2062 const ContentInfo* content =
2063 FindMediaSectionForTransceiver(transceiver, local_description());
2064 if (!content) {
2065 continue;
2066 }
Steve Anton74255ff2018-01-25 02:32:572067 const auto& streams = content->media_description()->streams();
2068 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022069 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102070 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022071 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572072 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272073 } else {
2074 // 0 is a special value meaning "this sender has no associated send
2075 // stream". Need to call this so the sender won't attempt to configure
2076 // a no longer existing stream and run into DCHECKs in the lower
2077 // layers.
2078 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-18 01:41:022079 }
2080 }
2081 } else {
2082 // Plan B semantics.
2083
Steve Antondcc3c022017-12-23 00:02:542084 // Update state and SSRC of local MediaStreams and DataChannels based on the
2085 // local session description.
2086 const cricket::ContentInfo* audio_content =
2087 GetFirstAudioContent(local_description()->description());
2088 if (audio_content) {
2089 if (audio_content->rejected) {
2090 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2091 } else {
2092 const cricket::AudioContentDescription* audio_desc =
2093 audio_content->media_description()->as_audio();
2094 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2095 }
deadbeeffaac4972015-11-12 23:33:072096 }
deadbeefab9b2d12015-10-14 18:33:112097
Steve Antondcc3c022017-12-23 00:02:542098 const cricket::ContentInfo* video_content =
2099 GetFirstVideoContent(local_description()->description());
2100 if (video_content) {
2101 if (video_content->rejected) {
2102 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2103 } else {
2104 const cricket::VideoContentDescription* video_desc =
2105 video_content->media_description()->as_video();
2106 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2107 }
deadbeeffaac4972015-11-12 23:33:072108 }
deadbeefab9b2d12015-10-14 18:33:112109 }
2110
2111 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442112 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112113 if (data_content) {
2114 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302115 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112116 if (rtc::starts_with(data_desc->protocol().data(),
2117 cricket::kMediaProtocolRtpPrefix)) {
2118 UpdateLocalRtpDataChannels(data_desc->streams());
2119 }
2120 }
2121
Steve Anton8a006912017-12-04 23:25:562122 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362123}
2124
2125void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072126 SetSessionDescriptionObserver* observer,
2127 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322128 SetRemoteDescription(
2129 std::unique_ptr<SessionDescriptionInterface>(desc),
2130 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2131 new SetRemoteDescriptionObserverAdapter(this, observer)));
2132}
2133
2134void PeerConnection::SetRemoteDescription(
2135 std::unique_ptr<SessionDescriptionInterface> desc,
2136 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172137 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562138
nisse7ce109a2017-01-31 08:57:562139 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252140 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362141 return;
2142 }
Steve Anton8a006912017-12-04 23:25:562143
henrike@webrtc.org28e20752013-07-10 00:45:362144 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322145 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562146 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362147 return;
2148 }
Steve Anton8d3444d2017-10-20 22:30:512149
Steve Anton80dd7b52018-02-17 01:08:422150 // If a session error has occurred the PeerConnection is in a possibly
2151 // inconsistent state so fail right away.
2152 if (session_error() != SessionError::kNone) {
2153 std::string error_message = GetSessionErrorMsg();
2154 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2155 observer->OnSetRemoteDescriptionComplete(
2156 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2157 return;
2158 }
Steve Anton71439a62018-02-15 19:53:062159
Steve Antonba42e992018-04-09 21:10:012160 if (desc->GetType() == SdpType::kOffer) {
2161 // Report to UMA the format of the received offer.
2162 ReportSdpFormatReceived(*desc);
2163 }
2164
Steve Anton80dd7b52018-02-17 01:08:422165 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062166 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422167 std::string error_message = GetSetDescriptionErrorMessage(
2168 cricket::CS_REMOTE, desc->GetType(), error);
2169 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062170 observer->OnSetRemoteDescriptionComplete(
2171 RTCError(error.type(), std::move(error_message)));
2172 return;
2173 }
Steve Anton71439a62018-02-15 19:53:062174
Steve Anton80dd7b52018-02-17 01:08:422175 // Grab the description type before moving ownership to
2176 // ApplyRemoteDescription, which may destroy it before returning.
2177 const SdpType type = desc->GetType();
2178
2179 error = ApplyRemoteDescription(std::move(desc));
2180 // |desc| may be destroyed at this point.
2181
2182 if (!error.ok()) {
2183 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2184 // inconsistent state, so act conservatively here and set the session error
2185 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2186 SetSessionError(SessionError::kContent, error.message());
2187 std::string error_message =
2188 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2189 RTC_LOG(LS_ERROR) << error_message;
2190 observer->OnSetRemoteDescriptionComplete(
2191 RTCError(error.type(), std::move(error_message)));
2192 return;
2193 }
2194 RTC_DCHECK(remote_description());
2195
2196 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562197 // TODO(deadbeef): We already had to hop to the network thread for
2198 // MaybeStartGathering...
2199 network_thread()->Invoke<void>(
2200 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2201 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002202 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302203 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562204 }
2205
2206 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342207 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562208}
2209
2210RTCError PeerConnection::ApplyRemoteDescription(
2211 std::unique_ptr<SessionDescriptionInterface> desc) {
2212 RTC_DCHECK_RUN_ON(signaling_thread());
2213 RTC_DCHECK(desc);
2214
henrike@webrtc.org28e20752013-07-10 00:45:362215 // Update stats here so that we have the most recent stats for tracks and
2216 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262217 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562218
Steve Antondcc3c022017-12-23 00:02:542219 // Take a reference to the old remote description since it's used below to
2220 // compare against the new remote description. When setting the new remote
2221 // description, grab ownership of the replaced session description in case it
2222 // is the same as |old_remote_description|, to keep it alive for the duration
2223 // of the method.
Steve Anton8a006912017-12-04 23:25:562224 const SessionDescriptionInterface* old_remote_description =
2225 remote_description();
Steve Anton8a006912017-12-04 23:25:562226 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512227 SdpType type = desc->GetType();
2228 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562229 replaced_remote_description = pending_remote_description_
2230 ? std::move(pending_remote_description_)
2231 : std::move(current_remote_description_);
2232 current_remote_description_ = std::move(desc);
2233 pending_remote_description_ = nullptr;
2234 current_local_description_ = std::move(pending_local_description_);
2235 } else {
2236 replaced_remote_description = std::move(pending_remote_description_);
2237 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362238 }
Steve Anton8a006912017-12-04 23:25:562239 // The session description to apply now must be accessed by
2240 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442241 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362242
Zhi Huange830e682018-03-30 17:48:352243 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2244 if (!error.ok()) {
2245 return error;
2246 }
Steve Anton8a006912017-12-04 23:25:562247 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542248 if (IsUnifiedPlan()) {
2249 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482250 cricket::CS_REMOTE, *remote_description(), local_description(),
2251 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562252 if (!error.ok()) {
2253 return error;
2254 }
Steve Antondcc3c022017-12-23 00:02:542255 } else {
Zhi Huange830e682018-03-30 17:48:352256 // Media channels will be created only when offer is set. These may use new
2257 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542258 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352259 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542260 // description is applied. Restore back to old description.
2261 RTCError error = CreateChannels(*remote_description()->description());
2262 if (!error.ok()) {
2263 return error;
2264 }
2265 }
Steve Antondcc3c022017-12-23 00:02:542266 // Remove unused channels if MediaContentDescription is rejected.
2267 RemoveUnusedChannels(remote_description()->description());
2268 }
Steve Anton8a006912017-12-04 23:25:562269
Zhi Huange830e682018-03-30 17:48:352270 // NOTE: Candidates allocation will be initiated only when
2271 // SetLocalDescription is called.
2272 error = UpdateSessionState(type, cricket::CS_REMOTE,
2273 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562274 if (!error.ok()) {
2275 return error;
2276 }
2277
2278 if (local_description() &&
2279 !UseCandidatesInSessionDescription(remote_description())) {
2280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2281 }
2282
2283 if (old_remote_description) {
2284 for (const cricket::ContentInfo& content :
2285 old_remote_description->description()->contents()) {
2286 // Check if this new SessionDescription contains new ICE ufrag and
2287 // password that indicates the remote peer requests an ICE restart.
2288 // TODO(deadbeef): When we start storing both the current and pending
2289 // remote description, this should reset pending_ice_restarts and compare
2290 // against the current description.
2291 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2292 content.name)) {
Steve Anton3828c062017-12-06 18:34:512293 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562294 pending_ice_restarts_.insert(content.name);
2295 }
2296 } else {
2297 // We retain all received candidates only if ICE is not restarted.
2298 // When ICE is restarted, all previous candidates belong to an old
2299 // generation and should not be kept.
2300 // TODO(deadbeef): This goes against the W3C spec which says the remote
2301 // description should only contain candidates from the last set remote
2302 // description plus any candidates added since then. We should remove
2303 // this once we're sure it won't break anything.
2304 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2305 old_remote_description, content.name, mutable_remote_description());
2306 }
2307 }
2308 }
2309
2310 if (session_error() != SessionError::kNone) {
2311 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2312 }
2313
2314 // Set the the ICE connection state to connecting since the connection may
2315 // become writable with peer reflexive candidates before any remote candidate
2316 // is signaled.
2317 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2318 // is to have a new signal the indicates a change in checking state from the
2319 // transport and expose a new checking() member from transport that can be
2320 // read to determine the current checking state. The existing SignalConnecting
2321 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412322 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172323 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562324 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2325 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2326 }
2327
deadbeefab9b2d12015-10-14 18:33:112328 // If setting the description decided our SSL role, allocate any necessary
2329 // SCTP sids.
2330 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172331 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112332 AllocateSctpSids(role);
2333 }
2334
Steve Antondcc3c022017-12-23 00:02:542335 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422336 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182337 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362338 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132339 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182340 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542341 for (auto transceiver : transceivers_) {
2342 const ContentInfo* content =
2343 FindMediaSectionForTransceiver(transceiver, remote_description());
2344 if (!content) {
2345 continue;
2346 }
2347 const MediaContentDescription* media_desc = content->media_description();
2348 RtpTransceiverDirection local_direction =
2349 RtpTransceiverDirectionReversed(media_desc->direction());
2350 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2351 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2352 // transceiver's current direction is neither sendrecv nor recvonly,
2353 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362354 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422355 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332356 // The remote description has signaled the stream IDs.
2357 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422358 }
Steve Antondcc3c022017-12-23 00:02:542359 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362360 (!transceiver->fired_direction() ||
2361 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232362 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362363 << content->name << " (added to "
2364 << GetStreamIdsString(stream_ids) << ").";
2365
2366 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2367 for (const std::string& stream_id : stream_ids) {
2368 rtc::scoped_refptr<MediaStreamInterface> stream =
2369 remote_streams_->find(stream_id);
2370 if (!stream) {
2371 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2372 MediaStream::Create(stream_id));
2373 remote_streams_->AddStream(stream);
2374 added_streams.push_back(stream);
2375 }
2376 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202377 }
Steve Anton3172c032018-05-03 22:30:182378 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 18:51:532379 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2380 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 23:31:362381 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 22:30:182382 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542383 }
Steve Anton0f5400a2018-07-17 21:25:362384 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2385 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2386 // removal of a remote track for the media description, given transceiver,
2387 // removeList, and muteTracks.
Steve Antondcc3c022017-12-23 00:02:542388 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362389 (transceiver->fired_direction() &&
2390 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2391 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2392 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542393 }
Steve Anton0f5400a2018-07-17 21:25:362394 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2395 transceiver->internal()->set_fired_direction(local_direction);
2396 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2397 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542398 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362399 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2400 // direction.
Steve Antondcc3c022017-12-23 00:02:542401 transceiver->internal()->set_current_direction(local_direction);
2402 }
Steve Anton0f5400a2018-07-17 21:25:362403 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2404 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-23 00:02:542405 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232406 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2407 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542408 transceiver->Stop();
2409 }
Seth Hampson2f0d7022018-02-20 19:54:422410 if (!content->rejected &&
2411 RtpTransceiverDirectionHasRecv(local_direction)) {
2412 // Set ssrc to 0 in the case of an unsignalled ssrc.
2413 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332414 if (!media_desc->streams().empty() &&
2415 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422416 ssrc = media_desc->streams()[0].first_ssrc();
2417 }
2418 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022419 }
Steve Antondcc3c022017-12-23 00:02:542420 }
Steve Antonc49bcd92018-02-14 22:28:132421 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162422 auto observer = Observer();
Steve Anton3172c032018-05-03 22:30:182423 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162424 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162425 observer->OnTrack(transceiver);
2426 observer->OnAddTrack(transceiver->receiver(),
2427 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202428 }
Steve Antonc49bcd92018-02-14 22:28:132429 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162430 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132431 }
Steve Anton0f5400a2018-07-17 21:25:362432 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162433 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182434 }
2435 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162436 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182437 }
Steve Antondcc3c022017-12-23 00:02:542438 }
2439
Henrik Boströmfdb92012017-11-09 18:55:442440 const cricket::ContentInfo* audio_content =
2441 GetFirstAudioContent(remote_description()->description());
2442 const cricket::ContentInfo* video_content =
2443 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402444 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442445 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402446 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442447 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402448 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442449 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402450
2451 // Check if the descriptions include streams, just in case the peer supports
2452 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442453 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402454 (audio_desc && !audio_desc->streams().empty()) ||
2455 (video_desc && !video_desc->streams().empty())) {
2456 remote_peer_supports_msid_ = true;
2457 }
deadbeefab9b2d12015-10-14 18:33:112458
2459 // We wait to signal new streams until we finish processing the description,
2460 // since only at that point will new streams have all their tracks.
2461 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2462
Steve Antondcc3c022017-12-23 00:02:542463 if (!IsUnifiedPlan()) {
2464 // TODO(steveanton): When removing RTP senders/receivers in response to a
2465 // rejected media section, there is some cleanup logic that expects the
2466 // voice/ video channel to still be set. But in this method the voice/video
2467 // channel would have been destroyed by the SetRemoteDescription caller
2468 // above so the cleanup that relies on them fails to run. The RemoveSenders
2469 // calls should be moved to right before the DestroyChannel calls to fix
2470 // this.
Steve Anton8d3444d2017-10-20 22:30:512471
Steve Antondcc3c022017-12-23 00:02:542472 // Find all audio rtp streams and create corresponding remote AudioTracks
2473 // and MediaStreams.
2474 if (audio_content) {
2475 if (audio_content->rejected) {
2476 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2477 } else {
2478 bool default_audio_track_needed =
2479 !remote_peer_supports_msid_ &&
2480 RtpTransceiverDirectionHasSend(audio_desc->direction());
2481 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2482 default_audio_track_needed, audio_desc->type(),
2483 new_streams);
2484 }
deadbeeffaac4972015-11-12 23:33:072485 }
deadbeefab9b2d12015-10-14 18:33:112486
Steve Antondcc3c022017-12-23 00:02:542487 // Find all video rtp streams and create corresponding remote VideoTracks
2488 // and MediaStreams.
2489 if (video_content) {
2490 if (video_content->rejected) {
2491 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2492 } else {
2493 bool default_video_track_needed =
2494 !remote_peer_supports_msid_ &&
2495 RtpTransceiverDirectionHasSend(video_desc->direction());
2496 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2497 default_video_track_needed, video_desc->type(),
2498 new_streams);
2499 }
deadbeeffaac4972015-11-12 23:33:072500 }
deadbeefab9b2d12015-10-14 18:33:112501
Steve Antondcc3c022017-12-23 00:02:542502 // Update the DataChannels with the information from the remote peer.
2503 if (data_desc) {
2504 if (rtc::starts_with(data_desc->protocol().data(),
2505 cricket::kMediaProtocolRtpPrefix)) {
2506 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2507 }
deadbeefab9b2d12015-10-14 18:33:112508 }
deadbeefab9b2d12015-10-14 18:33:112509
Steve Antondcc3c022017-12-23 00:02:542510 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162511 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542512 for (size_t i = 0; i < new_streams->count(); ++i) {
2513 MediaStreamInterface* new_stream = new_streams->at(i);
2514 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:162515 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542516 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2517 }
deadbeefab9b2d12015-10-14 18:33:112518
Steve Antondcc3c022017-12-23 00:02:542519 UpdateEndedRemoteMediaStreams();
2520 }
deadbeefab9b2d12015-10-14 18:33:112521
Steve Anton8a006912017-12-04 23:25:562522 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332523}
2524
Steve Anton0f5400a2018-07-17 21:25:362525void PeerConnection::ProcessRemovalOfRemoteTrack(
2526 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2527 transceiver,
2528 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2529 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2530 RTC_DCHECK(transceiver->mid());
2531 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2532 << *transceiver->mid();
2533 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2534 transceiver->internal()->receiver_internal()->streams();
2535 // This will remove the remote track from the streams.
2536 transceiver->internal()->receiver_internal()->set_stream_ids({});
2537 remove_list->push_back(transceiver);
2538 // Remove any streams that no longer have tracks.
2539 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2540 // of streams, see if the stream was removed by checking if this was the
2541 // last receiver with that stream ID.
2542 for (auto stream : media_streams) {
2543 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2544 remote_streams_->RemoveStream(stream);
2545 removed_streams->push_back(stream);
2546 }
2547 }
2548}
2549
Steve Antondcc3c022017-12-23 00:02:542550RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2551 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482552 const SessionDescriptionInterface& new_session,
2553 const SessionDescriptionInterface* old_local_description,
2554 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542555 RTC_DCHECK(IsUnifiedPlan());
2556
Steve Anton7464fca2018-01-19 19:10:372557 const cricket::ContentGroup* bundle_group = nullptr;
2558 if (new_session.GetType() == SdpType::kOffer) {
2559 auto bundle_group_or_error =
2560 GetEarlyBundleGroup(*new_session.description());
2561 if (!bundle_group_or_error.ok()) {
2562 return bundle_group_or_error.MoveError();
2563 }
2564 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542565 }
Steve Antondcc3c022017-12-23 00:02:542566
Steve Antondcc3c022017-12-23 00:02:542567 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542568 for (size_t i = 0; i < new_contents.size(); ++i) {
2569 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542570 cricket::MediaType media_type = new_content.media_description()->type();
2571 seen_mids_.insert(new_content.name);
2572 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2573 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482574 const cricket::ContentInfo* old_local_content = nullptr;
2575 if (old_local_description &&
2576 i < old_local_description->description()->contents().size()) {
2577 old_local_content =
2578 &old_local_description->description()->contents()[i];
2579 }
2580 const cricket::ContentInfo* old_remote_content = nullptr;
2581 if (old_remote_description &&
2582 i < old_remote_description->description()->contents().size()) {
2583 old_remote_content =
2584 &old_remote_description->description()->contents()[i];
2585 }
Steve Antondcc3c022017-12-23 00:02:542586 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482587 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2588 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542589 if (!transceiver_or_error.ok()) {
2590 return transceiver_or_error.MoveError();
2591 }
2592 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542593 RTCError error =
2594 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2595 if (!error.ok()) {
2596 return error;
2597 }
2598 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232599 if (GetDataMid() && new_content.name != *GetDataMid()) {
2600 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232601 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2602 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232603 continue;
2604 }
2605 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2606 if (!error.ok()) {
2607 return error;
2608 }
Steve Antondcc3c022017-12-23 00:02:542609 } else {
2610 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2611 "Unknown section type.");
2612 }
2613 }
2614
2615 return RTCError::OK();
2616}
2617
2618RTCError PeerConnection::UpdateTransceiverChannel(
2619 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2620 transceiver,
2621 const cricket::ContentInfo& content,
2622 const cricket::ContentGroup* bundle_group) {
2623 RTC_DCHECK(IsUnifiedPlan());
2624 RTC_DCHECK(transceiver);
2625 cricket::BaseChannel* channel = transceiver->internal()->channel();
2626 if (content.rejected) {
2627 if (channel) {
2628 transceiver->internal()->SetChannel(nullptr);
2629 DestroyBaseChannel(channel);
2630 }
2631 } else {
2632 if (!channel) {
Steve Anton69470252018-02-09 19:43:082633 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352634 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542635 } else {
Steve Anton69470252018-02-09 19:43:082636 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352637 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542638 }
2639 if (!channel) {
2640 LOG_AND_RETURN_ERROR(
2641 RTCErrorType::INTERNAL_ERROR,
2642 "Failed to create channel for mid=" + content.name);
2643 }
2644 transceiver->internal()->SetChannel(channel);
2645 }
2646 }
2647 return RTCError::OK();
2648}
2649
Steve Antonfa2260d2017-12-29 00:38:232650RTCError PeerConnection::UpdateDataChannel(
2651 cricket::ContentSource source,
2652 const cricket::ContentInfo& content,
2653 const cricket::ContentGroup* bundle_group) {
2654 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402655 // If data channels are disabled, ignore this media section. CreateAnswer
2656 // will take care of rejecting it.
2657 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232658 }
2659 if (content.rejected) {
2660 DestroyDataChannel();
2661 } else {
2662 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:352663 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232664 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2665 "Failed to create data channel.");
2666 }
2667 }
2668 if (source == cricket::CS_REMOTE) {
2669 const MediaContentDescription* data_desc = content.media_description();
2670 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2671 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2672 }
2673 }
2674 }
2675 return RTCError::OK();
2676}
2677
Steve Antondcc3c022017-12-23 00:02:542678RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2679PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482680 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542681 size_t mline_index,
2682 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482683 const ContentInfo* old_local_content,
2684 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542685 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482686 // If this is an offer then the m= section might be recycled. If the m=
2687 // section is being recycled (defined as: rejected in the current local or
2688 // remote description and not rejected in new description), dissociate the
2689 // currently associated RtpTransceiver by setting its mid property to null,
2690 // and discard the mapping between the transceiver and its m= section index.
2691 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2692 old_remote_content)) {
2693 // We want to dissociate the transceiver that has the rejected mid.
2694 const std::string& old_mid =
2695 (old_local_content && old_local_content->rejected)
2696 ? old_local_content->name
2697 : old_remote_content->name;
2698 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542699 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232700 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2701 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:432702 old_transceiver->internal()->set_mid(absl::nullopt);
2703 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:542704 }
2705 }
2706 const MediaContentDescription* media_desc = content.media_description();
2707 auto transceiver = GetAssociatedTransceiver(content.name);
2708 if (source == cricket::CS_LOCAL) {
2709 // Find the RtpTransceiver that corresponds to this m= section, using the
2710 // mapping between transceivers and m= section indices established when
2711 // creating the offer.
2712 if (!transceiver) {
2713 transceiver = GetTransceiverByMLineIndex(mline_index);
2714 }
2715 if (!transceiver) {
2716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2717 "Unknown transceiver");
2718 }
2719 } else {
2720 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2721 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2722 // of the same type...
2723 if (!transceiver &&
2724 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2725 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2726 }
2727 // If no RtpTransceiver was found in the previous step, create one with a
2728 // recvonly direction.
2729 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232730 RTC_LOG(LS_INFO) << "Adding "
2731 << cricket::MediaTypeToString(media_desc->type())
2732 << " transceiver for MID=" << content.name
2733 << " at i=" << mline_index
2734 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 20:03:362735 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 21:04:012736 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 18:58:302737 std::string receiver_id;
2738 if (!media_desc->streams().empty()) {
2739 receiver_id = media_desc->streams()[0].id;
2740 } else {
2741 receiver_id = rtc::CreateRandomUuid();
2742 }
2743 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062744 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542745 transceiver->internal()->set_direction(
2746 RtpTransceiverDirection::kRecvOnly);
2747 }
2748 }
2749 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082750 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542751 LOG_AND_RETURN_ERROR(
2752 RTCErrorType::INVALID_PARAMETER,
2753 "Transceiver type does not match media description type.");
2754 }
2755 // Associate the found or created RtpTransceiver with the m= section by
2756 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2757 // section, and establish a mapping between the transceiver and the index of
2758 // the m= section.
2759 transceiver->internal()->set_mid(content.name);
2760 transceiver->internal()->set_mline_index(mline_index);
2761 return std::move(transceiver);
2762}
2763
2764rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2765PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2766 RTC_DCHECK(IsUnifiedPlan());
2767 for (auto transceiver : transceivers_) {
2768 if (transceiver->mid() == mid) {
2769 return transceiver;
2770 }
2771 }
2772 return nullptr;
2773}
2774
2775rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2776PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2777 RTC_DCHECK(IsUnifiedPlan());
2778 for (auto transceiver : transceivers_) {
2779 if (transceiver->internal()->mline_index() == mline_index) {
2780 return transceiver;
2781 }
2782 }
2783 return nullptr;
2784}
2785
2786rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2787PeerConnection::FindAvailableTransceiverToReceive(
2788 cricket::MediaType media_type) const {
2789 RTC_DCHECK(IsUnifiedPlan());
2790 // From JSEP section 5.10 (Applying a Remote Description):
2791 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2792 // the same type that were added to the PeerConnection by addTrack and are not
2793 // associated with any m= section and are not stopped, find the first such
2794 // RtpTransceiver.
2795 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082796 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542797 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2798 !transceiver->stopped()) {
2799 return transceiver;
2800 }
2801 }
2802 return nullptr;
2803}
2804
Steve Antoned10bd92017-12-05 18:52:592805const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2806 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2807 transceiver,
2808 const SessionDescriptionInterface* sdesc) const {
2809 RTC_DCHECK(transceiver);
2810 RTC_DCHECK(sdesc);
2811 if (IsUnifiedPlan()) {
2812 if (!transceiver->internal()->mid()) {
2813 // This transceiver is not associated with a media section yet.
2814 return nullptr;
2815 }
2816 return sdesc->description()->GetContentByName(
2817 *transceiver->internal()->mid());
2818 } else {
2819 // Plan B only allows at most one audio and one video section, so use the
2820 // first media section of that type.
2821 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082822 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592823 }
2824}
2825
deadbeef46c73892016-11-17 03:42:042826PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2827 return configuration_;
2828}
2829
deadbeef293e9262017-01-11 20:28:302830bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2831 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172832 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:102833 if (IsClosed()) {
2834 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2835 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2836 }
2837
Qingsi Wanga2d60672018-04-11 23:57:452838 // According to JSEP, after setLocalDescription, changing the candidate pool
2839 // size is not allowed, and changing the set of ICE servers will not result
2840 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:172841 if (local_description() && configuration.ice_candidate_pool_size !=
2842 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252843 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2844 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302845 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452846 }
Taylor Brandstettera1c30352016-05-13 15:15:112847
deadbeef293e9262017-01-11 20:28:302848 // The simplest (and most future-compatible) way to tell if the config was
2849 // modified in an invalid way is to copy each property we do support
2850 // modifying, then use operator==. There are far more properties we don't
2851 // support modifying than those we do, and more could be added.
2852 RTCConfiguration modified_config = configuration_;
2853 modified_config.servers = configuration.servers;
2854 modified_config.type = configuration.type;
2855 modified_config.ice_candidate_pool_size =
2856 configuration.ice_candidate_pool_size;
2857 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052858 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142859 modified_config.ice_check_interval_strong_connectivity =
2860 configuration.ice_check_interval_strong_connectivity;
2861 modified_config.ice_check_interval_weak_connectivity =
2862 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:572863 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2864 modified_config.ice_unwritable_min_checks =
2865 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:492866 modified_config.stun_candidate_keepalive_interval =
2867 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:402868 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:402869 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:112870 modified_config.active_reset_srtp_params =
2871 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:302872 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252873 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302874 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2875 }
2876
Steve Anton038834f2017-07-14 22:59:592877 // Validate the modified configuration.
2878 RTCError validate_error = ValidateConfiguration(modified_config);
2879 if (!validate_error.ok()) {
2880 return SafeSetError(std::move(validate_error), error);
2881 }
2882
deadbeef293e9262017-01-11 20:28:302883 // Note that this isn't possible through chromium, since it's an unsigned
2884 // short in WebIDL.
2885 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:172886 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:302887 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2888 }
2889
2890 // Parse ICE servers before hopping to network thread.
2891 cricket::ServerAddresses stun_servers;
2892 std::vector<cricket::RelayServerConfig> turn_servers;
2893 RTCErrorType parse_error =
2894 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2895 if (parse_error != RTCErrorType::NONE) {
2896 return SafeSetError(parse_error, error);
2897 }
Harald Alvestrand8ebba742018-05-31 12:00:342898 // Note if STUN or TURN servers were supplied.
2899 if (!stun_servers.empty()) {
2900 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2901 }
2902 if (!turn_servers.empty()) {
2903 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2904 }
deadbeef293e9262017-01-11 20:28:302905
2906 // In theory this shouldn't fail.
2907 if (!network_thread()->Invoke<bool>(
2908 RTC_FROM_HERE,
2909 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2910 stun_servers, turn_servers, modified_config.type,
2911 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402912 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:492913 modified_config.turn_customizer,
2914 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:252915 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302916 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2917 }
Honghai Zhang4cedf2b2016-08-31 15:18:112918
deadbeefd1a38b52016-12-10 21:15:332919 // As described in JSEP, calling setConfiguration with new ICE servers or
2920 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2921 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302922 if (modified_config.servers != configuration_.servers ||
2923 modified_config.type != configuration_.type ||
2924 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292925 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332926 }
skvladd1f5fda2017-02-04 00:54:052927
Qingsi Wang9c98f0c2018-02-15 23:10:592928 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:052929
Zhi Huangb57e1692018-06-12 18:41:112930 if (configuration_.active_reset_srtp_params !=
2931 modified_config.active_reset_srtp_params) {
2932 transport_controller_->SetActiveResetSrtpParams(
2933 modified_config.active_reset_srtp_params);
2934 }
2935
deadbeef293e9262017-01-11 20:28:302936 configuration_ = modified_config;
2937 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452938}
2939
henrike@webrtc.org28e20752013-07-10 00:45:362940bool PeerConnection::AddIceCandidate(
2941 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:172942 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:252943 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:102944 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:362945 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:252946 return false;
2947 }
Steve Antond25da372017-11-06 22:50:292948
2949 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:102950 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:072951 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:362952 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:292953 return false;
2954 }
2955
2956 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:102957 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:362958 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:292959 return false;
2960 }
2961
2962 bool valid = false;
2963 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2964 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:362965 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:292966 return false;
2967 }
2968
2969 // Add this candidate to the remote session description.
2970 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:102971 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:362972 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:292973 return false;
2974 }
2975
2976 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:362977 bool result = UseCandidate(ice_candidate);
2978 if (result) {
2979 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2980 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2981 } else {
2982 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2983 }
2984 return result;
Steve Antond25da372017-11-06 22:50:292985 } else {
Steve Antonc79268f2018-04-24 16:54:102986 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:362987 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:292988 return true;
2989 }
henrike@webrtc.org28e20752013-07-10 00:45:362990}
2991
Honghai Zhang7fb69db2016-03-14 18:59:182992bool PeerConnection::RemoveIceCandidates(
2993 const std::vector<cricket::Candidate>& candidates) {
2994 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:102995 if (IsClosed()) {
2996 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2997 return false;
2998 }
2999
Steve Antond25da372017-11-06 22:50:293000 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103001 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3002 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293003 return false;
3004 }
3005
3006 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103007 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293008 return false;
3009 }
3010
3011 size_t number_removed =
3012 mutable_remote_description()->RemoveCandidates(candidates);
3013 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253014 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103015 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073016 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253017 << " are removed.";
Steve Antond25da372017-11-06 22:50:293018 }
3019
3020 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353021 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3022 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103023 RTC_LOG(LS_ERROR)
3024 << "RemoveIceCandidates: Error when removing remote candidates: "
3025 << error.message();
Steve Antond25da372017-11-06 22:50:293026 }
3027 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183028}
3029
Niels Möller0c4f7be2018-05-07 12:01:373030RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023031 if (!worker_thread()->IsCurrent()) {
3032 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053033 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373034 }
3035
Niels Möller0c4f7be2018-05-07 12:01:373036 const bool has_min = bitrate.min_bitrate_bps.has_value();
3037 const bool has_start = bitrate.start_bitrate_bps.has_value();
3038 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373039 if (has_min && *bitrate.min_bitrate_bps < 0) {
3040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3041 "min_bitrate_bps <= 0");
3042 }
Niels Möller0c4f7be2018-05-07 12:01:373043 if (has_start) {
3044 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373045 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373046 "start_bitrate_bps < min_bitrate_bps");
3047 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3049 "curent_bitrate_bps < 0");
3050 }
3051 }
3052 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053053 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373055 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373056 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3057 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3058 "max_bitrate_bps < min_bitrate_bps");
3059 } else if (*bitrate.max_bitrate_bps < 0) {
3060 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3061 "max_bitrate_bps < 0");
3062 }
3063 }
3064
zstein4b979802017-06-02 21:37:373065 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373066 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373067
3068 return RTCError::OK();
3069}
3070
Alex Narest78609d52017-10-20 08:37:473071void PeerConnection::SetBitrateAllocationStrategy(
3072 std::unique_ptr<rtc::BitrateAllocationStrategy>
3073 bitrate_allocation_strategy) {
3074 rtc::Thread* worker_thread = factory_->worker_thread();
3075 if (!worker_thread->IsCurrent()) {
3076 rtc::BitrateAllocationStrategy* strategy_raw =
3077 bitrate_allocation_strategy.release();
3078 auto functor = [this, strategy_raw]() {
3079 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 09:40:333080 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 08:37:473081 };
3082 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3083 return;
3084 }
3085 RTC_DCHECK(call_.get());
3086 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3087}
3088
henrika5f6bf242017-11-01 10:06:563089void PeerConnection::SetAudioPlayout(bool playout) {
3090 if (!worker_thread()->IsCurrent()) {
3091 worker_thread()->Invoke<void>(
3092 RTC_FROM_HERE,
3093 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3094 return;
3095 }
3096 auto audio_state =
3097 factory_->channel_manager()->media_engine()->GetAudioState();
3098 audio_state->SetPlayout(playout);
3099}
3100
3101void PeerConnection::SetAudioRecording(bool recording) {
3102 if (!worker_thread()->IsCurrent()) {
3103 worker_thread()->Invoke<void>(
3104 RTC_FROM_HERE,
3105 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3106 return;
3107 }
3108 auto audio_state =
3109 factory_->channel_manager()->media_engine()->GetAudioState();
3110 audio_state->SetRecording(recording);
3111}
3112
Steve Anton8c0f7a72017-10-03 17:03:103113std::unique_ptr<rtc::SSLCertificate>
3114PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513115 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3116 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103117 return nullptr;
3118 }
Taylor Brandstetterc3928662018-02-23 21:04:513119 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 17:03:103120}
3121
Zhi Huang70b820f2018-01-27 22:16:153122std::unique_ptr<rtc::SSLCertChain>
3123PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373124 auto audio_transceiver = GetFirstAudioTransceiver();
3125 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153126 return nullptr;
3127 }
Zhi Huang70b820f2018-01-27 22:16:153128 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373129 audio_transceiver->internal()->channel()->transport_name());
3130}
3131
3132rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3133PeerConnection::GetFirstAudioTransceiver() const {
3134 for (auto transceiver : transceivers_) {
3135 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3136 return transceiver;
3137 }
3138 }
3139 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153140}
3141
ivoc14d5dbe2016-07-04 14:06:553142bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3143 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403144 // TODO(eladalon): It would be better to not allow negative values into PC.
3145 const size_t max_size = (max_size_bytes < 0)
3146 ? RtcEventLog::kUnlimitedOutput
3147 : rtc::saturated_cast<size_t>(max_size_bytes);
3148 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333149 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 16:38:143150 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:403151}
3152
Bjorn Tereliusde939432017-11-20 16:38:143153bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3154 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063155 // TODO(eladalon): In C++14, this can be done with a lambda.
3156 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143157 bool operator()() {
3158 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3159 }
Karl Wibergd6b48192017-10-16 21:01:063160 PeerConnection* const pc;
3161 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143162 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403163 };
Bjorn Tereliusde939432017-11-20 16:38:143164 return worker_thread()->Invoke<bool>(
3165 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553166}
3167
3168void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023169 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553170 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3171}
3172
henrike@webrtc.org28e20752013-07-10 00:45:363173const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173174 return pending_local_description_ ? pending_local_description_.get()
3175 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363176}
3177
3178const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173179 return pending_remote_description_ ? pending_remote_description_.get()
3180 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363181}
3182
deadbeeffe4a8a42016-12-21 01:56:173183const SessionDescriptionInterface* PeerConnection::current_local_description()
3184 const {
Steve Anton75737c02017-11-06 18:37:173185 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173186}
3187
3188const SessionDescriptionInterface* PeerConnection::current_remote_description()
3189 const {
Steve Anton75737c02017-11-06 18:37:173190 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173191}
3192
3193const SessionDescriptionInterface* PeerConnection::pending_local_description()
3194 const {
Steve Anton75737c02017-11-06 18:37:173195 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173196}
3197
3198const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3199 const {
Steve Anton75737c02017-11-06 18:37:173200 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173201}
3202
henrike@webrtc.org28e20752013-07-10 00:45:363203void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173204 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363205 // Update stats here so that we have the most recent stats for tracks and
3206 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263207 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363208
Steve Anton75737c02017-11-06 18:37:173209 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343210 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083211
Steve Anton8af21862017-12-15 19:20:133212 for (auto transceiver : transceivers_) {
3213 transceiver->Stop();
3214 }
Steve Anton25cfeb92018-04-26 18:44:003215
3216 // Ensure that all asynchronous stats requests are completed before destroying
3217 // the transport controller below.
3218 if (stats_collector_) {
3219 stats_collector_->WaitForPendingRequest();
3220 }
3221
3222 // Don't destroy BaseChannels until after stats has been cleaned up so that
3223 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133224 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173225
Qingsi Wang93a84392018-01-31 01:13:093226 // The event log is used in the transport controller, which must be outlived
3227 // by the former. CreateOffer by the peer connection is implemented
3228 // asynchronously and if the peer connection is closed without resetting the
3229 // WebRTC session description factory, the session description factory would
3230 // call the transport controller.
3231 webrtc_session_desc_factory_.reset();
3232 transport_controller_.reset();
3233
deadbeef42a42632017-03-10 23:18:003234 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053235 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3236 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023237
Steve Anton978b8762017-09-29 19:15:023238 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153239 call_.reset();
3240 // The event log must outlive call (and any other object that uses it).
3241 event_log_.reset();
3242 });
Harald Alvestrand8ebba742018-05-31 12:00:343243 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163244 // The .h file says that observer can be discarded after close() returns.
3245 // Make sure this is true.
3246 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:363247}
3248
Steve Antonad182762018-09-05 20:22:403249void PeerConnection::OnMessage(rtc::Message* msg) {
3250 switch (msg->message_id) {
3251 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3252 SetSessionDescriptionMsg* param =
3253 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3254 param->observer->OnSuccess();
3255 delete param;
3256 break;
3257 }
3258 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3259 SetSessionDescriptionMsg* param =
3260 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3261 param->observer->OnFailure(std::move(param->error));
3262 delete param;
3263 break;
3264 }
3265 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3266 CreateSessionDescriptionMsg* param =
3267 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3268 param->observer->OnFailure(std::move(param->error));
3269 delete param;
3270 break;
3271 }
3272 case MSG_GETSTATS: {
3273 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3274 StatsReports reports;
3275 stats_->GetStats(param->track, &reports);
3276 param->observer->OnComplete(reports);
3277 delete param;
3278 break;
3279 }
3280 case MSG_FREE_DATACHANNELS: {
3281 sctp_data_channels_to_free_.clear();
3282 break;
3283 }
3284 case MSG_REPORT_USAGE_PATTERN: {
3285 ReportUsagePattern();
3286 break;
3287 }
3288 default:
3289 RTC_NOTREACHED() << "Not implemented";
3290 break;
3291 }
3292}
3293
Steve Antonafb0bb72018-02-20 19:35:373294cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3295 RTC_DCHECK(!IsUnifiedPlan());
3296 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3297 GetAudioTransceiver()->internal()->channel());
3298 if (voice_channel) {
3299 return voice_channel->media_channel();
3300 } else {
3301 return nullptr;
3302 }
3303}
3304
3305cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3306 RTC_DCHECK(!IsUnifiedPlan());
3307 auto* video_channel = static_cast<cricket::VideoChannel*>(
3308 GetVideoTransceiver()->internal()->channel());
3309 if (video_channel) {
3310 return video_channel->media_channel();
3311 } else {
3312 return nullptr;
3313 }
3314}
3315
Steve Anton4171afb2017-11-20 18:20:223316void PeerConnection::CreateAudioReceiver(
3317 MediaStreamInterface* stream,
3318 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513319 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3320 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533321 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3322 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023323 auto* audio_receiver = new AudioRtpReceiver(
3324 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503325 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023326 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3327 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3328 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223329 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163330 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343331 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363332}
3333
Steve Anton4171afb2017-11-20 18:20:223334void PeerConnection::CreateVideoReceiver(
3335 MediaStreamInterface* stream,
3336 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513337 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3338 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533339 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3340 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023341 auto* video_receiver = new VideoRtpReceiver(
3342 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503343 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023344 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3345 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3346 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223347 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163348 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343349 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363350}
3351
deadbeef70ab1a12015-09-28 23:53:553352// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3353// description.
Henrik Boström933d8b02017-10-10 17:05:163354rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223355 const RtpSenderInfo& remote_sender_info) {
3356 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3357 if (!receiver) {
3358 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3359 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163360 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553361 }
Steve Anton4171afb2017-11-20 18:20:223362 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3363 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3364 } else {
3365 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3366 }
Henrik Boström933d8b02017-10-10 17:05:163367 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363368}
3369
korniltsev.anatolyec390b52017-07-25 00:00:253370void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3371 MediaStreamInterface* stream) {
3372 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363373 RTC_DCHECK(track);
3374 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253375 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223376 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253377 // We already have a sender for this track, so just change the stream_id
3378 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363379 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253380 return;
3381 }
3382
3383 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363384 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3385 {stream->id()});
Steve Anton57858b32018-02-15 23:19:503386 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223387 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253388 // If the sender has already been configured in SDP, we call SetSsrc,
3389 // which will connect the sender to the underlying transport. This can
3390 // occur if a local session description that contains the ID of the sender
3391 // is set before AddStream is called. It can also occur if the local
3392 // session description is not changed and RemoveStream is called, and
3393 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223394 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183395 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223396 if (sender_info) {
3397 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253398 }
3399}
3400
3401// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3402// indefinitely, when we have unified plan SDP.
3403void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3404 MediaStreamInterface* stream) {
3405 RTC_DCHECK(!IsClosed());
3406 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223407 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253408 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3409 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253410 return;
3411 }
Steve Anton4171afb2017-11-20 18:20:223412 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253413}
3414
3415void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3416 MediaStreamInterface* stream) {
3417 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363418 RTC_DCHECK(track);
3419 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253420 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223421 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253422 // We already have a sender for this track, so just change the stream_id
3423 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363424 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253425 return;
3426 }
3427
3428 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363429 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3430 {stream->id()});
Steve Anton57858b32018-02-15 23:19:503431 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223432 GetVideoTransceiver()->internal()->AddSender(new_sender);
3433 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183434 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223435 if (sender_info) {
3436 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253437 }
3438}
3439
3440void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3441 MediaStreamInterface* stream) {
3442 RTC_DCHECK(!IsClosed());
3443 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223444 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253445 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3446 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253447 return;
3448 }
Steve Anton4171afb2017-11-20 18:20:223449 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253450}
3451
Steve Antonba818672017-11-06 18:21:573452void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283453 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573454 if (ice_connection_state_ == new_state) {
3455 return;
3456 }
3457
deadbeefcbecd352015-09-23 18:50:273458 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573459 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113460 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273461 return;
3462 }
Steve Antonba818672017-11-06 18:21:573463
Mirko Bonadei675513b2017-11-09 10:09:253464 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3465 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573466 RTC_DCHECK(ice_connection_state_ !=
3467 PeerConnectionInterface::kIceConnectionClosed);
3468
henrike@webrtc.org28e20752013-07-10 00:45:363469 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163470 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363471}
3472
3473void PeerConnection::OnIceGatheringChange(
3474 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283475 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363476 if (IsClosed()) {
3477 return;
3478 }
3479 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163480 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363481}
3482
jbauch81bf7b02017-03-25 15:31:123483void PeerConnection::OnIceCandidate(
3484 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283485 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253486 if (IsClosed()) {
3487 return;
3488 }
Harald Alvestrand8ebba742018-05-31 12:00:343489 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:583490 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3491 candidate->candidate().address().IsPrivateIP()) {
3492 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3493 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163494 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363495}
3496
Honghai Zhang7fb69db2016-03-14 18:59:183497void PeerConnection::OnIceCandidatesRemoved(
3498 const std::vector<cricket::Candidate>& candidates) {
3499 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253500 if (IsClosed()) {
3501 return;
3502 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163503 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:183504}
3505
henrike@webrtc.org28e20752013-07-10 00:45:363506void PeerConnection::ChangeSignalingState(
3507 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573508 RTC_DCHECK(signaling_thread()->IsCurrent());
3509 if (signaling_state_ == signaling_state) {
3510 return;
3511 }
Mirko Bonadei675513b2017-11-09 10:09:253512 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3513 << GetSignalingStateString(signaling_state_)
3514 << " New state: "
3515 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363516 signaling_state_ = signaling_state;
3517 if (signaling_state == kClosed) {
3518 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:163519 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363520 if (ice_gathering_state_ != kIceGatheringComplete) {
3521 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:163522 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363523 }
3524 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163525 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363526}
3527
deadbeefeb459812015-12-16 03:24:433528void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3529 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253530 if (IsClosed()) {
3531 return;
3532 }
korniltsev.anatolyec390b52017-07-25 00:00:253533 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163534 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433535}
3536
deadbeefeb459812015-12-16 03:24:433537void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3538 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253539 if (IsClosed()) {
3540 return;
3541 }
korniltsev.anatolyec390b52017-07-25 00:00:253542 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163543 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433544}
3545
3546void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3547 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253548 if (IsClosed()) {
3549 return;
3550 }
korniltsev.anatolyec390b52017-07-25 00:00:253551 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163552 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433553}
3554
3555void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3556 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253557 if (IsClosed()) {
3558 return;
3559 }
korniltsev.anatolyec390b52017-07-25 00:00:253560 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163561 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433562}
3563
Henrik Boström31638672017-11-23 16:48:323564void PeerConnection::PostSetSessionDescriptionSuccess(
3565 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:403566 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3567 signaling_thread()->Post(RTC_FROM_HERE, this,
3568 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:323569}
3570
deadbeefab9b2d12015-10-14 18:33:113571void PeerConnection::PostSetSessionDescriptionFailure(
3572 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:403573 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:033574 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403575 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3576 msg->error = std::move(error);
3577 signaling_thread()->Post(RTC_FROM_HERE, this,
3578 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113579}
3580
3581void PeerConnection::PostCreateSessionDescriptionFailure(
3582 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033583 RTCError error) {
3584 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403585 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3586 msg->error = std::move(error);
3587 signaling_thread()->Post(RTC_FROM_HERE, this,
3588 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113589}
3590
zhihuang1c378ed2017-08-17 21:10:503591void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543592 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113593 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543594 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503595
Steve Antondcc3c022017-12-23 00:02:543596 if (IsUnifiedPlan()) {
3597 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3598 } else {
3599 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3600 }
3601
Steve Antonfa2260d2017-12-29 00:38:233602 // Intentionally unset the data channel type for RTP data channel with the
3603 // second condition. Otherwise the RTP data channels would be successfully
3604 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3605 // when building with chromium. We want to leave RTP data channels broken, so
3606 // people won't try to use them.
3607 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3608 session_options->data_channel_type = data_channel_type();
3609 }
3610
Steve Antondcc3c022017-12-23 00:02:543611 // Apply ICE restart flag and renomination flag.
3612 for (auto& options : session_options->media_description_options) {
3613 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3614 options.transport_options.enable_ice_renomination =
3615 configuration_.enable_ice_renomination;
3616 }
3617
3618 session_options->rtcp_cname = rtcp_cname_;
3619 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163620 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-23 00:02:543621}
3622
3623void PeerConnection::GetOptionsForPlanBOffer(
3624 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3625 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503626 // Figure out transceiver directional preferences.
3627 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3628 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3629
3630 // By default, generate sendrecv/recvonly m= sections.
3631 bool recv_audio = true;
3632 bool recv_video = true;
3633
3634 // By default, only offer a new m= section if we have media to send with it.
3635 bool offer_new_audio_description = send_audio;
3636 bool offer_new_video_description = send_video;
3637 bool offer_new_data_description = HasDataChannels();
3638
3639 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543640 if (offer_answer_options.offer_to_receive_audio !=
3641 RTCOfferAnswerOptions::kUndefined) {
3642 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503643 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543644 offer_new_audio_description ||
3645 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503646 }
Steve Antondcc3c022017-12-23 00:02:543647 if (offer_answer_options.offer_to_receive_video !=
3648 RTCOfferAnswerOptions::kUndefined) {
3649 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503650 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543651 offer_new_video_description ||
3652 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503653 }
3654
Danil Chapovalov66cadcc2018-06-19 14:47:433655 absl::optional<size_t> audio_index;
3656 absl::optional<size_t> video_index;
3657 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:503658 // If a current description exists, generate m= sections in the same order,
3659 // using the first audio/video/data section that appears and rejecting
3660 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173661 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503662 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173663 local_description(),
Steve Anton1d03a752017-11-27 22:30:093664 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3665 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3666 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113667 }
3668
zhihuang1c378ed2017-08-17 21:10:503669 // Add audio/video/data m= sections to the end if needed.
3670 if (!audio_index && offer_new_audio_description) {
3671 session_options->media_description_options.push_back(
3672 cricket::MediaDescriptionOptions(
3673 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093674 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3675 false));
Oskar Sundbom9b28a032017-11-16 09:53:303676 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453677 }
zhihuang1c378ed2017-08-17 21:10:503678 if (!video_index && offer_new_video_description) {
3679 session_options->media_description_options.push_back(
3680 cricket::MediaDescriptionOptions(
3681 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093682 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3683 false));
Oskar Sundbom9b28a032017-11-16 09:53:303684 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453685 }
zhihuang1c378ed2017-08-17 21:10:503686 if (!data_index && offer_new_data_description) {
3687 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233688 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303689 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503690 }
3691
3692 cricket::MediaDescriptionOptions* audio_media_description_options =
3693 !audio_index ? nullptr
3694 : &session_options->media_description_options[*audio_index];
3695 cricket::MediaDescriptionOptions* video_media_description_options =
3696 !video_index ? nullptr
3697 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503698
Steve Anton4171afb2017-11-20 18:20:223699 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:373700 video_media_description_options,
3701 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:543702}
3703
3704// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3705// and return a reference to it.
3706// Generated MIDs should be no more than 3 bytes long to take up less space in
3707// the RTP packet.
3708static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3709 RTC_DCHECK(used_mids);
3710 // We're boring: just generate MIDs 0, 1, 2, ...
3711 size_t i = 0;
3712 std::set<std::string>::iterator it;
3713 bool inserted;
3714 do {
3715 std::string mid = rtc::ToString(i++);
3716 auto insert_result = used_mids->insert(mid);
3717 it = insert_result.first;
3718 inserted = insert_result.second;
3719 } while (!inserted);
3720 return *it;
3721}
3722
3723static cricket::MediaDescriptionOptions
3724GetMediaDescriptionOptionsForTransceiver(
3725 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3726 transceiver,
3727 const std::string& mid) {
3728 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083729 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543730 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303731 // This behavior is specified in JSEP. The gist is that:
3732 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3733 // sendrecv.
3734 // 2. If the MSID is included, then it must be included in any subsequent
3735 // offer/answer exactly the same until the RtpTransceiver is stopped.
3736 if (!transceiver->stopped() &&
3737 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3738 transceiver->internal()->has_ever_been_used_to_send())) {
3739 cricket::SenderOptions sender_options;
3740 sender_options.track_id = transceiver->sender()->id();
3741 sender_options.stream_ids = transceiver->sender()->stream_ids();
3742 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3743 // set in the RTP parameters when the transceiver was added.
3744 sender_options.num_sim_layers = 1;
3745 media_description_options.sender_options.push_back(sender_options);
3746 }
Steve Antondcc3c022017-12-23 00:02:543747 return media_description_options;
3748}
3749
3750void PeerConnection::GetOptionsForUnifiedPlanOffer(
3751 const RTCOfferAnswerOptions& offer_answer_options,
3752 cricket::MediaSessionOptions* session_options) {
3753 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3754 // Offers) and 5.2.2 (Subsequent Offers).
3755 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3756 const ContentInfos& local_contents =
3757 (local_description() ? local_description()->description()->contents()
3758 : ContentInfos());
3759 const ContentInfos& remote_contents =
3760 (remote_description() ? remote_description()->description()->contents()
3761 : ContentInfos());
3762 // The mline indices that can be recycled. New transceivers should reuse these
3763 // slots first.
3764 std::queue<size_t> recycleable_mline_indices;
3765 // Track the MIDs used in previous offer/answer exchanges and the current
3766 // offer so that new, unique MIDs are generated.
3767 std::set<std::string> used_mids = seen_mids_;
3768 // First, go through each media section that exists in either the local or
3769 // remote description and generate a media section in this offer for the
3770 // associated transceiver. If a media section can be recycled, generate a
3771 // default, rejected media section here that can be later overwritten.
3772 for (size_t i = 0;
3773 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3774 // Either |local_content| or |remote_content| is non-null.
3775 const ContentInfo* local_content =
3776 (i < local_contents.size() ? &local_contents[i] : nullptr);
3777 const ContentInfo* remote_content =
3778 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3779 bool had_been_rejected = (local_content && local_content->rejected) ||
3780 (remote_content && remote_content->rejected);
3781 const std::string& mid =
3782 (local_content ? local_content->name : remote_content->name);
3783 cricket::MediaType media_type =
3784 (local_content ? local_content->media_description()->type()
3785 : remote_content->media_description()->type());
3786 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3787 media_type == cricket::MEDIA_TYPE_VIDEO) {
3788 auto transceiver = GetAssociatedTransceiver(mid);
3789 RTC_CHECK(transceiver);
3790 // A media section is considered eligible for recycling if it is marked as
3791 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483792 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543793 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083794 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3795 RtpTransceiverDirection::kInactive,
3796 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543797 recycleable_mline_indices.push(i);
3798 } else {
3799 session_options->media_description_options.push_back(
3800 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3801 // CreateOffer shouldn't really cause any state changes in
3802 // PeerConnection, but we need a way to match new transceivers to new
3803 // media sections in SetLocalDescription and JSEP specifies this is done
3804 // by recording the index of the media section generated for the
3805 // transceiver in the offer.
3806 transceiver->internal()->set_mline_index(i);
3807 }
3808 } else {
3809 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233810 RTC_CHECK(GetDataMid());
3811 if (had_been_rejected || mid != *GetDataMid()) {
3812 session_options->media_description_options.push_back(
3813 GetMediaDescriptionOptionsForRejectedData(mid));
3814 } else {
3815 session_options->media_description_options.push_back(
3816 GetMediaDescriptionOptionsForActiveData(mid));
3817 }
Steve Antondcc3c022017-12-23 00:02:543818 }
3819 }
3820 // Next, look for transceivers that are newly added (that is, are not stopped
3821 // and not associated). Reuse media sections marked as recyclable first,
3822 // otherwise append to the end of the offer. New media sections should be
3823 // added in the order they were added to the PeerConnection.
3824 for (auto transceiver : transceivers_) {
3825 if (transceiver->mid() || transceiver->stopped()) {
3826 continue;
3827 }
3828 size_t mline_index;
3829 if (!recycleable_mline_indices.empty()) {
3830 mline_index = recycleable_mline_indices.front();
3831 recycleable_mline_indices.pop();
3832 session_options->media_description_options[mline_index] =
3833 GetMediaDescriptionOptionsForTransceiver(transceiver,
3834 AllocateMid(&used_mids));
3835 } else {
3836 mline_index = session_options->media_description_options.size();
3837 session_options->media_description_options.push_back(
3838 GetMediaDescriptionOptionsForTransceiver(transceiver,
3839 AllocateMid(&used_mids)));
3840 }
3841 // See comment above for why CreateOffer changes the transceiver's state.
3842 transceiver->internal()->set_mline_index(mline_index);
3843 }
Steve Antonfa2260d2017-12-29 00:38:233844 // Lastly, add a m-section if we have local data channels and an m section
3845 // does not already exist.
3846 if (!GetDataMid() && HasDataChannels()) {
3847 session_options->media_description_options.push_back(
3848 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3849 }
Steve Antondcc3c022017-12-23 00:02:543850}
3851
3852void PeerConnection::GetOptionsForAnswer(
3853 const RTCOfferAnswerOptions& offer_answer_options,
3854 cricket::MediaSessionOptions* session_options) {
3855 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3856
3857 if (IsUnifiedPlan()) {
3858 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3859 } else {
3860 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3861 }
3862
Steve Antonfa2260d2017-12-29 00:38:233863 // Intentionally unset the data channel type for RTP data channel. Otherwise
3864 // the RTP data channels would be successfully negotiated by default and the
3865 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3866 // We want to leave RTP data channels broken, so people won't try to use them.
3867 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3868 session_options->data_channel_type = data_channel_type();
3869 }
3870
Steve Antondcc3c022017-12-23 00:02:543871 // Apply ICE renomination flag.
3872 for (auto& options : session_options->media_description_options) {
3873 options.transport_options.enable_ice_renomination =
3874 configuration_.enable_ice_renomination;
3875 }
zhihuang8f65cdf2016-05-07 01:40:303876
3877 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323878 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163879 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 18:33:113880}
3881
Steve Antondcc3c022017-12-23 00:02:543882void PeerConnection::GetOptionsForPlanBAnswer(
3883 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113884 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503885 // Figure out transceiver directional preferences.
3886 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3887 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3888
3889 // By default, generate sendrecv/recvonly m= sections. The direction is also
3890 // restricted by the direction in the offer.
3891 bool recv_audio = true;
3892 bool recv_video = true;
3893
3894 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543895 if (offer_answer_options.offer_to_receive_audio !=
3896 RTCOfferAnswerOptions::kUndefined) {
3897 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523898 }
Steve Antondcc3c022017-12-23 00:02:543899 if (offer_answer_options.offer_to_receive_video !=
3900 RTCOfferAnswerOptions::kUndefined) {
3901 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503902 }
3903
Danil Chapovalov66cadcc2018-06-19 14:47:433904 absl::optional<size_t> audio_index;
3905 absl::optional<size_t> video_index;
3906 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:293907
3908 // Generate m= sections that match those in the offer.
3909 // Note that mediasession.cc will handle intersection our preferred
3910 // direction with the offered direction.
3911 GenerateMediaDescriptionOptions(
3912 remote_description(),
3913 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3914 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3915 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:503916
3917 cricket::MediaDescriptionOptions* audio_media_description_options =
3918 !audio_index ? nullptr
3919 : &session_options->media_description_options[*audio_index];
3920 cricket::MediaDescriptionOptions* video_media_description_options =
3921 !video_index ? nullptr
3922 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503923
Steve Anton4171afb2017-11-20 18:20:223924 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:373925 video_media_description_options,
3926 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:543927}
zhihuangaf388472016-11-02 23:49:483928
Steve Antondcc3c022017-12-23 00:02:543929void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3930 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3931 cricket::MediaSessionOptions* session_options) {
3932 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3933 // Answers) and 5.3.2 (Subsequent Answers).
3934 RTC_DCHECK(remote_description());
3935 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3936 for (const ContentInfo& content :
3937 remote_description()->description()->contents()) {
3938 cricket::MediaType media_type = content.media_description()->type();
3939 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3940 media_type == cricket::MEDIA_TYPE_VIDEO) {
3941 auto transceiver = GetAssociatedTransceiver(content.name);
3942 RTC_CHECK(transceiver);
3943 session_options->media_description_options.push_back(
3944 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3945 } else {
3946 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:403947 // Reject all data sections if data channels are disabled.
3948 // Reject a data section if it has already been rejected.
3949 // Reject all data sections except for the first one.
3950 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3951 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:233952 session_options->media_description_options.push_back(
3953 GetMediaDescriptionOptionsForRejectedData(content.name));
3954 } else {
3955 session_options->media_description_options.push_back(
3956 GetMediaDescriptionOptionsForActiveData(content.name));
3957 }
Steve Antondcc3c022017-12-23 00:02:543958 }
3959 }
htaa2a49d92016-03-04 10:51:393960}
3961
zhihuang1c378ed2017-08-17 21:10:503962void PeerConnection::GenerateMediaDescriptionOptions(
3963 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:093964 RtpTransceiverDirection audio_direction,
3965 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:433966 absl::optional<size_t>* audio_index,
3967 absl::optional<size_t>* video_index,
3968 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:393969 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503970 for (const cricket::ContentInfo& content :
3971 session_desc->description()->contents()) {
3972 if (IsAudioContent(&content)) {
3973 // If we already have an audio m= section, reject this extra one.
3974 if (*audio_index) {
3975 session_options->media_description_options.push_back(
3976 cricket::MediaDescriptionOptions(
3977 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:093978 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503979 } else {
3980 session_options->media_description_options.push_back(
3981 cricket::MediaDescriptionOptions(
3982 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:093983 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303984 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503985 }
3986 } else if (IsVideoContent(&content)) {
3987 // If we already have an video m= section, reject this extra one.
3988 if (*video_index) {
3989 session_options->media_description_options.push_back(
3990 cricket::MediaDescriptionOptions(
3991 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:093992 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503993 } else {
3994 session_options->media_description_options.push_back(
3995 cricket::MediaDescriptionOptions(
3996 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:093997 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303998 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503999 }
4000 } else {
4001 RTC_DCHECK(IsDataContent(&content));
4002 // If we already have an data m= section, reject this extra one.
4003 if (*data_index) {
4004 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234005 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504006 } else {
4007 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234008 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304009 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504010 }
4011 }
htaa2a49d92016-03-04 10:51:394012 }
deadbeefab9b2d12015-10-14 18:33:114013}
4014
Steve Antonfa2260d2017-12-29 00:38:234015cricket::MediaDescriptionOptions
4016PeerConnection::GetMediaDescriptionOptionsForActiveData(
4017 const std::string& mid) const {
4018 // Direction for data sections is meaningless, but legacy endpoints might
4019 // expect sendrecv.
4020 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4021 RtpTransceiverDirection::kSendRecv,
4022 /*stopped=*/false);
4023 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4024 return options;
4025}
4026
4027cricket::MediaDescriptionOptions
4028PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4029 const std::string& mid) const {
4030 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4031 RtpTransceiverDirection::kInactive,
4032 /*stopped=*/true);
4033 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4034 return options;
4035}
4036
Danil Chapovalov66cadcc2018-06-19 14:47:434037absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234038 switch (data_channel_type_) {
4039 case cricket::DCT_RTP:
4040 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434041 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234042 }
4043 return rtp_data_channel_->content_name();
4044 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354045 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:234046 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434047 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234048 }
4049}
4050
Steve Anton4171afb2017-11-20 18:20:224051void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4052 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4053 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404054 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074055}
4056
Steve Anton4171afb2017-11-20 18:20:224057void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114058 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224059 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114060 cricket::MediaType media_type,
4061 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364062 RTC_DCHECK(!IsUnifiedPlan());
4063
Steve Anton4171afb2017-11-20 18:20:224064 std::vector<RtpSenderInfo>* current_senders =
4065 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114066
Steve Anton4171afb2017-11-20 18:20:224067 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014068 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224069 for (auto sender_it = current_senders->begin();
4070 sender_it != current_senders->end();
4071 /* incremented manually */) {
4072 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114073 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224074 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094075 std::string params_stream_id;
4076 if (params) {
4077 params_stream_id =
4078 (!params->first_stream_id().empty() ? params->first_stream_id()
4079 : kDefaultStreamId);
4080 }
Seth Hampson5b4f0752018-04-02 23:31:364081 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094082 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404083 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104084 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224085 sender_exists) {
4086 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404087 } else {
Steve Anton4171afb2017-11-20 18:20:224088 OnRemoteSenderRemoved(info, media_type);
4089 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114090 }
4091 }
4092
Steve Anton4171afb2017-11-20 18:20:224093 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114094 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334095 if (!params.has_ssrcs()) {
4096 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4097 // sender, this means it is coming from a Unified Plan endpoint,so we just
4098 // create a default.
4099 default_sender_needed = true;
4100 break;
4101 }
4102
Seth Hampson845e8782018-03-02 19:34:104103 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364104 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334105 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4106 // not supported in Plan B, we just take the first here and create the
4107 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104108 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094109 (!params.first_stream_id().empty() ? params.first_stream_id()
4110 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224111 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114112 uint32_t ssrc = params.first_ssrc();
4113
4114 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104115 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114116 if (!stream) {
4117 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194118 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104119 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114120 remote_streams_->AddStream(stream);
4121 new_streams->AddStream(stream);
4122 }
4123
Steve Anton4171afb2017-11-20 18:20:224124 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184125 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224126 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104127 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224128 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114129 }
4130 }
deadbeefbda7e0b2015-12-09 01:13:404131
Steve Anton4171afb2017-11-20 18:20:224132 // Add default sender if necessary.
4133 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404134 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104135 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404136 if (!default_stream) {
4137 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194138 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104139 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404140 remote_streams_->AddStream(default_stream);
4141 new_streams->AddStream(default_stream);
4142 }
Steve Anton4171afb2017-11-20 18:20:224143 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4144 ? kDefaultAudioSenderId
4145 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104146 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184147 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224148 if (!default_sender_info) {
4149 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104150 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224151 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404152 }
4153 }
deadbeefab9b2d12015-10-14 18:33:114154}
4155
Steve Anton4171afb2017-11-20 18:20:224156void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4157 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234158 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4159 << " receiver for track_id=" << sender_info.sender_id
4160 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114161
Steve Anton3d954a62018-04-02 18:27:234162 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114163 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224164 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114165 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224166 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114167 } else {
nisseeb4ca4e2017-01-12 10:24:274168 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114169 }
4170}
4171
Steve Anton4171afb2017-11-20 18:20:224172void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4173 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094174 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4175 << " receiver for track_id=" << sender_info.sender_id
4176 << " and stream_id=" << sender_info.stream_id;
4177
Seth Hampson845e8782018-03-02 19:34:104178 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114179
Henrik Boström933d8b02017-10-10 17:05:164180 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114181 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194182 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4183 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224184 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114185 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224186 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114187 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114188 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114189 }
4190 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194191 // Stopping or destroying a VideoRtpReceiver will end the
4192 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224193 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114194 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224195 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114196 if (video_track) {
perkjd61bf802016-03-24 10:16:194197 // There's no guarantee the track is still available, e.g. the track may
4198 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114199 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114200 }
4201 } else {
nisseede5da42017-01-12 13:15:364202 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114203 }
Henrik Boström933d8b02017-10-10 17:05:164204 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164205 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164206 }
deadbeefab9b2d12015-10-14 18:33:114207}
4208
4209void PeerConnection::UpdateEndedRemoteMediaStreams() {
4210 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4211 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4212 MediaStreamInterface* stream = remote_streams_->at(i);
4213 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4214 streams_to_remove.push_back(stream);
4215 }
4216 }
4217
Taylor Brandstetter98cde262016-05-31 20:02:214218 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114219 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164220 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114221 }
4222}
4223
Steve Anton4171afb2017-11-20 18:20:224224void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114225 const std::vector<cricket::StreamParams>& streams,
4226 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224227 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114228
Seth Hampson845e8782018-03-02 19:34:104229 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114230 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224231 for (auto sender_it = current_senders->begin();
4232 sender_it != current_senders->end();
4233 /* incremented manually */) {
4234 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114235 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224236 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4237 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104238 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224239 OnLocalSenderRemoved(info, media_type);
4240 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114241 } else {
Steve Anton4171afb2017-11-20 18:20:224242 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114243 }
4244 }
4245
Steve Anton4171afb2017-11-20 18:20:224246 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114247 for (const cricket::StreamParams& params : streams) {
4248 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224249 // sender id.
Seth Hampson845e8782018-03-02 19:34:104250 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224251 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114252 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224253 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184254 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224255 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104256 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224257 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114258 }
4259 }
4260}
4261
Steve Anton4171afb2017-11-20 18:20:224262void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4263 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364264 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224265 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014266 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224267 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4268 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254269 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114270 return;
4271 }
4272
deadbeeffac06552015-11-25 19:26:014273 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254274 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074275 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014276 return;
deadbeefab9b2d12015-10-14 18:33:114277 }
deadbeeffac06552015-11-25 19:26:014278
Seth Hampson5b4f0752018-04-02 23:31:364279 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224280 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114281}
4282
Steve Anton4171afb2017-11-20 18:20:224283void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4284 cricket::MediaType media_type) {
4285 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014286 if (!sender) {
4287 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114288 // SessionDescriptions has been renegotiated.
4289 return;
4290 }
deadbeeffac06552015-11-25 19:26:014291
4292 // A sender has been removed from the SessionDescription but it's still
4293 // associated with the PeerConnection. This only occurs if the SDP doesn't
4294 // match with the calls to CreateSender, AddStream and RemoveStream.
4295 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254296 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074297 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014298 return;
deadbeefab9b2d12015-10-14 18:33:114299 }
deadbeeffac06552015-11-25 19:26:014300
Steve Anton4171afb2017-11-20 18:20:224301 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114302}
4303
4304void PeerConnection::UpdateLocalRtpDataChannels(
4305 const cricket::StreamParamsVec& streams) {
4306 std::vector<std::string> existing_channels;
4307
4308 // Find new and active data channels.
4309 for (const cricket::StreamParams& params : streams) {
4310 // |it->sync_label| is actually the data channel label. The reason is that
4311 // we use the same naming of data channels as we do for
4312 // MediaStreams and Tracks.
4313 // For MediaStreams, the sync_label is the MediaStream label and the
4314 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104315 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114316 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564317 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254318 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114319 continue;
4320 }
4321 // Set the SSRC the data channel should use for sending.
4322 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4323 existing_channels.push_back(data_channel_it->first);
4324 }
4325
4326 UpdateClosingRtpDataChannels(existing_channels, true);
4327}
4328
4329void PeerConnection::UpdateRemoteRtpDataChannels(
4330 const cricket::StreamParamsVec& streams) {
4331 std::vector<std::string> existing_channels;
4332
4333 // Find new and active data channels.
4334 for (const cricket::StreamParams& params : streams) {
4335 // The data channel label is either the mslabel or the SSRC if the mslabel
4336 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104337 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114338 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104339 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114340 auto data_channel_it = rtp_data_channels_.find(label);
4341 if (data_channel_it == rtp_data_channels_.end()) {
4342 // This is a new data channel.
4343 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4344 } else {
4345 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4346 }
4347 existing_channels.push_back(label);
4348 }
4349
4350 UpdateClosingRtpDataChannels(existing_channels, false);
4351}
4352
4353void PeerConnection::UpdateClosingRtpDataChannels(
4354 const std::vector<std::string>& active_channels,
4355 bool is_local_update) {
4356 auto it = rtp_data_channels_.begin();
4357 while (it != rtp_data_channels_.end()) {
4358 DataChannel* data_channel = it->second;
4359 if (std::find(active_channels.begin(), active_channels.end(),
4360 data_channel->label()) != active_channels.end()) {
4361 ++it;
4362 continue;
4363 }
4364
4365 if (is_local_update) {
4366 data_channel->SetSendSsrc(0);
4367 } else {
4368 data_channel->RemotePeerRequestClose();
4369 }
4370
4371 if (data_channel->state() == DataChannel::kClosed) {
4372 rtp_data_channels_.erase(it);
4373 it = rtp_data_channels_.begin();
4374 } else {
4375 ++it;
4376 }
4377 }
4378}
4379
4380void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4381 uint32_t remote_ssrc) {
4382 rtc::scoped_refptr<DataChannel> channel(
4383 InternalCreateDataChannel(label, nullptr));
4384 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254385 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074386 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114387 return;
4388 }
4389 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394390 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4391 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164392 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114393}
4394
4395rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4396 const std::string& label,
4397 const InternalDataChannelInit* config) {
4398 if (IsClosed()) {
4399 return nullptr;
4400 }
Steve Anton75737c02017-11-06 18:37:174401 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254402 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114403 << "InternalCreateDataChannel: Data is not supported in this call.";
4404 return nullptr;
4405 }
4406 InternalDataChannelInit new_config =
4407 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:174408 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:114409 if (new_config.id < 0) {
4410 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174411 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114412 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254413 RTC_LOG(LS_ERROR)
4414 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114415 return nullptr;
4416 }
4417 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254418 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074419 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114420 return nullptr;
4421 }
4422 }
4423
Steve Anton75737c02017-11-06 18:37:174424 rtc::scoped_refptr<DataChannel> channel(
4425 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114426 if (!channel) {
4427 sid_allocator_.ReleaseSid(new_config.id);
4428 return nullptr;
4429 }
4430
4431 if (channel->data_channel_type() == cricket::DCT_RTP) {
4432 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254433 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4434 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114435 return nullptr;
4436 }
4437 rtp_data_channels_[channel->label()] = channel;
4438 } else {
4439 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4440 sctp_data_channels_.push_back(channel);
4441 channel->SignalClosed.connect(this,
4442 &PeerConnection::OnSctpDataChannelClosed);
4443 }
4444
Steve Anton2d8609c2018-01-24 00:38:464445 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114446 return channel;
4447}
4448
4449bool PeerConnection::HasDataChannels() const {
4450 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4451}
4452
4453void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4454 for (const auto& channel : sctp_data_channels_) {
4455 if (channel->id() < 0) {
4456 int sid;
4457 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254458 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114459 continue;
4460 }
4461 channel->SetSctpSid(sid);
4462 }
4463 }
4464}
4465
4466void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294467 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114468 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4469 ++it) {
4470 if (it->get() == channel) {
4471 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:324472 // After the closing procedure is done, it's safe to use this ID for
4473 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114474 sid_allocator_.ReleaseSid(channel->id());
4475 }
deadbeefbd292462015-12-15 02:15:294476 // Since this method is triggered by a signal from the DataChannel,
4477 // we can't free it directly here; we need to free it asynchronously.
4478 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114479 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:404480 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4481 nullptr);
deadbeefab9b2d12015-10-14 18:33:114482 return;
4483 }
4484 }
4485}
4486
deadbeefab9b2d12015-10-14 18:33:114487void PeerConnection::OnDataChannelDestroyed() {
4488 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4489 // DataChannel may callback to us and try to modify the list.
4490 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4491 temp_rtp_dcs.swap(rtp_data_channels_);
4492 for (const auto& kv : temp_rtp_dcs) {
4493 kv.second->OnTransportChannelDestroyed();
4494 }
4495
4496 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4497 temp_sctp_dcs.swap(sctp_data_channels_);
4498 for (const auto& channel : temp_sctp_dcs) {
4499 channel->OnTransportChannelDestroyed();
4500 }
4501}
4502
4503void PeerConnection::OnDataChannelOpenMessage(
4504 const std::string& label,
4505 const InternalDataChannelInit& config) {
4506 rtc::scoped_refptr<DataChannel> channel(
4507 InternalCreateDataChannel(label, &config));
4508 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254509 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114510 return;
4511 }
4512
deadbeefa601f5c2016-06-06 21:27:394513 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4514 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164515 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:414516 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:114517}
4518
Steve Anton4171afb2017-11-20 18:20:224519rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4520PeerConnection::GetAudioTransceiver() const {
4521 // This method only works with Plan B SDP, where there is a single
4522 // audio/video transceiver.
4523 RTC_DCHECK(!IsUnifiedPlan());
4524 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084525 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224526 return transceiver;
4527 }
4528 }
4529 RTC_NOTREACHED();
4530 return nullptr;
4531}
4532
4533rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4534PeerConnection::GetVideoTransceiver() const {
4535 // This method only works with Plan B SDP, where there is a single
4536 // audio/video transceiver.
4537 RTC_DCHECK(!IsUnifiedPlan());
4538 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084539 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224540 return transceiver;
4541 }
4542 }
4543 RTC_NOTREACHED();
4544 return nullptr;
4545}
4546
4547// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4548// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504549bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224550 switch (type) {
4551 case cricket::MEDIA_TYPE_AUDIO:
4552 return !GetAudioTransceiver()->internal()->senders().empty();
4553 case cricket::MEDIA_TYPE_VIDEO:
4554 return !GetVideoTransceiver()->internal()->senders().empty();
4555 case cricket::MEDIA_TYPE_DATA:
4556 return false;
4557 }
4558 RTC_NOTREACHED();
4559 return false;
zhihuang1c378ed2017-08-17 21:10:504560}
4561
Steve Anton4171afb2017-11-20 18:20:224562rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4563PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4564 for (auto transceiver : transceivers_) {
4565 for (auto sender : transceiver->internal()->senders()) {
4566 if (sender->track() == track) {
4567 return sender;
4568 }
4569 }
4570 }
4571 return nullptr;
deadbeeffac06552015-11-25 19:26:014572}
4573
Steve Anton4171afb2017-11-20 18:20:224574rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4575PeerConnection::FindSenderById(const std::string& sender_id) const {
4576 for (auto transceiver : transceivers_) {
4577 for (auto sender : transceiver->internal()->senders()) {
4578 if (sender->id() == sender_id) {
4579 return sender;
4580 }
4581 }
4582 }
4583 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554584}
4585
Steve Anton4171afb2017-11-20 18:20:224586rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4587PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4588 for (auto transceiver : transceivers_) {
4589 for (auto receiver : transceiver->internal()->receivers()) {
4590 if (receiver->id() == receiver_id) {
4591 return receiver;
4592 }
4593 }
4594 }
4595 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554596}
4597
Steve Anton4171afb2017-11-20 18:20:224598std::vector<PeerConnection::RtpSenderInfo>*
4599PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4600 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4601 media_type == cricket::MEDIA_TYPE_VIDEO);
4602 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4603 ? &remote_audio_sender_infos_
4604 : &remote_video_sender_infos_;
4605}
4606
4607std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114608 cricket::MediaType media_type) {
4609 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4610 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224611 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4612 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114613}
4614
Steve Anton4171afb2017-11-20 18:20:224615const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4616 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184617 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224618 const std::string sender_id) const {
4619 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184620 if (sender_info.stream_id == stream_id &&
4621 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224622 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114623 }
4624 }
4625 return nullptr;
4626}
4627
4628DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4629 for (const auto& channel : sctp_data_channels_) {
4630 if (channel->id() == sid) {
4631 return channel;
4632 }
4633 }
4634 return nullptr;
4635}
4636
deadbeef91dd5672016-05-18 23:55:304637bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:074638 const cricket::ServerAddresses& stun_servers,
4639 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:114640 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-28 00:20:154641 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114642 // To handle both internal and externally created port allocator, we will
4643 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454644 port_allocator_flags_ = port_allocator_->flags();
4645 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4646 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4647 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114648 // If the disable-IPv6 flag was specified, we'll not override it
4649 // by experiment.
4650 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454651 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474652 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4653 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454654 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114655 }
4656
zhihuangb09b3f92017-03-07 22:40:514657 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:454658 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254659 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514660 }
4661
Taylor Brandstettera1c30352016-05-13 15:15:114662 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:454663 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254664 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114665 }
4666
honghaiz60347052016-06-01 01:29:124667 if (configuration.candidate_network_policy ==
4668 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:454669 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254670 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124671 }
4672
Daniel Lazarenko2870b0a2018-01-25 09:30:224673 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:454674 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224675 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4676 }
4677
Qingsi Wanga2d60672018-04-11 23:57:454678 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:114679 // No step delay is used while allocating ports.
4680 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4681 port_allocator_->set_candidate_filter(
4682 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114683 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114684
Harald Alvestrandb2a74782018-06-28 11:54:074685 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:264686 for (auto& turn_server : turn_servers_copy) {
4687 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:254688 }
Taylor Brandstettera1c30352016-05-13 15:15:114689 // Call this last since it may create pooled allocator sessions using the
4690 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494691 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264692 stun_servers, std::move(turn_servers_copy),
4693 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4694 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 22:45:494695 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114696 return true;
4697}
4698
deadbeef91dd5672016-05-18 23:55:304699bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304700 const cricket::ServerAddresses& stun_servers,
4701 const std::vector<cricket::RelayServerConfig>& turn_servers,
4702 IceTransportsType type,
4703 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404704 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494705 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 14:47:434706 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114707 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304708 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:454709 // According to JSEP, after setLocalDescription, changing the candidate pool
4710 // size is not allowed, and changing the set of ICE servers will not result
4711 // in new candidates being gathered.
4712 if (local_description()) {
4713 port_allocator_->FreezeCandidatePool();
4714 }
Benjamin Wright6f80f092018-08-14 00:06:264715 // Add the custom tls turn servers if they exist.
4716 auto turn_servers_copy = turn_servers;
4717 for (auto& turn_server : turn_servers_copy) {
4718 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4719 }
Taylor Brandstettera1c30352016-05-13 15:15:114720 // Call this last since it may create pooled allocator sessions using the
4721 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324722 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:264723 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4724 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114725}
4726
Steve Antonba818672017-11-06 18:21:574727cricket::ChannelManager* PeerConnection::channel_manager() const {
4728 return factory_->channel_manager();
4729}
4730
Elad Alon99c3fe52017-10-13 14:29:404731bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144732 std::unique_ptr<RtcEventLogOutput> output,
4733 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164734 if (!event_log_) {
4735 return false;
4736 }
Bjorn Tereliusde939432017-11-20 16:38:144737 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554738}
4739
4740void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164741 if (event_log_) {
4742 event_log_->StopLogging();
4743 }
ivoc14d5dbe2016-07-04 14:06:554744}
nisseeaabdf62017-05-05 09:23:024745
Steve Anton75737c02017-11-06 18:37:174746cricket::BaseChannel* PeerConnection::GetChannel(
4747 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544748 for (auto transceiver : transceivers_) {
4749 cricket::BaseChannel* channel = transceiver->internal()->channel();
4750 if (channel && channel->content_name() == content_name) {
4751 return channel;
4752 }
Steve Anton75737c02017-11-06 18:37:174753 }
4754 if (rtp_data_channel() &&
4755 rtp_data_channel()->content_name() == content_name) {
4756 return rtp_data_channel();
4757 }
4758 return nullptr;
4759}
4760
4761bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4762 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254763 RTC_LOG(LS_INFO)
4764 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074765 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174766 return false;
4767 }
4768 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254769 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074770 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174771 return false;
4772 }
4773
Zhi Huange830e682018-03-30 17:48:354774 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4775 if (dtls_role) {
4776 *role = *dtls_role;
4777 return true;
4778 }
4779 return false;
Steve Anton75737c02017-11-06 18:37:174780}
4781
4782bool PeerConnection::GetSslRole(const std::string& content_name,
4783 rtc::SSLRole* role) {
4784 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254785 RTC_LOG(LS_INFO)
4786 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074787 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174788 return false;
4789 }
4790
Zhi Huange830e682018-03-30 17:48:354791 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4792 if (dtls_role) {
4793 *role = *dtls_role;
4794 return true;
4795 }
4796 return false;
Steve Anton75737c02017-11-06 18:37:174797}
4798
Steve Antonf8470812017-12-04 18:46:214799void PeerConnection::SetSessionError(SessionError error,
4800 const std::string& error_desc) {
4801 RTC_DCHECK_RUN_ON(signaling_thread());
4802 if (error != session_error_) {
4803 session_error_ = error;
4804 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174805 }
4806}
4807
Zhi Huange830e682018-03-30 17:48:354808RTCError PeerConnection::UpdateSessionState(
4809 SdpType type,
4810 cricket::ContentSource source,
4811 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:564812 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174813
4814 // If there's already a pending error then no state transition should happen.
4815 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214816 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474817
Steve Anton6d6a2ae2017-12-05 01:19:474818 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514819 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594820 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474821 }
4822
4823 // Update the signaling state according to the specified state machine (see
4824 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514825 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474826 ChangeSignalingState(source == cricket::CS_LOCAL
4827 ? PeerConnectionInterface::kHaveLocalOffer
4828 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514829 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474830 ChangeSignalingState(source == cricket::CS_LOCAL
4831 ? PeerConnectionInterface::kHaveLocalPrAnswer
4832 : PeerConnectionInterface::kHaveRemotePrAnswer);
4833 } else {
Steve Anton3828c062017-12-06 18:34:514834 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474835 ChangeSignalingState(PeerConnectionInterface::kStable);
4836 }
4837
4838 // Update internal objects according to the session description's media
4839 // descriptions.
Zhi Huange830e682018-03-30 17:48:354840 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474841 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:424842 return error;
Steve Anton6d6a2ae2017-12-05 01:19:474843 }
4844
Steve Anton8a006912017-12-04 23:25:564845 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174846}
4847
Steve Anton8a006912017-12-04 23:25:564848RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514849 SdpType type,
Steve Anton8a006912017-12-04 23:25:564850 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594851 const SessionDescriptionInterface* sdesc =
4852 (source == cricket::CS_LOCAL ? local_description()
4853 : remote_description());
Steve Anton75737c02017-11-06 18:37:174854 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594855
4856 // Push down the new SDP media section for each audio/video transceiver.
4857 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174858 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594859 FindMediaSectionForTransceiver(transceiver, sdesc);
4860 cricket::BaseChannel* channel = transceiver->internal()->channel();
4861 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174862 continue;
4863 }
4864 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304865 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594866 if (!content_desc) {
4867 continue;
4868 }
4869 std::string error;
Yves Gerey665174f2018-06-19 13:03:054870 bool success = (source == cricket::CS_LOCAL)
4871 ? channel->SetLocalContent(content_desc, type, &error)
4872 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594873 if (!success) {
4874 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4875 }
4876 }
4877
4878 // If using the RtpDataChannel, push down the new SDP section for it too.
4879 if (rtp_data_channel_) {
4880 const ContentInfo* data_content =
4881 cricket::GetFirstDataContent(sdesc->description());
4882 if (data_content && !data_content->rejected) {
4883 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304884 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594885 if (data_desc) {
4886 std::string error;
4887 bool success =
4888 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514889 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:054890 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594891 if (!success) {
4892 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4893 std::move(error));
4894 }
Steve Anton75737c02017-11-06 18:37:174895 }
4896 }
4897 }
Steve Antoned10bd92017-12-05 18:52:594898
Steve Anton75737c02017-11-06 18:37:174899 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4900 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4901 if (sctp_transport_ && local_description() && remote_description() &&
4902 cricket::GetFirstDataContent(local_description()->description()) &&
4903 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564904 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174905 RTC_FROM_HERE,
4906 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564907 if (!success) {
4908 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4909 "Failed to push down SCTP parameters.");
4910 }
Steve Anton75737c02017-11-06 18:37:174911 }
Steve Antoned10bd92017-12-05 18:52:594912
Steve Anton8a006912017-12-04 23:25:564913 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174914}
4915
4916bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4917 RTC_DCHECK(network_thread()->IsCurrent());
4918 RTC_DCHECK(local_description());
4919 RTC_DCHECK(remote_description());
4920 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4921 // When we support "max-message-size", that would also be pushed down here.
4922 return sctp_transport_->Start(
4923 GetSctpPort(local_description()->description()),
4924 GetSctpPort(remote_description()->description()));
4925}
4926
Steve Anton8a006912017-12-04 23:25:564927RTCError PeerConnection::PushdownTransportDescription(
4928 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514929 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564930 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174931
Zhi Huange830e682018-03-30 17:48:354932 if (source == cricket::CS_LOCAL) {
4933 const SessionDescriptionInterface* sdesc = local_description();
4934 RTC_DCHECK(sdesc);
4935 return transport_controller_->SetLocalDescription(type,
4936 sdesc->description());
4937 } else {
4938 const SessionDescriptionInterface* sdesc = remote_description();
4939 RTC_DCHECK(sdesc);
4940 return transport_controller_->SetRemoteDescription(type,
4941 sdesc->description());
Steve Anton75737c02017-11-06 18:37:174942 }
Steve Anton75737c02017-11-06 18:37:174943}
4944
4945bool PeerConnection::GetTransportDescription(
4946 const SessionDescription* description,
4947 const std::string& content_name,
4948 cricket::TransportDescription* tdesc) {
4949 if (!description || !tdesc) {
4950 return false;
4951 }
4952 const TransportInfo* transport_info =
4953 description->GetTransportInfoByName(content_name);
4954 if (!transport_info) {
4955 return false;
4956 }
4957 *tdesc = transport_info->description;
4958 return true;
4959}
4960
Steve Anton75737c02017-11-06 18:37:174961cricket::IceConfig PeerConnection::ParseIceConfig(
4962 const PeerConnectionInterface::RTCConfiguration& config) const {
4963 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:174964 switch (config.continual_gathering_policy) {
4965 case PeerConnectionInterface::GATHER_ONCE:
4966 gathering_policy = cricket::GATHER_ONCE;
4967 break;
4968 case PeerConnectionInterface::GATHER_CONTINUALLY:
4969 gathering_policy = cricket::GATHER_CONTINUALLY;
4970 break;
4971 default:
4972 RTC_NOTREACHED();
4973 gathering_policy = cricket::GATHER_ONCE;
4974 }
Qingsi Wang9a5c6f82018-02-01 18:38:404975
Steve Anton75737c02017-11-06 18:37:174976 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:234977 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4978 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:174979 ice_config.prioritize_most_likely_candidate_pairs =
4980 config.prioritize_most_likely_ice_candidate_pairs;
4981 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:234982 RTCConfigurationToIceConfigOptionalInt(
4983 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:174984 ice_config.continual_gathering_policy = gathering_policy;
4985 ice_config.presume_writable_when_fully_relayed =
4986 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:144987 ice_config.ice_check_interval_strong_connectivity =
4988 config.ice_check_interval_strong_connectivity;
4989 ice_config.ice_check_interval_weak_connectivity =
4990 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:174991 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:494992 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:174993 ice_config.regather_all_networks_interval_range =
4994 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:404995 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:174996 return ice_config;
4997}
4998
Steve Anton75737c02017-11-06 18:37:174999bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5000 std::string* track_id) {
5001 if (!local_description()) {
5002 return false;
5003 }
5004 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5005 track_id);
5006}
5007
5008bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5009 std::string* track_id) {
5010 if (!remote_description()) {
5011 return false;
5012 }
5013 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5014 track_id);
5015}
5016
5017bool PeerConnection::SendData(const cricket::SendDataParams& params,
5018 const rtc::CopyOnWriteBuffer& payload,
5019 cricket::SendDataResult* result) {
5020 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255021 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 09:37:075022 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175023 return false;
5024 }
5025 return rtp_data_channel_
5026 ? rtp_data_channel_->SendData(params, payload, result)
5027 : network_thread()->Invoke<bool>(
5028 RTC_FROM_HERE,
5029 Bind(&cricket::SctpTransportInternal::SendData,
5030 sctp_transport_.get(), params, payload, result));
5031}
5032
5033bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5034 if (!rtp_data_channel_ && !sctp_transport_) {
5035 // Don't log an error here, because DataChannels are expected to call
5036 // ConnectDataChannel in this state. It's the only way to initially tell
5037 // whether or not the underlying transport is ready.
5038 return false;
5039 }
5040 if (rtp_data_channel_) {
5041 rtp_data_channel_->SignalReadyToSendData.connect(
5042 webrtc_data_channel, &DataChannel::OnChannelReady);
5043 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5044 &DataChannel::OnDataReceived);
5045 } else {
5046 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5047 &DataChannel::OnChannelReady);
5048 SignalSctpDataReceived.connect(webrtc_data_channel,
5049 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325050 SignalSctpClosingProcedureStartedRemotely.connect(
5051 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5052 SignalSctpClosingProcedureComplete.connect(
5053 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175054 }
5055 return true;
5056}
5057
5058void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5059 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255060 RTC_LOG(LS_ERROR)
5061 << "DisconnectDataChannel called when rtp_data_channel_ and "
5062 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175063 return;
5064 }
5065 if (rtp_data_channel_) {
5066 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5067 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5068 } else {
5069 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5070 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325071 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5072 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175073 }
5074}
5075
5076void PeerConnection::AddSctpDataStream(int sid) {
5077 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255078 RTC_LOG(LS_ERROR)
5079 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175080 return;
5081 }
5082 network_thread()->Invoke<void>(
5083 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5084 sctp_transport_.get(), sid));
5085}
5086
5087void PeerConnection::RemoveSctpDataStream(int sid) {
5088 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255089 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075090 "NULL.";
Steve Anton75737c02017-11-06 18:37:175091 return;
5092 }
5093 network_thread()->Invoke<void>(
5094 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5095 sctp_transport_.get(), sid));
5096}
5097
5098bool PeerConnection::ReadyToSendData() const {
5099 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5100 sctp_ready_to_send_data_;
5101}
5102
Danil Chapovalov66cadcc2018-06-19 14:47:435103absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 17:48:355104 if (sctp_mid_ && transport_controller_) {
5105 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5106 if (dtls_transport) {
5107 return dtls_transport->transport_name();
5108 }
Danil Chapovalov66cadcc2018-06-19 14:47:435109 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355110 }
Danil Chapovalov66cadcc2018-06-19 14:47:435111 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355112}
5113
Qingsi Wang72a43a12018-02-21 00:03:185114cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5115 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455116 network_thread()->Invoke<void>(
5117 RTC_FROM_HERE,
5118 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5119 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185120 return candidate_states_list;
5121}
5122
Steve Anton5dfde182018-02-06 18:34:405123std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5124 const {
5125 std::map<std::string, std::string> transport_names_by_mid;
5126 for (auto transceiver : transceivers_) {
5127 cricket::BaseChannel* channel = transceiver->internal()->channel();
5128 if (channel) {
5129 transport_names_by_mid[channel->content_name()] =
5130 channel->transport_name();
5131 }
Steve Anton75737c02017-11-06 18:37:175132 }
Steve Anton5dfde182018-02-06 18:34:405133 if (rtp_data_channel_) {
5134 transport_names_by_mid[rtp_data_channel_->content_name()] =
5135 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175136 }
5137 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435138 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355139 RTC_DCHECK(transport_name);
5140 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175141 }
Steve Anton5dfde182018-02-06 18:34:405142 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175143}
5144
Steve Anton5dfde182018-02-06 18:34:405145std::map<std::string, cricket::TransportStats>
5146PeerConnection::GetTransportStatsByNames(
5147 const std::set<std::string>& transport_names) {
5148 if (!network_thread()->IsCurrent()) {
5149 return network_thread()
5150 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5151 RTC_FROM_HERE,
5152 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175153 }
Steve Anton5dfde182018-02-06 18:34:405154 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5155 for (const std::string& transport_name : transport_names) {
5156 cricket::TransportStats transport_stats;
5157 bool success =
5158 transport_controller_->GetStats(transport_name, &transport_stats);
5159 if (success) {
5160 transport_stats_by_name[transport_name] = std::move(transport_stats);
5161 } else {
5162 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5163 << transport_name;
5164 }
5165 }
5166 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175167}
5168
5169bool PeerConnection::GetLocalCertificate(
5170 const std::string& transport_name,
5171 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355172 if (!certificate) {
5173 return false;
5174 }
5175 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5176 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175177}
5178
Taylor Brandstetterc3928662018-02-23 21:04:515179std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175180 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515181 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175182}
5183
5184cricket::DataChannelType PeerConnection::data_channel_type() const {
5185 return data_channel_type_;
5186}
5187
5188bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5189 return pending_ice_restarts_.find(content_name) !=
5190 pending_ice_restarts_.end();
5191}
5192
Steve Anton75737c02017-11-06 18:37:175193bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5194 return transport_controller_->NeedsIceRestart(content_name);
5195}
5196
5197void PeerConnection::OnCertificateReady(
5198 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5199 transport_controller_->SetLocalCertificate(certificate);
5200}
5201
5202void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215203 SetSessionError(SessionError::kTransport,
5204 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175205}
5206
5207void PeerConnection::OnTransportControllerConnectionState(
5208 cricket::IceConnectionState state) {
5209 switch (state) {
5210 case cricket::kIceConnectionConnecting:
5211 // If the current state is Connected or Completed, then there were
5212 // writable channels but now there are not, so the next state must
5213 // be Disconnected.
5214 // kIceConnectionConnecting is currently used as the default,
5215 // un-connected state by the TransportController, so its only use is
5216 // detecting disconnections.
5217 if (ice_connection_state_ ==
5218 PeerConnectionInterface::kIceConnectionConnected ||
5219 ice_connection_state_ ==
5220 PeerConnectionInterface::kIceConnectionCompleted) {
5221 SetIceConnectionState(
5222 PeerConnectionInterface::kIceConnectionDisconnected);
5223 }
5224 break;
5225 case cricket::kIceConnectionFailed:
5226 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5227 break;
5228 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:255229 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 09:37:075230 "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:175231 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 12:00:345232 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 18:37:175233 break;
5234 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:255235 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 09:37:075236 "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:175237 if (ice_connection_state_ !=
5238 PeerConnectionInterface::kIceConnectionConnected) {
5239 // If jumping directly from "checking" to "connected",
5240 // signal "connected" first.
5241 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5242 }
5243 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 12:00:345244 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 19:54:535245 ReportTransportStats();
Steve Anton75737c02017-11-06 18:37:175246 break;
5247 default:
5248 RTC_NOTREACHED();
5249 }
5250}
5251
5252void PeerConnection::OnTransportControllerCandidatesGathered(
5253 const std::string& transport_name,
5254 const cricket::Candidates& candidates) {
5255 RTC_DCHECK(signaling_thread()->IsCurrent());
5256 int sdp_mline_index;
5257 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255258 RTC_LOG(LS_ERROR)
5259 << "OnTransportControllerCandidatesGathered: content name "
5260 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175261 return;
5262 }
5263
5264 for (cricket::Candidates::const_iterator citer = candidates.begin();
5265 citer != candidates.end(); ++citer) {
5266 // Use transport_name as the candidate media id.
5267 std::unique_ptr<JsepIceCandidate> candidate(
5268 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5269 if (local_description()) {
5270 mutable_local_description()->AddCandidate(candidate.get());
5271 }
5272 OnIceCandidate(std::move(candidate));
5273 }
5274}
5275
5276void PeerConnection::OnTransportControllerCandidatesRemoved(
5277 const std::vector<cricket::Candidate>& candidates) {
5278 RTC_DCHECK(signaling_thread()->IsCurrent());
5279 // Sanity check.
5280 for (const cricket::Candidate& candidate : candidates) {
5281 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255282 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075283 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255284 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175285 return;
5286 }
5287 }
5288
5289 if (local_description()) {
5290 mutable_local_description()->RemoveCandidates(candidates);
5291 }
5292 OnIceCandidatesRemoved(candidates);
5293}
5294
5295void PeerConnection::OnTransportControllerDtlsHandshakeError(
5296 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 19:54:535297 RTC_HISTOGRAM_ENUMERATION(
5298 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5299 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:175300}
5301
Steve Antoned10bd92017-12-05 18:52:595302void PeerConnection::EnableSending() {
5303 for (auto transceiver : transceivers_) {
5304 cricket::BaseChannel* channel = transceiver->internal()->channel();
5305 if (channel && !channel->enabled()) {
5306 channel->Enable(true);
5307 }
Steve Anton75737c02017-11-06 18:37:175308 }
5309
Steve Anton4171afb2017-11-20 18:20:225310 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175311 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225312 }
Steve Anton75737c02017-11-06 18:37:175313}
5314
5315// Returns the media index for a local ice candidate given the content name.
5316bool PeerConnection::GetLocalCandidateMediaIndex(
5317 const std::string& content_name,
5318 int* sdp_mline_index) {
5319 if (!local_description() || !sdp_mline_index) {
5320 return false;
5321 }
5322
5323 bool content_found = false;
5324 const ContentInfos& contents = local_description()->description()->contents();
5325 for (size_t index = 0; index < contents.size(); ++index) {
5326 if (contents[index].name == content_name) {
5327 *sdp_mline_index = static_cast<int>(index);
5328 content_found = true;
5329 break;
5330 }
5331 }
5332 return content_found;
5333}
5334
5335bool PeerConnection::UseCandidatesInSessionDescription(
5336 const SessionDescriptionInterface* remote_desc) {
5337 if (!remote_desc) {
5338 return true;
5339 }
5340 bool ret = true;
5341
5342 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5343 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5344 for (size_t n = 0; n < candidates->count(); ++n) {
5345 const IceCandidateInterface* candidate = candidates->at(n);
5346 bool valid = false;
5347 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5348 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255349 RTC_LOG(LS_INFO)
5350 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075351 "candidate.";
Steve Anton75737c02017-11-06 18:37:175352 }
5353 continue;
5354 }
5355 ret = UseCandidate(candidate);
5356 if (!ret) {
5357 break;
5358 }
5359 }
5360 }
5361 return ret;
5362}
5363
5364bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5365 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5366 size_t remote_content_size =
5367 remote_description()->description()->contents().size();
5368 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255369 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175370 return false;
5371 }
5372
5373 cricket::ContentInfo content =
5374 remote_description()->description()->contents()[mediacontent_index];
5375 std::vector<cricket::Candidate> candidates;
5376 candidates.push_back(candidate->candidate());
5377 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355378 RTCError error =
5379 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505380 if (error.ok()) {
5381 // Candidates successfully submitted for checking.
5382 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5383 ice_connection_state_ ==
5384 PeerConnectionInterface::kIceConnectionDisconnected) {
5385 // If state is New, then the session has just gotten its first remote ICE
5386 // candidates, so go to Checking.
5387 // If state is Disconnected, the session is re-using old candidates or
5388 // receiving additional ones, so go to Checking.
5389 // If state is Connected, stay Connected.
5390 // TODO(bemasc): If state is Connected, and the new candidates are for a
5391 // newly added transport, then the state actually _should_ move to
5392 // checking. Add a way to distinguish that case.
5393 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5394 }
5395 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 08:07:075396 } else {
Zhi Huange830e682018-03-30 17:48:355397 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175398 }
5399 return true;
5400}
5401
5402void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175403 // Destroy video channel first since it may have a pointer to the
5404 // voice channel.
5405 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295406 if (!video_info || video_info->rejected) {
5407 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175408 }
5409
Steve Anton6fec8802017-12-04 18:37:295410 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5411 if (!audio_info || audio_info->rejected) {
5412 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175413 }
5414
5415 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5416 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295417 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175418 }
5419}
5420
Steve Antondcc3c022017-12-23 00:02:545421RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5422 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175423 const cricket::ContentGroup* bundle_group = nullptr;
5424 if (configuration_.bundle_policy ==
5425 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545426 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175427 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5429 "max-bundle configured but session description "
5430 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175431 }
5432 }
Steve Antondcc3c022017-12-23 00:02:545433 return std::move(bundle_group);
5434}
5435
5436RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355437 // Creating the media channels. Transports should already have been created
5438 // at this point.
Steve Antondcc3c022017-12-23 00:02:545439 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555440 if (voice && !voice->rejected &&
5441 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355442 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555443 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565444 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5445 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555446 }
5447 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5448 }
5449
Steve Antondcc3c022017-12-23 00:02:545450 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555451 if (video && !video->rejected &&
5452 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355453 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555454 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565455 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5456 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175457 }
Steve Antoneda6ccd2017-12-04 18:21:555458 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175459 }
5460
Steve Antondcc3c022017-12-23 00:02:545461 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175462 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5463 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355464 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565465 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5466 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175467 }
5468 }
5469
Steve Anton8a006912017-12-04 23:25:565470 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175471}
5472
Steve Anton4171afb2017-11-20 18:20:225473// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555474cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355475 const std::string& mid) {
5476 RtpTransportInternal* rtp_transport =
5477 transport_controller_->GetRtpTransport(mid);
5478 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175479 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355480 call_.get(), configuration_.media_config, rtp_transport,
5481 signaling_thread(), mid, SrtpRequired(),
5482 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 18:37:175483 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555484 return nullptr;
Steve Anton75737c02017-11-06 18:37:175485 }
Steve Anton75737c02017-11-06 18:37:175486 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5487 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175488 voice_channel->SignalSentPacket.connect(this,
5489 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355490 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225491
Steve Antoneda6ccd2017-12-04 18:21:555492 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175493}
5494
Steve Anton4171afb2017-11-20 18:20:225495// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555496cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355497 const std::string& mid) {
5498 RtpTransportInternal* rtp_transport =
5499 transport_controller_->GetRtpTransport(mid);
5500 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175501 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355502 call_.get(), configuration_.media_config, rtp_transport,
5503 signaling_thread(), mid, SrtpRequired(),
5504 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 18:37:175505 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555506 return nullptr;
Steve Anton75737c02017-11-06 18:37:175507 }
Steve Anton75737c02017-11-06 18:37:175508 video_channel->SignalDtlsSrtpSetupFailure.connect(
5509 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175510 video_channel->SignalSentPacket.connect(this,
5511 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355512 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225513
Steve Antoneda6ccd2017-12-04 18:21:555514 return video_channel;
Steve Anton75737c02017-11-06 18:37:175515}
5516
Zhi Huange830e682018-03-30 17:48:355517bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175518 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5519 if (sctp) {
5520 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255521 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175522 << "Trying to create SCTP transport, but didn't compile with "
5523 "SCTP support (HAVE_SCTP)";
5524 return false;
5525 }
5526 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 17:48:355527 RTC_FROM_HERE,
5528 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 18:37:175529 return false;
5530 }
Steve Antoneda6ccd2017-12-04 18:21:555531 for (const auto& channel : sctp_data_channels_) {
5532 channel->OnTransportChannelCreated();
5533 }
Steve Anton75737c02017-11-06 18:37:175534 } else {
Zhi Huange830e682018-03-30 17:48:355535 RtpTransportInternal* rtp_transport =
5536 transport_controller_->GetRtpTransport(mid);
5537 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175538 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 17:48:355539 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5540 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 18:37:175541 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175542 return false;
5543 }
Steve Anton75737c02017-11-06 18:37:175544 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5545 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5546 rtp_data_channel_->SignalSentPacket.connect(
5547 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355548 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175549 }
5550
Steve Anton75737c02017-11-06 18:37:175551 return true;
5552}
5553
5554Call::Stats PeerConnection::GetCallStats() {
5555 if (!worker_thread()->IsCurrent()) {
5556 return worker_thread()->Invoke<Call::Stats>(
5557 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5558 }
5559 if (call_) {
5560 return call_->GetStats();
5561 } else {
5562 return Call::Stats();
5563 }
5564}
5565
Zhi Huange830e682018-03-30 17:48:355566bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175567 RTC_DCHECK(network_thread()->IsCurrent());
5568 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265569 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355570 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265571 RTC_DCHECK(dtls_transport);
5572 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175573 RTC_DCHECK(sctp_transport_);
5574 sctp_invoker_.reset(new rtc::AsyncInvoker());
5575 sctp_transport_->SignalReadyToSendData.connect(
5576 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5577 sctp_transport_->SignalDataReceived.connect(
5578 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:325579 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5580 // another thread. Would be nice if there was a helper class similar to
5581 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5582 // code.
5583 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5584 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5585 sctp_transport_->SignalClosingProcedureComplete.connect(
5586 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:355587 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265588 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355589 return true;
Steve Anton75737c02017-11-06 18:37:175590}
5591
5592void PeerConnection::DestroySctpTransport_n() {
5593 RTC_DCHECK(network_thread()->IsCurrent());
5594 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355595 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175596 sctp_invoker_.reset(nullptr);
5597 sctp_ready_to_send_data_ = false;
5598}
5599
5600void PeerConnection::OnSctpTransportReadyToSendData_n() {
5601 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5602 RTC_DCHECK(network_thread()->IsCurrent());
5603 // Note: Cannot use rtc::Bind here because it will grab a reference to
5604 // PeerConnection and potentially cause PeerConnection to live longer than
5605 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5606 // be destroyed before PeerConnection is destroyed, and at that point all
5607 // pending tasks will be cleared.
5608 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5609 OnSctpTransportReadyToSendData_s(true);
5610 });
5611}
5612
5613void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5614 RTC_DCHECK(signaling_thread()->IsCurrent());
5615 sctp_ready_to_send_data_ = ready;
5616 SignalSctpReadyToSendData(ready);
5617}
5618
5619void PeerConnection::OnSctpTransportDataReceived_n(
5620 const cricket::ReceiveDataParams& params,
5621 const rtc::CopyOnWriteBuffer& payload) {
5622 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5623 RTC_DCHECK(network_thread()->IsCurrent());
5624 // Note: Cannot use rtc::Bind here because it will grab a reference to
5625 // PeerConnection and potentially cause PeerConnection to live longer than
5626 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5627 // be destroyed before PeerConnection is destroyed, and at that point all
5628 // pending tasks will be cleared.
5629 sctp_invoker_->AsyncInvoke<void>(
5630 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5631 OnSctpTransportDataReceived_s(params, payload);
5632 });
5633}
5634
5635void PeerConnection::OnSctpTransportDataReceived_s(
5636 const cricket::ReceiveDataParams& params,
5637 const rtc::CopyOnWriteBuffer& payload) {
5638 RTC_DCHECK(signaling_thread()->IsCurrent());
5639 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5640 // Received OPEN message; parse and signal that a new data channel should
5641 // be created.
5642 std::string label;
5643 InternalDataChannelInit config;
5644 config.id = params.ssrc;
5645 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255646 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5647 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175648 return;
5649 }
5650 config.open_handshake_role = InternalDataChannelInit::kAcker;
5651 OnDataChannelOpenMessage(label, config);
5652 } else {
5653 // Otherwise just forward the signal.
5654 SignalSctpDataReceived(params, payload);
5655 }
5656}
5657
Taylor Brandstettercdd05f02018-05-31 20:23:325658void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:175659 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5660 RTC_DCHECK(network_thread()->IsCurrent());
5661 sctp_invoker_->AsyncInvoke<void>(
5662 RTC_FROM_HERE, signaling_thread(),
5663 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:325664 &SignalSctpClosingProcedureStartedRemotely, sid));
5665}
5666
5667void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5668 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5669 RTC_DCHECK(network_thread()->IsCurrent());
5670 sctp_invoker_->AsyncInvoke<void>(
5671 RTC_FROM_HERE, signaling_thread(),
5672 rtc::Bind(&sigslot::signal1<int>::operator(),
5673 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:175674}
5675
5676// Returns false if bundle is enabled and rtcp_mux is disabled.
5677bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5678 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5679 if (!bundle_enabled)
5680 return true;
5681
5682 const cricket::ContentGroup* bundle_group =
5683 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5684 RTC_DCHECK(bundle_group != NULL);
5685
5686 const cricket::ContentInfos& contents = desc->contents();
5687 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5688 citer != contents.end(); ++citer) {
5689 const cricket::ContentInfo* content = (&*citer);
5690 RTC_DCHECK(content != NULL);
5691 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005692 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175693 if (!HasRtcpMuxEnabled(content))
5694 return false;
5695 }
5696 }
5697 // RTCP-MUX is enabled in all the contents.
5698 return true;
5699}
5700
5701bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305702 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175703}
5704
Steve Anton8a006912017-12-04 23:25:565705RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175706 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565707 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215708 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565709 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175710 }
5711
5712 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175714 }
5715
Steve Anton3828c062017-12-06 18:34:515716 SdpType type = sdesc->GetType();
5717 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5718 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565719 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:035720 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:565721 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175722 }
5723
5724 // Verify crypto settings.
5725 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565726 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5727 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:535728 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:565729 if (!crypto_error.ok()) {
5730 return crypto_error;
5731 }
Steve Anton75737c02017-11-06 18:37:175732 }
5733
5734 // Verify ice-ufrag and ice-pwd.
5735 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565736 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5737 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175738 }
5739
5740 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5742 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175743 }
5744
5745 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5746 // m-lines that do not rtcp-mux enabled.
5747
5748 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515749 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:485750 // With an answer we want to compare the new answer session description with
5751 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:175752 const cricket::SessionDescription* offer_desc =
5753 (source == cricket::CS_LOCAL) ? remote_description()->description()
5754 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:485755 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5756 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5757 type)) {
Steve Anton8a006912017-12-04 23:25:565758 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5759 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175760 }
5761 } else {
Steve Anton75737c02017-11-06 18:37:175762 // The re-offers should respect the order of m= sections in current
5763 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:485764 // With a re-offer, either the current local or current remote descriptions
5765 // could be the most up to date, so we would like to check against both of
5766 // them if they exist. It could be the case that one of them has a 0 port
5767 // for a media section, but the other does not. This is important to check
5768 // against in the case that we are recycling an m= section.
5769 const cricket::SessionDescription* current_desc = nullptr;
5770 const cricket::SessionDescription* secondary_current_desc = nullptr;
5771 if (local_description()) {
5772 current_desc = local_description()->description();
5773 if (remote_description()) {
5774 secondary_current_desc = remote_description()->description();
5775 }
5776 } else if (remote_description()) {
5777 current_desc = remote_description()->description();
5778 }
Steve Anton75737c02017-11-06 18:37:175779 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:485780 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5781 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:565782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5783 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175784 }
5785 }
5786
Steve Antonba42e992018-04-09 21:10:015787 if (IsUnifiedPlan()) {
5788 // Ensure that each audio and video media section has at most one
5789 // "StreamParams". This will return an error if receiving a session
5790 // description from a "Plan B" endpoint which adds multiple tracks of the
5791 // same type. With Unified Plan, there can only be at most one track per
5792 // media section.
5793 for (const ContentInfo& content : sdesc->description()->contents()) {
5794 const MediaContentDescription& desc = *content.description;
5795 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5796 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5797 desc.streams().size() > 1u) {
5798 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5799 "Media section has more than one track specified "
5800 "with a=ssrc lines which is not supported with "
5801 "Unified Plan.");
5802 }
5803 }
5804 }
5805
Steve Anton8a006912017-12-04 23:25:565806 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175807}
5808
Steve Anton3828c062017-12-06 18:34:515809bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175810 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515811 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175812 return (state == PeerConnectionInterface::kStable) ||
5813 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525814 } else {
Steve Anton3828c062017-12-06 18:34:515815 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175816 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5817 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5818 }
5819}
5820
Steve Anton3828c062017-12-06 18:34:515821bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175822 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515823 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175824 return (state == PeerConnectionInterface::kStable) ||
5825 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525826 } else {
Steve Anton3828c062017-12-06 18:34:515827 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175828 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5829 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5830 }
5831}
5832
Steve Antonf8470812017-12-04 18:46:215833const char* PeerConnection::SessionErrorToString(SessionError error) const {
5834 switch (error) {
5835 case SessionError::kNone:
5836 return "ERROR_NONE";
5837 case SessionError::kContent:
5838 return "ERROR_CONTENT";
5839 case SessionError::kTransport:
5840 return "ERROR_TRANSPORT";
5841 }
5842 RTC_NOTREACHED();
5843 return "";
5844}
5845
Steve Anton75737c02017-11-06 18:37:175846std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:305847 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:215848 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5849 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:325850 return desc.Release();
Steve Anton75737c02017-11-06 18:37:175851}
5852
Steve Anton8e20f172018-03-06 18:55:045853void PeerConnection::ReportSdpFormatReceived(
5854 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:045855 int num_audio_mlines = 0;
5856 int num_video_mlines = 0;
5857 int num_audio_tracks = 0;
5858 int num_video_tracks = 0;
5859 for (const ContentInfo& content : remote_offer.description()->contents()) {
5860 cricket::MediaType media_type = content.media_description()->type();
5861 int num_tracks = std::max(
5862 1, static_cast<int>(content.media_description()->streams().size()));
5863 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5864 num_audio_mlines += 1;
5865 num_audio_tracks += num_tracks;
5866 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5867 num_video_mlines += 1;
5868 num_video_tracks += num_tracks;
5869 }
5870 }
5871 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5872 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5873 format = kSdpFormatReceivedComplexUnifiedPlan;
5874 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5875 format = kSdpFormatReceivedComplexPlanB;
5876 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5877 format = kSdpFormatReceivedSimple;
5878 }
Qingsi Wang7fc821d2018-07-12 19:54:535879 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5880 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:045881}
5882
Harald Alvestrand8ebba742018-05-31 12:00:345883void PeerConnection::NoteUsageEvent(UsageEvent event) {
5884 RTC_DCHECK_RUN_ON(signaling_thread());
5885 usage_event_accumulator_ |= static_cast<int>(event);
5886}
5887
5888void PeerConnection::ReportUsagePattern() const {
5889 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 19:54:535890 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5891 usage_event_accumulator_,
5892 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:555893 const int bad_bits =
5894 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5895 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5896 const int good_bits =
5897 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5898 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5899 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5900 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5901 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 08:50:165902 // If called after close(), we can't report, because observer may have
5903 // been deallocated, and therefore pointer is null. Write to log instead.
5904 if (observer_) {
5905 Observer()->OnInterestingUsage(usage_event_accumulator_);
5906 } else {
5907 RTC_LOG(LS_INFO) << "Interesting usage signature "
5908 << usage_event_accumulator_
5909 << " observed after observer shutdown";
5910 }
Harald Alvestrandc0e97252018-07-26 08:39:555911 }
Harald Alvestrand8ebba742018-05-31 12:00:345912}
5913
Steve Anton0ffaaa22018-02-23 18:31:305914void PeerConnection::ReportNegotiatedSdpSemantics(
5915 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:535916 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:305917 switch (answer.description()->msid_signaling()) {
5918 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:535919 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:305920 break;
5921 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:535922 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:305923 break;
5924 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:535925 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:305926 break;
5927 case cricket::kMsidSignalingMediaSection |
5928 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:535929 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:305930 break;
5931 default:
5932 RTC_NOTREACHED();
5933 }
Qingsi Wang7fc821d2018-07-12 19:54:535934 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5935 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:305936}
5937
Steve Anton75737c02017-11-06 18:37:175938// We need to check the local/remote description for the Transport instead of
5939// the session, because a new Transport added during renegotiation may have
5940// them unset while the session has them set from the previous negotiation.
5941// Not doing so may trigger the auto generation of transport description and
5942// mess up DTLS identity information, ICE credential, etc.
5943bool PeerConnection::ReadyToUseRemoteCandidate(
5944 const IceCandidateInterface* candidate,
5945 const SessionDescriptionInterface* remote_desc,
5946 bool* valid) {
5947 *valid = true;
5948
5949 const SessionDescriptionInterface* current_remote_desc =
5950 remote_desc ? remote_desc : remote_description();
5951
5952 if (!current_remote_desc) {
5953 return false;
5954 }
5955
5956 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5957 size_t remote_content_size =
5958 current_remote_desc->description()->contents().size();
5959 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255960 RTC_LOG(LS_ERROR)
5961 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5962 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:175963
5964 *valid = false;
5965 return false;
5966 }
5967
5968 cricket::ContentInfo content =
5969 current_remote_desc->description()->contents()[mediacontent_index];
5970
5971 const std::string transport_name = GetTransportName(content.name);
5972 if (transport_name.empty()) {
5973 return false;
5974 }
Zhi Huange830e682018-03-30 17:48:355975 return true;
Steve Anton75737c02017-11-06 18:37:175976}
5977
5978bool PeerConnection::SrtpRequired() const {
5979 return dtls_enabled_ ||
5980 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5981}
5982
5983void PeerConnection::OnTransportControllerGatheringState(
5984 cricket::IceGatheringState state) {
5985 RTC_DCHECK(signaling_thread()->IsCurrent());
5986 if (state == cricket::kIceGatheringGathering) {
5987 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5988 } else if (state == cricket::kIceGatheringComplete) {
5989 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5990 }
5991}
5992
5993void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:455994 std::map<std::string, std::set<cricket::MediaType>>
5995 media_types_by_transport_name;
5996 for (auto transceiver : transceivers_) {
5997 if (transceiver->internal()->channel()) {
5998 const std::string& transport_name =
5999 transceiver->internal()->channel()->transport_name();
6000 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086001 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456002 }
Steve Anton75737c02017-11-06 18:37:176003 }
6004 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456005 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6006 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176007 }
Zhi Huange830e682018-03-30 17:48:356008
Danil Chapovalov66cadcc2018-06-19 14:47:436009 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356010 if (transport_name) {
6011 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456012 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176013 }
Zhi Huange830e682018-03-30 17:48:356014
Steve Antonc7b964c2018-02-01 22:39:456015 for (const auto& entry : media_types_by_transport_name) {
6016 const std::string& transport_name = entry.first;
6017 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176018 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456019 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176020 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456021 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176022 }
6023 }
6024}
6025// Walk through the ConnectionInfos to gather best connection usage
6026// for IPv4 and IPv6.
6027void PeerConnection::ReportBestConnectionState(
6028 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 22:39:456029 for (const cricket::TransportChannelStats& channel_stats :
6030 stats.channel_stats) {
6031 for (const cricket::ConnectionInfo& connection_info :
6032 channel_stats.connection_infos) {
6033 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176034 continue;
6035 }
6036
Steve Antonc7b964c2018-02-01 22:39:456037 const cricket::Candidate& local = connection_info.local_candidate;
6038 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176039
6040 // Increment the counter for IceCandidatePairType.
6041 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6042 (local.type() == RELAY_PORT_TYPE &&
6043 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 19:54:536044 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6045 GetIceCandidatePairCounter(local, remote),
6046 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176047 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536048 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6049 GetIceCandidatePairCounter(local, remote),
6050 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176051 } else {
6052 RTC_CHECK(0);
6053 }
Steve Anton75737c02017-11-06 18:37:176054
6055 // Increment the counter for IP type.
6056 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536057 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6058 kBestConnections_IPv4,
6059 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176060 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536061 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6062 kBestConnections_IPv6,
6063 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176064 } else {
6065 RTC_CHECK(0);
6066 }
6067
6068 return;
6069 }
6070 }
6071}
6072
6073void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456074 const cricket::TransportStats& stats,
6075 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176076 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6077 return;
6078 }
6079
6080 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6081 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6082 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6083 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6084 return;
6085 }
6086
Qingsi Wang7fc821d2018-07-12 19:54:536087 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6088 for (cricket::MediaType media_type : media_types) {
6089 switch (media_type) {
6090 case cricket::MEDIA_TYPE_AUDIO:
6091 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6092 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6093 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6094 break;
6095 case cricket::MEDIA_TYPE_VIDEO:
6096 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6097 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6098 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6099 break;
6100 case cricket::MEDIA_TYPE_DATA:
6101 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6102 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6103 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6104 break;
6105 default:
6106 RTC_NOTREACHED();
6107 continue;
6108 }
Steve Antonc7b964c2018-02-01 22:39:456109 }
Qingsi Wang7fc821d2018-07-12 19:54:536110 }
6111
6112 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6113 for (cricket::MediaType media_type : media_types) {
6114 switch (media_type) {
6115 case cricket::MEDIA_TYPE_AUDIO:
6116 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6117 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6118 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6119 break;
6120 case cricket::MEDIA_TYPE_VIDEO:
6121 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6122 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6123 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6124 break;
6125 case cricket::MEDIA_TYPE_DATA:
6126 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6127 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6128 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6129 break;
6130 default:
6131 RTC_NOTREACHED();
6132 continue;
6133 }
Steve Antonc7b964c2018-02-01 22:39:456134 }
Steve Anton75737c02017-11-06 18:37:176135 }
6136}
6137
6138void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6139 RTC_DCHECK(worker_thread()->IsCurrent());
6140 RTC_DCHECK(call_);
6141 call_->OnSentPacket(sent_packet);
6142}
6143
6144const std::string PeerConnection::GetTransportName(
6145 const std::string& content_name) {
6146 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296147 if (channel) {
6148 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176149 }
Steve Anton6fec8802017-12-04 18:37:296150 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356151 RTC_DCHECK(sctp_mid_);
6152 if (content_name == *sctp_mid_) {
6153 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296154 }
6155 }
6156 // Return an empty string if failed to retrieve the transport name.
6157 return "";
Steve Anton75737c02017-11-06 18:37:176158}
6159
Steve Anton6fec8802017-12-04 18:37:296160void PeerConnection::DestroyTransceiverChannel(
6161 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6162 transceiver) {
6163 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176164
Steve Anton6fec8802017-12-04 18:37:296165 cricket::BaseChannel* channel = transceiver->internal()->channel();
6166 if (channel) {
6167 transceiver->internal()->SetChannel(nullptr);
6168 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:176169 }
6170}
6171
6172void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296173 if (rtp_data_channel_) {
6174 OnDataChannelDestroyed();
6175 DestroyBaseChannel(rtp_data_channel_);
6176 rtp_data_channel_ = nullptr;
6177 }
6178
6179 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6180 // grab a reference to this PeerConnection. If this is called from the
6181 // PeerConnection destructor, the RefCountedObject vtable will have already
6182 // been destroyed (since it is a subclass of PeerConnection) and using
6183 // rtc::Bind will cause "Pure virtual function called" error to appear.
6184
6185 if (sctp_transport_) {
6186 OnDataChannelDestroyed();
6187 network_thread()->Invoke<void>(RTC_FROM_HERE,
6188 [this] { DestroySctpTransport_n(); });
6189 }
6190}
6191
6192void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6193 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296194 switch (channel->media_type()) {
6195 case cricket::MEDIA_TYPE_AUDIO:
6196 channel_manager()->DestroyVoiceChannel(
6197 static_cast<cricket::VoiceChannel*>(channel));
6198 break;
6199 case cricket::MEDIA_TYPE_VIDEO:
6200 channel_manager()->DestroyVideoChannel(
6201 static_cast<cricket::VideoChannel*>(channel));
6202 break;
6203 case cricket::MEDIA_TYPE_DATA:
6204 channel_manager()->DestroyRtpDataChannel(
6205 static_cast<cricket::RtpDataChannel*>(channel));
6206 break;
6207 default:
6208 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6209 break;
6210 }
Zhi Huange830e682018-03-30 17:48:356211}
Steve Anton6fec8802017-12-04 18:37:296212
Taylor Brandstettercbaa2542018-04-16 23:42:146213bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356214 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146215 RtpTransportInternal* rtp_transport,
6216 cricket::DtlsTransportInternal* dtls_transport) {
6217 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356218 auto base_channel = GetChannel(mid);
6219 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146220 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356221 }
Taylor Brandstettercbaa2542018-04-16 23:42:146222 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266223 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176224 }
Taylor Brandstettercbaa2542018-04-16 23:42:146225 return ret;
Steve Anton75737c02017-11-06 18:37:176226}
6227
Harald Alvestrand7a1c7f72018-08-01 08:50:166228PeerConnectionObserver* PeerConnection::Observer() const {
6229 // In earlier production code, the pointer was not cleared on close,
6230 // which might have led to undefined behavior if the observer was not
6231 // deallocated, or strange crashes if it was.
6232 // We use CHECK in order to catch such behavior if it exists.
6233 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6234 RTC_CHECK(observer_);
6235 return observer_;
6236}
6237
Harald Alvestrand89061872018-01-02 13:08:346238void PeerConnection::ClearStatsCache() {
6239 if (stats_collector_) {
6240 stats_collector_->ClearCachedStatsReport();
6241 }
6242}
6243
Harald Alvestrand7a1c7f72018-08-01 08:50:166244void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:406245 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6246 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:166247}
6248
henrike@webrtc.org28e20752013-07-10 00:45:366249} // namespace webrtc