blob: 9155b7119aed95cb1394bc88fa66a7a00e3c7355 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
23#include "api/mediaconstraintsinterface.h"
24#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
26#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800109 MSG_FREE_DATACHANNELS,
Harald Alvestrand19793842018-06-25 12:03:50 +0200110 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111};
112
Harald Alvestrand19793842018-06-25 12:03:50 +0200113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200118 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100121 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122};
123
deadbeefab9b2d12015-10-14 11:33:11 -0700124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100130 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700131};
132
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200136 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139};
140
deadbeefab9b2d12015-10-14 11:33:11 -0700141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
176 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 } else {
184 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
185 if (video_media_description_options) {
186 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700187 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700188 }
189 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700190 }
zhihuang1c378ed2017-08-17 14:10:50 -0700191}
olka3c747662017-08-17 06:50:32 -0700192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |session_options| from |rtp_data_channels|.
194void AddRtpDataChannelOptions(
195 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
196 rtp_data_channels,
197 cricket::MediaDescriptionOptions* data_media_description_options) {
198 if (!data_media_description_options) {
199 return;
200 }
deadbeefab9b2d12015-10-14 11:33:11 -0700201 // Check for data channels.
202 for (const auto& kv : rtp_data_channels) {
203 const DataChannel* channel = kv.second;
204 if (channel->state() == DataChannel::kConnecting ||
205 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700206 // Legacy RTP data channels are signaled with the track/stream ID set to
207 // the data channel's label.
208 data_media_description_options->AddRtpDataChannel(channel->label(),
209 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700210 }
211 }
212}
213
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700214uint32_t ConvertIceTransportTypeToCandidateFilter(
215 PeerConnectionInterface::IceTransportsType type) {
216 switch (type) {
217 case PeerConnectionInterface::kNone:
218 return cricket::CF_NONE;
219 case PeerConnectionInterface::kRelay:
220 return cricket::CF_RELAY;
221 case PeerConnectionInterface::kNoHost:
222 return (cricket::CF_ALL & ~cricket::CF_HOST);
223 case PeerConnectionInterface::kAll:
224 return cricket::CF_ALL;
225 default:
nissec80e7412017-01-11 05:56:46 -0800226 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700227 }
228 return cricket::CF_NONE;
229}
230
deadbeef293e9262017-01-11 12:28:30 -0800231// Helper to set an error and return from a method.
232bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
233 if (error) {
234 error->set_type(type);
235 }
236 return type == webrtc::RTCErrorType::NONE;
237}
238
Steve Anton038834f2017-07-14 15:59:59 -0700239bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700240 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700241 if (error_out) {
242 *error_out = std::move(error);
243 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700244 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700245}
246
Steve Antonba818672017-11-06 10:21:57 -0800247std::string GetSignalingStateString(
248 PeerConnectionInterface::SignalingState state) {
249 switch (state) {
250 case PeerConnectionInterface::kStable:
251 return "kStable";
252 case PeerConnectionInterface::kHaveLocalOffer:
253 return "kHaveLocalOffer";
254 case PeerConnectionInterface::kHaveLocalPrAnswer:
255 return "kHavePrAnswer";
256 case PeerConnectionInterface::kHaveRemoteOffer:
257 return "kHaveRemoteOffer";
258 case PeerConnectionInterface::kHaveRemotePrAnswer:
259 return "kHaveRemotePrAnswer";
260 case PeerConnectionInterface::kClosed:
261 return "kClosed";
262 }
263 RTC_NOTREACHED();
264 return "";
265}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700266
Steve Anton75737c02017-11-06 10:37:17 -0800267IceCandidatePairType GetIceCandidatePairCounter(
268 const cricket::Candidate& local,
269 const cricket::Candidate& remote) {
270 const auto& l = local.type();
271 const auto& r = remote.type();
272 const auto& host = LOCAL_PORT_TYPE;
273 const auto& srflx = STUN_PORT_TYPE;
274 const auto& relay = RELAY_PORT_TYPE;
275 const auto& prflx = PRFLX_PORT_TYPE;
276 if (l == host && r == host) {
277 bool local_private = IPIsPrivate(local.address().ipaddr());
278 bool remote_private = IPIsPrivate(remote.address().ipaddr());
279 if (local_private) {
280 if (remote_private) {
281 return kIceCandidatePairHostPrivateHostPrivate;
282 } else {
283 return kIceCandidatePairHostPrivateHostPublic;
284 }
285 } else {
286 if (remote_private) {
287 return kIceCandidatePairHostPublicHostPrivate;
288 } else {
289 return kIceCandidatePairHostPublicHostPublic;
290 }
291 }
292 }
293 if (l == host && r == srflx)
294 return kIceCandidatePairHostSrflx;
295 if (l == host && r == relay)
296 return kIceCandidatePairHostRelay;
297 if (l == host && r == prflx)
298 return kIceCandidatePairHostPrflx;
299 if (l == srflx && r == host)
300 return kIceCandidatePairSrflxHost;
301 if (l == srflx && r == srflx)
302 return kIceCandidatePairSrflxSrflx;
303 if (l == srflx && r == relay)
304 return kIceCandidatePairSrflxRelay;
305 if (l == srflx && r == prflx)
306 return kIceCandidatePairSrflxPrflx;
307 if (l == relay && r == host)
308 return kIceCandidatePairRelayHost;
309 if (l == relay && r == srflx)
310 return kIceCandidatePairRelaySrflx;
311 if (l == relay && r == relay)
312 return kIceCandidatePairRelayRelay;
313 if (l == relay && r == prflx)
314 return kIceCandidatePairRelayPrflx;
315 if (l == prflx && r == host)
316 return kIceCandidatePairPrflxHost;
317 if (l == prflx && r == srflx)
318 return kIceCandidatePairPrflxSrflx;
319 if (l == prflx && r == relay)
320 return kIceCandidatePairPrflxRelay;
321 return kIceCandidatePairMax;
322}
323
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800324// Logic to decide if an m= section can be recycled. This means that the new
325// m= section is not rejected, but the old local or remote m= section is
326// rejected. |old_content_one| and |old_content_two| refer to the m= section
327// of the old remote and old local descriptions in no particular order.
328// We need to check both the old local and remote because either
329// could be the most current from the latest negotation.
330bool IsMediaSectionBeingRecycled(SdpType type,
331 const ContentInfo& content,
332 const ContentInfo* old_content_one,
333 const ContentInfo* old_content_two) {
334 return type == SdpType::kOffer && !content.rejected &&
335 ((old_content_one && old_content_one->rejected) ||
336 (old_content_two && old_content_two->rejected));
337}
338
Steve Anton75737c02017-11-06 10:37:17 -0800339// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800340// |current_desc|. The number of m= sections in |new_desc| should be no
341// less than |current_desc|. In the case of checking an answer's
342// |new_desc|, the |current_desc| is the last offer that was set as the
343// local or remote. In the case of checking an offer's |new_desc| we
344// check against the local and remote descriptions stored from the last
345// negotiation, because either of these could be the most up to date for
346// possible rejected m sections. These are the |current_desc| and
347// |secondary_current_desc|.
348bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
349 const SessionDescription* secondary_current_desc,
350 const SessionDescription& new_desc,
351 const SdpType type) {
352 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800353 return false;
354 }
355
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800356 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
357 const cricket::ContentInfo* secondary_content_info = nullptr;
358 if (secondary_current_desc &&
359 i < secondary_current_desc->contents().size()) {
360 secondary_content_info = &secondary_current_desc->contents()[i];
361 }
362 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
363 &current_desc.contents()[i],
364 secondary_content_info)) {
365 // For new offer descriptions, if the media section can be recycled, it's
366 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800367 continue;
368 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800369 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800370 return false;
371 }
372 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800373 new_desc.contents()[i].media_description();
374 const MediaContentDescription* current_desc_mdesc =
375 current_desc.contents()[i].media_description();
376 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800377 return false;
378 }
379 }
380 return true;
381}
382
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800383bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
384 const SessionDescription& desc2) {
385 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800386}
387
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700388void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
389 cricket::MediaType media_type) {
390 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
391 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100392 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
393 KeyExchangeProtocolMedia>
394 proto_media_counter_map = {
395 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
396 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
398 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
400 kEnumCounterKeyProtocolMediaTypeDtlsData},
401 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
402 kEnumCounterKeyProtocolMediaTypeSdesAudio},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
404 kEnumCounterKeyProtocolMediaTypeSdesVideo},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
406 kEnumCounterKeyProtocolMediaTypeSdesData}};
407
408 auto it = proto_media_counter_map.find({protocol_type, media_type});
409 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700410 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
411 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100412 }
413}
414
Harald Alvestrand76829d72018-07-18 23:24:36 +0200415void NoteAddIceCandidateResult(int result) {
416 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
417 kAddIceCandidateMax);
418}
419
Steve Anton75737c02017-11-06 10:37:17 -0800420// Checks that each non-rejected content has SDES crypto keys or a DTLS
421// fingerprint, unless it's in a BUNDLE group, in which case only the
422// BUNDLE-tag section (first media section/description in the BUNDLE group)
423// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
424// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
425// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700426RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700436 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800437 const std::string& mid = content_info.name;
438 if (bundle && bundle->HasContentName(mid) &&
439 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800440 // This isn't the first media section in the BUNDLE group, so it's not
441 // required to have crypto attributes, since only the crypto attributes
442 // from the first section actually get used.
443 continue;
444 }
445
446 // If the content isn't rejected or bundled into another m= section, crypto
447 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800448 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800449 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800450 if (!media || !tinfo) {
451 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800453 }
454 if (dtls_enabled) {
455 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_WARNING)
457 << "Session description must have DTLS fingerprint if "
458 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800459 return RTCError(RTCErrorType::INVALID_PARAMETER,
460 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800461 }
462 } else {
463 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800465 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800466 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800467 }
468 }
469 }
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800471}
472
473// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
474// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
475// media section/description in the BUNDLE group) needs a ufrag and pwd.
476bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have ufrag/password, since only the ufrag/password from
488 // the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section,
493 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800503 return false;
504 }
505 }
506 return true;
507}
508
509bool GetTrackIdBySsrc(const SessionDescription* session_description,
510 uint32_t ssrc,
511 std::string* track_id) {
512 RTC_DCHECK(track_id != NULL);
513
Steve Antonb1c1de12017-12-21 15:14:30 -0800514 const cricket::AudioContentDescription* audio_desc =
515 cricket::GetFirstAudioContentDescription(session_description);
516 if (audio_desc) {
517 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::VideoContentDescription* video_desc =
525 cricket::GetFirstVideoContentDescription(session_description);
526 if (video_desc) {
527 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800528 if (found) {
529 *track_id = found->id;
530 return true;
531 }
532 }
533 return false;
534}
535
536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
596 std::ostringstream oss;
597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
599 return oss.str();
600}
601
Seth Hampson5b4f0752018-04-02 16:31:36 -0700602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200613absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200617 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700618 }
619 return rtc_configuration_parameter;
620}
621
Steve Anton75737c02017-11-06 10:37:17 -0800622} // namespace
623
Henrik Boström31638672017-11-23 17:48:32 +0100624// Upon completion, posts a task to execute the callback of the
625// SetSessionDescriptionObserver asynchronously on the same thread. At this
626// point, the state of the peer connection might no longer reflect the effects
627// of the SetRemoteDescription operation, as the peer connection could have been
628// modified during the post.
629// TODO(hbos): Remove this class once we remove the version of
630// PeerConnectionInterface::SetRemoteDescription() that takes a
631// SetSessionDescriptionObserver as an argument.
632class PeerConnection::SetRemoteDescriptionObserverAdapter
633 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
634 public:
635 SetRemoteDescriptionObserverAdapter(
636 rtc::scoped_refptr<PeerConnection> pc,
637 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
638 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
639
640 // SetRemoteDescriptionObserverInterface implementation.
641 void OnSetRemoteDescriptionComplete(RTCError error) override {
642 if (error.ok())
643 pc_->PostSetSessionDescriptionSuccess(wrapper_);
644 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100645 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100646 }
647
648 private:
649 rtc::scoped_refptr<PeerConnection> pc_;
650 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
651};
652
deadbeef293e9262017-01-11 12:28:30 -0800653bool PeerConnectionInterface::RTCConfiguration::operator==(
654 const PeerConnectionInterface::RTCConfiguration& o) const {
655 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700656 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800657 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000658 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700659 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800660 BundlePolicy bundle_policy;
661 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700662 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
663 int ice_candidate_pool_size;
664 bool disable_ipv6;
665 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700666 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100667 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700668 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200669 absl::optional<int> screencast_min_bitrate;
670 absl::optional<bool> combined_audio_video_bwe;
671 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800672 TcpCandidatePolicy tcp_candidate_policy;
673 CandidateNetworkPolicy candidate_network_policy;
674 int audio_jitter_buffer_max_packets;
675 bool audio_jitter_buffer_fast_accelerate;
676 int ice_connection_receiving_timeout;
677 int ice_backup_candidate_pair_ping_interval;
678 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800679 bool prioritize_most_likely_ice_candidate_pairs;
680 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800681 bool prune_turn_ports;
682 bool presume_writable_when_fully_relayed;
683 bool enable_ice_renomination;
684 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200685 absl::optional<int> ice_check_interval_strong_connectivity;
686 absl::optional<int> ice_check_interval_weak_connectivity;
687 absl::optional<int> ice_check_min_interval;
688 absl::optional<int> ice_unwritable_timeout;
689 absl::optional<int> ice_unwritable_min_checks;
690 absl::optional<int> stun_candidate_keepalive_interval;
691 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200692 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800693 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200694 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700695 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800696 };
697 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
698 "Did you add something to RTCConfiguration and forget to "
699 "update operator==?");
700 return type == o.type && servers == o.servers &&
701 bundle_policy == o.bundle_policy &&
702 rtcp_mux_policy == o.rtcp_mux_policy &&
703 tcp_candidate_policy == o.tcp_candidate_policy &&
704 candidate_network_policy == o.candidate_network_policy &&
705 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
706 audio_jitter_buffer_fast_accelerate ==
707 o.audio_jitter_buffer_fast_accelerate &&
708 ice_connection_receiving_timeout ==
709 o.ice_connection_receiving_timeout &&
710 ice_backup_candidate_pair_ping_interval ==
711 o.ice_backup_candidate_pair_ping_interval &&
712 continual_gathering_policy == o.continual_gathering_policy &&
713 certificates == o.certificates &&
714 prioritize_most_likely_ice_candidate_pairs ==
715 o.prioritize_most_likely_ice_candidate_pairs &&
716 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800717 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700718 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100719 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800720 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800721 screencast_min_bitrate == o.screencast_min_bitrate &&
722 combined_audio_video_bwe == o.combined_audio_video_bwe &&
723 enable_dtls_srtp == o.enable_dtls_srtp &&
724 ice_candidate_pool_size == o.ice_candidate_pool_size &&
725 prune_turn_ports == o.prune_turn_ports &&
726 presume_writable_when_fully_relayed ==
727 o.presume_writable_when_fully_relayed &&
728 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800729 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800730 ice_check_interval_strong_connectivity ==
731 o.ice_check_interval_strong_connectivity &&
732 ice_check_interval_weak_connectivity ==
733 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700735 ice_unwritable_timeout == o.ice_unwritable_timeout &&
736 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800737 stun_candidate_keepalive_interval ==
738 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200739 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800740 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800741 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700742 network_preference == o.network_preference &&
743 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800744}
745
746bool PeerConnectionInterface::RTCConfiguration::operator!=(
747 const PeerConnectionInterface::RTCConfiguration& o) const {
748 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800749}
750
zhihuang8f65cdf2016-05-06 18:40:30 -0700751// Generate a RTCP CNAME when a PeerConnection is created.
752std::string GenerateRtcpCname() {
753 std::string cname;
754 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100755 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800756 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700757 }
758 return cname;
759}
760
zhihuang1c378ed2017-08-17 14:10:50 -0700761bool ValidateOfferAnswerOptions(
762 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
763 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
764 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700765}
766
zhihuang1c378ed2017-08-17 14:10:50 -0700767// From |rtc_options|, fill parts of |session_options| shared by all generated
768// m= sections (in other words, nothing that involves a map/array).
769void ExtractSharedMediaSessionOptions(
770 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
771 cricket::MediaSessionOptions* session_options) {
772 session_options->vad_enabled = rtc_options.voice_activity_detection;
773 session_options->bundle_enabled = rtc_options.use_rtp_mux;
774}
zhihuanga77e6bb2017-08-14 18:17:48 -0700775
zhihuang38ede132017-06-15 12:52:32 -0700776PeerConnection::PeerConnection(PeerConnectionFactory* factory,
777 std::unique_ptr<RtcEventLog> event_log,
778 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700780 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700781 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700782 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700783 remote_streams_(StreamCollection::Create()),
784 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785
786PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100787 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800788 RTC_DCHECK_RUN_ON(signaling_thread());
789
Steve Anton8af21862017-12-15 11:20:13 -0800790 // Need to stop transceivers before destroying the stats collector because
791 // AudioRtpSender has a reference to the StatsCollector it will update when
792 // stopping.
793 for (auto transceiver : transceivers_) {
794 transceiver->Stop();
795 }
Steve Anton4171afb2017-11-20 10:20:22 -0800796
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700797 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800798 if (stats_collector_) {
799 stats_collector_->WaitForPendingRequest();
800 stats_collector_ = nullptr;
801 }
Steve Anton75737c02017-11-06 10:37:17 -0800802
Steve Anton8af21862017-12-15 11:20:13 -0800803 // Don't destroy BaseChannels until after stats has been cleaned up so that
804 // the last stats request can still read from the channels.
805 DestroyAllChannels();
806
Mirko Bonadei675513b2017-11-09 11:09:25 +0100807 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800808
809 webrtc_session_desc_factory_.reset();
810 sctp_invoker_.reset();
811 sctp_factory_.reset();
812 transport_controller_.reset();
813
deadbeef91dd5672016-05-18 16:55:30 -0700814 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700815 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700816 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700817 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700818 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700819 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800820 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700821 event_log_.reset();
822 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823}
824
Steve Anton8af21862017-12-15 11:20:13 -0800825void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800826 // Destroy video channels first since they may have a pointer to a voice
827 // channel.
828 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800829 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800830 DestroyTransceiverChannel(transceiver);
831 }
832 }
833 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800834 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800835 DestroyTransceiverChannel(transceiver);
836 }
837 }
838 DestroyDataChannel();
839}
840
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000841bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000842 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700843 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100844 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700845
846 RTCError config_error = ValidateConfiguration(configuration);
847 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700849 return false;
850 }
851
Benjamin Wrightcab58882018-05-02 15:12:47 -0700852 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100853 RTC_LOG(LS_ERROR)
854 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100855 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800856 return false;
857 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200858
Benjamin Wrightcab58882018-05-02 15:12:47 -0700859 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800860 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100861 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100862 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800863 return false;
864 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700865
Benjamin Wrightcab58882018-05-02 15:12:47 -0700866 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700867 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700868 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700869 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800870
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200871 cricket::ServerAddresses stun_servers;
872 std::vector<cricket::RelayServerConfig> turn_servers;
873
874 RTCErrorType parse_error =
875 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
876 if (parse_error != RTCErrorType::NONE) {
877 return false;
878 }
879
deadbeef91dd5672016-05-18 16:55:30 -0700880 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700881 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700882 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200883 RTC_FROM_HERE,
884 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
885 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886 return false;
887 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200888 // If initialization was successful, note if STUN or TURN servers
889 // were supplied.
890 if (!stun_servers.empty()) {
891 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
892 }
893 if (!turn_servers.empty()) {
894 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
895 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000896
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700897 // Send information about IPv4/IPv6 status.
898 PeerConnectionAddressFamilyCounter address_family;
899 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
900 address_family = kPeerConnection_IPv6;
901 } else {
902 address_family = kPeerConnection_IPv4;
903 }
904 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
905 kPeerConnectionAddressFamilyCounter_Max);
906
Zhi Huange830e682018-03-30 10:48:35 -0700907 const PeerConnectionFactoryInterface::Options& options = factory_->options();
908
Steve Anton75737c02017-11-06 10:37:17 -0800909 // RFC 3264: The numeric value of the session id and version in the
910 // o line MUST be representable with a "64 bit signed integer".
911 // Due to this constraint session id |session_id_| is max limited to
912 // LLONG_MAX.
913 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700914 JsepTransportController::Config config;
915 config.redetermine_role_on_ice_restart =
916 configuration.redetermine_role_on_ice_restart;
917 config.ssl_max_version = factory_->options().ssl_max_version;
918 config.disable_encryption = options.disable_encryption;
919 config.bundle_policy = configuration.bundle_policy;
920 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
921 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700922 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700923 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700924#if defined(ENABLE_EXTERNAL_AUTH)
925 config.enable_external_auth = true;
926#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700927 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700928 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700929 signaling_thread(), network_thread(), port_allocator_.get(),
930 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700931 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800932 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700933 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800934 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700935 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800936 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700937 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800938 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
939 transport_controller_->SignalDtlsHandshakeError.connect(
940 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
941
942 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700943
deadbeefab9b2d12015-10-14 11:33:11 -0700944 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700945 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946
Steve Antonba818672017-11-06 10:21:57 -0800947 configuration_ = configuration;
948
Steve Anton75737c02017-11-06 10:37:17 -0800949 // Obtain a certificate from RTCConfiguration if any were provided (optional).
950 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
951 if (!configuration.certificates.empty()) {
952 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
953 // just picking the first one. The decision should be made based on the DTLS
954 // handshake. The DTLS negotiations need to know about all certificates.
955 certificate = configuration.certificates[0];
956 }
957
Steve Antond25da372017-11-06 14:50:29 -0800958 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800959
960 if (options.disable_encryption) {
961 dtls_enabled_ = false;
962 } else {
963 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700964 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800965 // |configuration| can override the default |dtls_enabled_| value.
966 if (configuration.enable_dtls_srtp) {
967 dtls_enabled_ = *(configuration.enable_dtls_srtp);
968 }
969 }
970
971 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
972 // It takes precendence over the disable_sctp_data_channels
973 // PeerConnectionFactoryInterface::Options.
974 if (configuration.enable_rtp_data_channel) {
975 data_channel_type_ = cricket::DCT_RTP;
976 } else {
977 // DTLS has to be enabled to use SCTP.
978 if (!options.disable_sctp_data_channels && dtls_enabled_) {
979 data_channel_type_ = cricket::DCT_SCTP;
980 }
981 }
982
983 video_options_.screencast_min_bitrate_kbps =
984 configuration.screencast_min_bitrate;
985 audio_options_.combined_audio_video_bwe =
986 configuration.combined_audio_video_bwe;
987
988 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100989 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800990
991 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100992 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800993
994 // Whether the certificate generator/certificate is null or not determines
995 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
996 // the right instructions by clearing the variables if needed.
997 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -0700998 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800999 certificate = nullptr;
1000 } else if (certificate) {
1001 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001002 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001003 }
1004
1005 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1006 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001007 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001008 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1009 this, &PeerConnection::OnCertificateReady);
1010
1011 if (options.disable_encryption) {
1012 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1013 }
1014
1015 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1016 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017
Steve Anton4171afb2017-11-20 10:20:22 -08001018 // Add default audio/video transceivers for Plan B SDP.
1019 if (!IsUnifiedPlan()) {
1020 transceivers_.push_back(
1021 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1022 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1023 transceivers_.push_back(
1024 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1025 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1026 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001027 int delay_ms =
1028 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1029 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1030 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 return true;
1032}
1033
Steve Anton038834f2017-07-14 15:59:59 -07001034RTCError PeerConnection::ValidateConfiguration(
1035 const RTCConfiguration& config) const {
1036 if (config.ice_regather_interval_range &&
1037 config.continual_gathering_policy == GATHER_ONCE) {
1038 return RTCError(RTCErrorType::INVALID_PARAMETER,
1039 "ice_regather_interval_range specified but continual "
1040 "gathering policy is GATHER_ONCE");
1041 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001042 auto result =
1043 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1044 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001045}
1046
Yves Gerey665174f2018-06-19 15:03:05 +02001047rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001048 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1049 "Plan SdpSemantics. Please use GetSenders "
1050 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001051 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052}
1053
Yves Gerey665174f2018-06-19 15:03:05 +02001054rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001055 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1056 "Plan SdpSemantics. Please use GetReceivers "
1057 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001058 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059}
1060
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001061bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001062 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1063 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001064 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 if (IsClosed()) {
1066 return false;
1067 }
deadbeefab9b2d12015-10-14 11:33:11 -07001068 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001069 return false;
1070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071
1072 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001073 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1074 observer->SignalAudioTrackAdded.connect(this,
1075 &PeerConnection::OnAudioTrackAdded);
1076 observer->SignalAudioTrackRemoved.connect(
1077 this, &PeerConnection::OnAudioTrackRemoved);
1078 observer->SignalVideoTrackAdded.connect(this,
1079 &PeerConnection::OnVideoTrackAdded);
1080 observer->SignalVideoTrackRemoved.connect(
1081 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001082 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001083
deadbeefab9b2d12015-10-14 11:33:11 -07001084 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001085 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
1087 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001088 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001089 }
1090
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001091 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001092 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 return true;
1094}
1095
1096void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001097 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1098 "Plan SdpSemantics. Please use RemoveTrack "
1099 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001100 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001101 if (!IsClosed()) {
1102 for (const auto& track : local_stream->GetAudioTracks()) {
1103 RemoveAudioTrack(track.get(), local_stream);
1104 }
1105 for (const auto& track : local_stream->GetVideoTracks()) {
1106 RemoveVideoTrack(track.get(), local_stream);
1107 }
deadbeefab9b2d12015-10-14 11:33:11 -07001108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001110 stream_observers_.erase(
1111 std::remove_if(
1112 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001113 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001114 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001115 }),
1116 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001117
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118 if (IsClosed()) {
1119 return;
1120 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001121 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122}
1123
Steve Anton2d6c76a2018-01-05 17:10:52 -08001124RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001125 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001126 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001127 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001128 if (!track) {
1129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1130 }
1131 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1132 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1133 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1134 "Track has invalid kind: " + track->kind());
1135 }
Steve Antonf9381f02017-12-14 10:23:57 -08001136 if (IsClosed()) {
1137 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1138 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001139 }
Steve Anton4171afb2017-11-20 10:20:22 -08001140 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001141 LOG_AND_RETURN_ERROR(
1142 RTCErrorType::INVALID_PARAMETER,
1143 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001144 }
Steve Antonf9381f02017-12-14 10:23:57 -08001145 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001146 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1147 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001148 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001149 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001150 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001151 }
1152 return sender_or_error;
1153}
deadbeefe1f9d832016-01-14 15:35:42 -08001154
Steve Antonf9381f02017-12-14 10:23:57 -08001155RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1156PeerConnection::AddTrackPlanB(
1157 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001158 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001159 if (stream_ids.size() > 1u) {
1160 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1161 "AddTrack with more than one stream is not "
1162 "supported with Plan B semantics.");
1163 }
1164 std::vector<std::string> adjusted_stream_ids = stream_ids;
1165 if (adjusted_stream_ids.empty()) {
1166 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1167 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001168 cricket::MediaType media_type =
1169 (track->kind() == MediaStreamTrackInterface::kAudioKind
1170 ? cricket::MEDIA_TYPE_AUDIO
1171 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001172 auto new_sender =
1173 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001174 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001175 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001176 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001177 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001178 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001179 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001180 if (sender_info) {
1181 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001182 }
Steve Antonf9381f02017-12-14 10:23:57 -08001183 } else {
1184 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001185 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001186 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001187 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001188 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001189 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001190 if (sender_info) {
1191 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001192 }
deadbeefe1f9d832016-01-14 15:35:42 -08001193 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001194 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001195}
deadbeefe1f9d832016-01-14 15:35:42 -08001196
Steve Antonf9381f02017-12-14 10:23:57 -08001197RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1198PeerConnection::AddTrackUnifiedPlan(
1199 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001200 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001201 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1202 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001203 RTC_LOG(LS_INFO) << "Reusing an existing "
1204 << cricket::MediaTypeToString(transceiver->media_type())
1205 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001206 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001207 transceiver->internal()->set_direction(
1208 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001209 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001210 transceiver->internal()->set_direction(
1211 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001212 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001213 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001214 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001215 } else {
1216 cricket::MediaType media_type =
1217 (track->kind() == MediaStreamTrackInterface::kAudioKind
1218 ? cricket::MEDIA_TYPE_AUDIO
1219 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001220 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1221 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001222 std::string sender_id = track->id();
1223 // Avoid creating a sender with an existing ID by generating a random ID.
1224 // This can happen if this is the second time AddTrack has created a sender
1225 // for this track.
1226 if (FindSenderById(sender_id)) {
1227 sender_id = rtc::CreateRandomUuid();
1228 }
1229 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001230 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1231 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001232 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001233 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001234 }
Steve Antonf9381f02017-12-14 10:23:57 -08001235 return transceiver->sender();
1236}
1237
1238rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1239PeerConnection::FindFirstTransceiverForAddedTrack(
1240 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1241 RTC_DCHECK(track);
1242 for (auto transceiver : transceivers_) {
1243 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001244 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001245 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001246 !transceiver->internal()->has_ever_been_used_to_send() &&
1247 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001248 return transceiver;
1249 }
1250 }
1251 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001252}
1253
1254bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1255 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001256 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001257}
1258
Steve Anton24db5732018-07-23 10:27:33 -07001259RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001260 rtc::scoped_refptr<RtpSenderInterface> sender) {
1261 if (!sender) {
1262 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1263 }
deadbeefe1f9d832016-01-14 15:35:42 -08001264 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001265 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1266 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001267 }
Steve Antonf9381f02017-12-14 10:23:57 -08001268 if (IsUnifiedPlan()) {
1269 auto transceiver = FindTransceiverBySender(sender);
1270 if (!transceiver || !sender->track()) {
1271 return RTCError::OK();
1272 }
1273 sender->SetTrack(nullptr);
1274 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001275 transceiver->internal()->set_direction(
1276 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001277 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001278 transceiver->internal()->set_direction(
1279 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001280 }
Steve Anton4171afb2017-11-20 10:20:22 -08001281 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001282 bool removed;
1283 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1284 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1285 } else {
1286 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1287 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1288 }
1289 if (!removed) {
1290 LOG_AND_RETURN_ERROR(
1291 RTCErrorType::INVALID_PARAMETER,
1292 "Couldn't find sender " + sender->id() + " to remove.");
1293 }
Steve Anton4171afb2017-11-20 10:20:22 -08001294 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001295 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001296 return RTCError::OK();
1297}
1298
1299rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1300PeerConnection::FindTransceiverBySender(
1301 rtc::scoped_refptr<RtpSenderInterface> sender) {
1302 for (auto transceiver : transceivers_) {
1303 if (transceiver->sender() == sender) {
1304 return transceiver;
1305 }
1306 }
1307 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001308}
1309
Steve Anton9158ef62017-11-27 13:01:52 -08001310RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1311PeerConnection::AddTransceiver(
1312 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1313 return AddTransceiver(track, RtpTransceiverInit());
1314}
1315
1316RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1317PeerConnection::AddTransceiver(
1318 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1319 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001320 RTC_CHECK(IsUnifiedPlan())
1321 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001322 if (!track) {
1323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1324 }
1325 cricket::MediaType media_type;
1326 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1327 media_type = cricket::MEDIA_TYPE_AUDIO;
1328 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1329 media_type = cricket::MEDIA_TYPE_VIDEO;
1330 } else {
1331 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1332 "Track kind is not audio or video");
1333 }
1334 return AddTransceiver(media_type, track, init);
1335}
1336
1337RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1338PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1339 return AddTransceiver(media_type, RtpTransceiverInit());
1340}
1341
1342RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1343PeerConnection::AddTransceiver(cricket::MediaType media_type,
1344 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001345 RTC_CHECK(IsUnifiedPlan())
1346 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001347 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1348 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1350 "media type is not audio or video");
1351 }
1352 return AddTransceiver(media_type, nullptr, init);
1353}
1354
1355RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1356PeerConnection::AddTransceiver(
1357 cricket::MediaType media_type,
1358 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001359 const RtpTransceiverInit& init,
1360 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001361 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1362 media_type == cricket::MEDIA_TYPE_VIDEO));
1363 if (track) {
1364 RTC_DCHECK_EQ(media_type,
1365 (track->kind() == MediaStreamTrackInterface::kAudioKind
1366 ? cricket::MEDIA_TYPE_AUDIO
1367 : cricket::MEDIA_TYPE_VIDEO));
1368 }
1369
1370 // TODO(bugs.webrtc.org/7600): Verify init.
1371
Steve Anton3d954a62018-04-02 11:27:23 -07001372 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1373 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001374 // Set the sender ID equal to the track ID if the track is specified unless
1375 // that sender ID is already in use.
1376 std::string sender_id =
1377 (track && !FindSenderById(track->id()) ? track->id()
1378 : rtc::CreateRandomUuid());
1379 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1381 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1382 transceiver->internal()->set_direction(init.direction);
1383
Steve Anton22da89f2018-01-25 13:58:07 -08001384 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001385 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001386 }
Steve Antonf9381f02017-12-14 10:23:57 -08001387
1388 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1389}
1390
Steve Anton02ee47c2018-01-10 16:26:06 -08001391rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1392PeerConnection::CreateSender(
1393 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001394 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001396 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001397 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1399 RTC_DCHECK(!track ||
1400 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1401 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1402 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001403 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001404 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001405 } else {
1406 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1407 RTC_DCHECK(!track ||
1408 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1409 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001410 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001411 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001413 bool set_track_succeeded = sender->SetTrack(track);
1414 RTC_DCHECK(set_track_succeeded);
1415 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 return sender;
1417}
1418
1419rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1420PeerConnection::CreateReceiver(cricket::MediaType media_type,
1421 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001422 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1423 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001424 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001425 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001426 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1427 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001428 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001429 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001430 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001431 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001432 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1433 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001434 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001435 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001436 return receiver;
1437}
1438
1439rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1440PeerConnection::CreateAndAddTransceiver(
1441 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001444 // Ensure that the new sender does not have an ID that is already in use by
1445 // another sender.
1446 // Allow receiver IDs to conflict since those come from remote SDP (which
1447 // could be invalid, but should not cause a crash).
1448 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001449 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1450 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001451 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001452 transceiver->internal()->SignalNegotiationNeeded.connect(
1453 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001454 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001455}
1456
Steve Anton52d86772018-02-20 15:48:12 -08001457void PeerConnection::OnNegotiationNeeded() {
1458 RTC_DCHECK_RUN_ON(signaling_thread());
1459 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001460 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001461}
1462
deadbeeffac06552015-11-25 11:26:01 -08001463rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001464 const std::string& kind,
1465 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001466 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1467 "Plan SdpSemantics. Please use AddTransceiver "
1468 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001469 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001470 if (IsClosed()) {
1471 return nullptr;
1472 }
Steve Anton4171afb2017-11-20 10:20:22 -08001473
Seth Hampson5b4f0752018-04-02 16:31:36 -07001474 // Internally we need to have one stream with Plan B semantics, so we
1475 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001476 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001477 if (stream_id.empty()) {
1478 stream_ids.push_back(rtc::CreateRandomUuid());
1479 RTC_LOG(LS_INFO)
1480 << "No stream_id specified for sender. Generated stream ID: "
1481 << stream_ids[0];
1482 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001483 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001484 }
1485
Steve Anton4171afb2017-11-20 10:20:22 -08001486 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001487 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001488 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001489 auto* audio_sender = new AudioRtpSender(
1490 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001491 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001492 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001493 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001494 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001495 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001496 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001497 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001498 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001499 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001501 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001502 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001503 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001504 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001505 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001506 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001507
deadbeefe1f9d832016-01-14 15:35:42 -08001508 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001509}
1510
deadbeef70ab1a12015-09-28 16:53:55 -07001511std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1512 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001513 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001514 for (auto sender : GetSendersInternal()) {
1515 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001516 }
1517 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001518}
1519
Steve Anton4171afb2017-11-20 10:20:22 -08001520std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1521PeerConnection::GetSendersInternal() const {
1522 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1523 all_senders;
1524 for (auto transceiver : transceivers_) {
1525 auto senders = transceiver->internal()->senders();
1526 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1527 }
1528 return all_senders;
1529}
1530
deadbeef70ab1a12015-09-28 16:53:55 -07001531std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1532PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001533 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001534 for (const auto& receiver : GetReceiversInternal()) {
1535 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001536 }
1537 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001538}
1539
Steve Anton4171afb2017-11-20 10:20:22 -08001540std::vector<
1541 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1542PeerConnection::GetReceiversInternal() const {
1543 std::vector<
1544 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1545 all_receivers;
1546 for (auto transceiver : transceivers_) {
1547 auto receivers = transceiver->internal()->receivers();
1548 all_receivers.insert(all_receivers.end(), receivers.begin(),
1549 receivers.end());
1550 }
1551 return all_receivers;
1552}
1553
Steve Anton9158ef62017-11-27 13:01:52 -08001554std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1555PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001556 RTC_CHECK(IsUnifiedPlan())
1557 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001558 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1559 for (auto transceiver : transceivers_) {
1560 all_transceivers.push_back(transceiver);
1561 }
1562 return all_transceivers;
1563}
1564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001566 MediaStreamTrackInterface* track,
1567 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001568 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001569 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001570 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001571 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572 return false;
1573 }
1574
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001575 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001576 // The StatsCollector is used to tell if a track is valid because it may
1577 // remember tracks that the PeerConnection previously removed.
1578 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001579 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1580 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001581 return false;
1582 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001583 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001584 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585 return true;
1586}
1587
hbos74e1a4f2016-09-15 23:33:01 -07001588void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001589 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001590 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001591 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001592 stats_collector_->GetStatsReport(callback);
1593}
1594
Henrik Boström1df1bf82018-03-20 13:24:20 +01001595void PeerConnection::GetStats(
1596 rtc::scoped_refptr<RtpSenderInterface> selector,
1597 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1598 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1599 RTC_DCHECK(callback);
1600 RTC_DCHECK(stats_collector_);
1601 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1602 if (selector) {
1603 for (const auto& proxy_transceiver : transceivers_) {
1604 for (const auto& proxy_sender :
1605 proxy_transceiver->internal()->senders()) {
1606 if (proxy_sender == selector) {
1607 internal_sender = proxy_sender->internal();
1608 break;
1609 }
1610 }
1611 if (internal_sender)
1612 break;
1613 }
1614 }
1615 // If there is no |internal_sender| then |selector| is either null or does not
1616 // belong to the PeerConnection (in Plan B, senders can be removed from the
1617 // PeerConnection). This means that "all the stats objects representing the
1618 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1619 // produces an empty stats report.
1620 stats_collector_->GetStatsReport(internal_sender, callback);
1621}
1622
1623void PeerConnection::GetStats(
1624 rtc::scoped_refptr<RtpReceiverInterface> selector,
1625 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1626 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1627 RTC_DCHECK(callback);
1628 RTC_DCHECK(stats_collector_);
1629 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1630 if (selector) {
1631 for (const auto& proxy_transceiver : transceivers_) {
1632 for (const auto& proxy_receiver :
1633 proxy_transceiver->internal()->receivers()) {
1634 if (proxy_receiver == selector) {
1635 internal_receiver = proxy_receiver->internal();
1636 break;
1637 }
1638 }
1639 if (internal_receiver)
1640 break;
1641 }
1642 }
1643 // If there is no |internal_receiver| then |selector| is either null or does
1644 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1645 // the PeerConnection). This means that "all the stats objects representing
1646 // the selector" is an empty set. Invoking GetStatsReport() with a null
1647 // selector produces an empty stats report.
1648 stats_collector_->GetStatsReport(internal_receiver, callback);
1649}
1650
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1652 return signaling_state_;
1653}
1654
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001655PeerConnectionInterface::IceConnectionState
1656PeerConnection::ice_connection_state() {
1657 return ice_connection_state_;
1658}
1659
1660PeerConnectionInterface::IceGatheringState
1661PeerConnection::ice_gathering_state() {
1662 return ice_gathering_state_;
1663}
1664
Yves Gerey665174f2018-06-19 15:03:05 +02001665rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666 const std::string& label,
1667 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001668 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001669
deadbeefab9b2d12015-10-14 11:33:11 -07001670 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001671
kwibergd1fe2812016-04-27 06:47:29 -07001672 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001673 if (config) {
1674 internal_config.reset(new InternalDataChannelInit(*config));
1675 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001676 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001677 InternalCreateDataChannel(label, internal_config.get()));
1678 if (!channel.get()) {
1679 return nullptr;
1680 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001682 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1683 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001684 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001685 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001686 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001687 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688 return DataChannelProxy::Create(signaling_thread(), channel.get());
1689}
1690
1691void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001692 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001693 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001694
nisse7ce109a2017-01-31 00:57:56 -08001695 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001696 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001697 return;
1698 }
deadbeefab9b2d12015-10-14 11:33:11 -07001699
Steve Anton8d3444d2017-10-20 15:30:51 -07001700 if (IsClosed()) {
1701 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001702 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001703 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001704 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001705 return;
1706 }
1707
zhihuang1c378ed2017-08-17 14:10:50 -07001708 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001709 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001710 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001711 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001712 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001713 return;
1714 }
1715
Steve Anton22da89f2018-01-25 13:58:07 -08001716 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1717 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1718 if (IsUnifiedPlan()) {
1719 RTCError error = HandleLegacyOfferOptions(options);
1720 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001721 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001722 return;
1723 }
1724 }
1725
zhihuang1c378ed2017-08-17 14:10:50 -07001726 cricket::MediaSessionOptions session_options;
1727 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001728 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729}
1730
Steve Anton22da89f2018-01-25 13:58:07 -08001731RTCError PeerConnection::HandleLegacyOfferOptions(
1732 const RTCOfferAnswerOptions& options) {
1733 RTC_DCHECK(IsUnifiedPlan());
1734
1735 if (options.offer_to_receive_audio == 0) {
1736 RemoveRecvDirectionFromReceivingTransceiversOfType(
1737 cricket::MEDIA_TYPE_AUDIO);
1738 } else if (options.offer_to_receive_audio == 1) {
1739 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1740 } else if (options.offer_to_receive_audio > 1) {
1741 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1742 "offer_to_receive_audio > 1 is not supported.");
1743 }
1744
1745 if (options.offer_to_receive_video == 0) {
1746 RemoveRecvDirectionFromReceivingTransceiversOfType(
1747 cricket::MEDIA_TYPE_VIDEO);
1748 } else if (options.offer_to_receive_video == 1) {
1749 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1750 } else if (options.offer_to_receive_video > 1) {
1751 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1752 "offer_to_receive_video > 1 is not supported.");
1753 }
1754
1755 return RTCError::OK();
1756}
1757
1758void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1759 cricket::MediaType media_type) {
1760 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001761 RtpTransceiverDirection new_direction =
1762 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1763 if (new_direction != transceiver->direction()) {
1764 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1765 << " transceiver (MID="
1766 << transceiver->mid().value_or("<not set>") << ") from "
1767 << RtpTransceiverDirectionToString(
1768 transceiver->direction())
1769 << " to "
1770 << RtpTransceiverDirectionToString(new_direction)
1771 << " since CreateOffer specified offer_to_receive=0";
1772 transceiver->internal()->set_direction(new_direction);
1773 }
Steve Anton22da89f2018-01-25 13:58:07 -08001774 }
1775}
1776
1777void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1778 cricket::MediaType media_type) {
1779 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001780 RTC_LOG(LS_INFO)
1781 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1782 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001783 RtpTransceiverInit init;
1784 init.direction = RtpTransceiverDirection::kRecvOnly;
1785 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1786 }
1787}
1788
1789std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1790PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1791 std::vector<
1792 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1793 receiving_transceivers;
1794 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001795 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001796 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1797 receiving_transceivers.push_back(transceiver);
1798 }
1799 }
1800 return receiving_transceivers;
1801}
1802
htaa2a49d92016-03-04 02:51:39 -08001803void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1804 const RTCOfferAnswerOptions& options) {
1805 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001806 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001807 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001808 return;
1809 }
1810
Steve Antondffead82018-02-06 10:31:29 -08001811 if (!(signaling_state_ == kHaveRemoteOffer ||
1812 signaling_state_ == kHaveLocalPrAnswer)) {
1813 std::string error =
1814 "PeerConnection cannot create an answer in a state other than "
1815 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001816 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001817 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001818 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001819 return;
1820 }
1821
Steve Antondffead82018-02-06 10:31:29 -08001822 // The remote description should be set if we're in the right state.
1823 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001824
Steve Anton22da89f2018-01-25 13:58:07 -08001825 if (IsUnifiedPlan()) {
1826 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1827 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1828 "supported with Unified Plan semantics. Use the "
1829 "RtpTransceiver API instead.";
1830 }
1831 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1832 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1833 "supported with Unified Plan semantics. Use the "
1834 "RtpTransceiver API instead.";
1835 }
1836 }
1837
htaa2a49d92016-03-04 02:51:39 -08001838 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001839 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001840
Steve Antond25da372017-11-06 14:50:29 -08001841 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842}
1843
1844void PeerConnection::SetLocalDescription(
1845 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001846 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001847 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001848
Steve Anton80dd7b52018-02-16 17:08:42 -08001849 // The SetLocalDescription contract is that we take ownership of the session
1850 // description regardless of the outcome, so wrap it in a unique_ptr right
1851 // away. Ideally, SetLocalDescription's signature will be changed to take the
1852 // description as a unique_ptr argument to formalize this agreement.
1853 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1854
nisse7ce109a2017-01-31 00:57:56 -08001855 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001856 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 return;
1858 }
Steve Anton8a006912017-12-04 15:25:56 -08001859
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001861 PostSetSessionDescriptionFailure(
1862 observer,
1863 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 return;
1865 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001866
Steve Anton80dd7b52018-02-16 17:08:42 -08001867 // If a session error has occurred the PeerConnection is in a possibly
1868 // inconsistent state so fail right away.
1869 if (session_error() != SessionError::kNone) {
1870 std::string error_message = GetSessionErrorMsg();
1871 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001872 PostSetSessionDescriptionFailure(
1873 observer,
1874 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001875 return;
1876 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001877
Steve Anton80dd7b52018-02-16 17:08:42 -08001878 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1879 if (!error.ok()) {
1880 std::string error_message = GetSetDescriptionErrorMessage(
1881 cricket::CS_LOCAL, desc->GetType(), error);
1882 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001883 PostSetSessionDescriptionFailure(
1884 observer,
1885 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001886 return;
1887 }
1888
1889 // Grab the description type before moving ownership to ApplyLocalDescription,
1890 // which may destroy it before returning.
1891 const SdpType type = desc->GetType();
1892
1893 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001894 // |desc| may be destroyed at this point.
1895
1896 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001897 // If ApplyLocalDescription fails, the PeerConnection could be in an
1898 // inconsistent state, so act conservatively here and set the session error
1899 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1900 SetSessionError(SessionError::kContent, error.message());
1901 std::string error_message =
1902 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1903 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001904 PostSetSessionDescriptionFailure(
1905 observer,
1906 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001907 return;
1908 }
Steve Anton8a006912017-12-04 15:25:56 -08001909 RTC_DCHECK(local_description());
1910
1911 PostSetSessionDescriptionSuccess(observer);
1912
Steve Anton8a006912017-12-04 15:25:56 -08001913 // MaybeStartGathering needs to be called after posting
1914 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1915 // before signaling that SetLocalDescription completed.
1916 transport_controller_->MaybeStartGathering();
1917
Steve Antona3a92c22017-12-07 10:27:41 -08001918 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001919 // TODO(deadbeef): We already had to hop to the network thread for
1920 // MaybeStartGathering...
1921 network_thread()->Invoke<void>(
1922 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1923 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001924 // Make UMA notes about what was agreed to.
1925 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001926 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001927 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001928}
1929
1930RTCError PeerConnection::ApplyLocalDescription(
1931 std::unique_ptr<SessionDescriptionInterface> desc) {
1932 RTC_DCHECK_RUN_ON(signaling_thread());
1933 RTC_DCHECK(desc);
1934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 // Update stats here so that we have the most recent stats for tracks and
1936 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001937 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001938
Steve Antondcc3c022017-12-22 16:02:54 -08001939 // Take a reference to the old local description since it's used below to
1940 // compare against the new local description. When setting the new local
1941 // description, grab ownership of the replaced session description in case it
1942 // is the same as |old_local_description|, to keep it alive for the duration
1943 // of the method.
1944 const SessionDescriptionInterface* old_local_description =
1945 local_description();
1946 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001947 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001948 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001949 replaced_local_description = pending_local_description_
1950 ? std::move(pending_local_description_)
1951 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001952 current_local_description_ = std::move(desc);
1953 pending_local_description_ = nullptr;
1954 current_remote_description_ = std::move(pending_remote_description_);
1955 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001956 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001957 pending_local_description_ = std::move(desc);
1958 }
1959 // The session description to apply now must be accessed by
1960 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001961 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001962
Zhi Huange830e682018-03-30 10:48:35 -07001963 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1964 if (!error.ok()) {
1965 return error;
1966 }
1967
Steve Antondcc3c022017-12-22 16:02:54 -08001968 if (IsUnifiedPlan()) {
1969 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001970 cricket::CS_LOCAL, *local_description(), old_local_description,
1971 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001972 if (!error.ok()) {
1973 return error;
1974 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001975 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1976 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001977 for (auto transceiver : transceivers_) {
1978 const ContentInfo* content =
1979 FindMediaSectionForTransceiver(transceiver, local_description());
1980 if (!content) {
1981 continue;
1982 }
1983 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001984 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1985 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001986 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001987 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1988 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
1989 // "recvonly", process the removal of a remote track for the media
1990 // description, given transceiver, removeList, and muteTracks.
1991 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
1992 (transceiver->internal()->fired_direction() &&
1993 RtpTransceiverDirectionHasRecv(
1994 *transceiver->internal()->fired_direction()))) {
1995 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
1996 &removed_streams);
1997 }
1998 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
1999 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002000 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002001 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002002 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002003 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002004 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002005 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002006 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002007 }
2008 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002009 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002010 }
2011 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002012 // Media channels will be created only when offer is set. These may use new
2013 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002014 if (type == SdpType::kOffer) {
2015 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2016 // description is applied. Restore back to old description.
2017 RTCError error = CreateChannels(*local_description()->description());
2018 if (!error.ok()) {
2019 return error;
2020 }
2021 }
Steve Antondcc3c022017-12-22 16:02:54 -08002022 // Remove unused channels if MediaContentDescription is rejected.
2023 RemoveUnusedChannels(local_description()->description());
2024 }
Steve Anton8a006912017-12-04 15:25:56 -08002025
Zhi Huange830e682018-03-30 10:48:35 -07002026 error = UpdateSessionState(type, cricket::CS_LOCAL,
2027 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002028 if (!error.ok()) {
2029 return error;
2030 }
Steve Antondcc3c022017-12-22 16:02:54 -08002031
Steve Anton8a006912017-12-04 15:25:56 -08002032 if (remote_description()) {
2033 // Now that we have a local description, we can push down remote candidates.
2034 UseCandidatesInSessionDescription(remote_description());
2035 }
2036
2037 pending_ice_restarts_.clear();
2038 if (session_error() != SessionError::kNone) {
2039 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2040 }
2041
deadbeefab9b2d12015-10-14 11:33:11 -07002042 // If setting the description decided our SSL role, allocate any necessary
2043 // SCTP sids.
2044 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002045 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002046 AllocateSctpSids(role);
2047 }
2048
Steve Antond3679212018-01-17 17:41:02 -08002049 if (IsUnifiedPlan()) {
2050 for (auto transceiver : transceivers_) {
2051 const ContentInfo* content =
2052 FindMediaSectionForTransceiver(transceiver, local_description());
2053 if (!content) {
2054 continue;
2055 }
Steve Anton74255ff2018-01-24 18:32:57 -08002056 const auto& streams = content->media_description()->streams();
2057 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002058 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002059 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002060 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002061 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002062 } else {
2063 // 0 is a special value meaning "this sender has no associated send
2064 // stream". Need to call this so the sender won't attempt to configure
2065 // a no longer existing stream and run into DCHECKs in the lower
2066 // layers.
2067 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002068 }
2069 }
2070 } else {
2071 // Plan B semantics.
2072
Steve Antondcc3c022017-12-22 16:02:54 -08002073 // Update state and SSRC of local MediaStreams and DataChannels based on the
2074 // local session description.
2075 const cricket::ContentInfo* audio_content =
2076 GetFirstAudioContent(local_description()->description());
2077 if (audio_content) {
2078 if (audio_content->rejected) {
2079 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2080 } else {
2081 const cricket::AudioContentDescription* audio_desc =
2082 audio_content->media_description()->as_audio();
2083 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2084 }
deadbeeffaac4972015-11-12 15:33:07 -08002085 }
deadbeefab9b2d12015-10-14 11:33:11 -07002086
Steve Antondcc3c022017-12-22 16:02:54 -08002087 const cricket::ContentInfo* video_content =
2088 GetFirstVideoContent(local_description()->description());
2089 if (video_content) {
2090 if (video_content->rejected) {
2091 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2092 } else {
2093 const cricket::VideoContentDescription* video_desc =
2094 video_content->media_description()->as_video();
2095 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2096 }
deadbeeffaac4972015-11-12 15:33:07 -08002097 }
deadbeefab9b2d12015-10-14 11:33:11 -07002098 }
2099
2100 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002101 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002102 if (data_content) {
2103 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002104 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002105 if (rtc::starts_with(data_desc->protocol().data(),
2106 cricket::kMediaProtocolRtpPrefix)) {
2107 UpdateLocalRtpDataChannels(data_desc->streams());
2108 }
2109 }
2110
Steve Anton8a006912017-12-04 15:25:56 -08002111 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112}
2113
2114void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002115 SetSessionDescriptionObserver* observer,
2116 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002117 SetRemoteDescription(
2118 std::unique_ptr<SessionDescriptionInterface>(desc),
2119 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2120 new SetRemoteDescriptionObserverAdapter(this, observer)));
2121}
2122
2123void PeerConnection::SetRemoteDescription(
2124 std::unique_ptr<SessionDescriptionInterface> desc,
2125 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002126 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002127
nisse7ce109a2017-01-31 00:57:56 -08002128 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002129 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 return;
2131 }
Steve Anton8a006912017-12-04 15:25:56 -08002132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002134 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002135 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 return;
2137 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002138
Steve Anton80dd7b52018-02-16 17:08:42 -08002139 // If a session error has occurred the PeerConnection is in a possibly
2140 // inconsistent state so fail right away.
2141 if (session_error() != SessionError::kNone) {
2142 std::string error_message = GetSessionErrorMsg();
2143 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2144 observer->OnSetRemoteDescriptionComplete(
2145 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2146 return;
2147 }
Steve Anton71439a62018-02-15 11:53:06 -08002148
Steve Antonba42e992018-04-09 14:10:01 -07002149 if (desc->GetType() == SdpType::kOffer) {
2150 // Report to UMA the format of the received offer.
2151 ReportSdpFormatReceived(*desc);
2152 }
2153
Steve Anton80dd7b52018-02-16 17:08:42 -08002154 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002155 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002156 std::string error_message = GetSetDescriptionErrorMessage(
2157 cricket::CS_REMOTE, desc->GetType(), error);
2158 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002159 observer->OnSetRemoteDescriptionComplete(
2160 RTCError(error.type(), std::move(error_message)));
2161 return;
2162 }
Steve Anton71439a62018-02-15 11:53:06 -08002163
Steve Anton80dd7b52018-02-16 17:08:42 -08002164 // Grab the description type before moving ownership to
2165 // ApplyRemoteDescription, which may destroy it before returning.
2166 const SdpType type = desc->GetType();
2167
2168 error = ApplyRemoteDescription(std::move(desc));
2169 // |desc| may be destroyed at this point.
2170
2171 if (!error.ok()) {
2172 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2173 // inconsistent state, so act conservatively here and set the session error
2174 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2175 SetSessionError(SessionError::kContent, error.message());
2176 std::string error_message =
2177 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2178 RTC_LOG(LS_ERROR) << error_message;
2179 observer->OnSetRemoteDescriptionComplete(
2180 RTCError(error.type(), std::move(error_message)));
2181 return;
2182 }
2183 RTC_DCHECK(remote_description());
2184
2185 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002186 // TODO(deadbeef): We already had to hop to the network thread for
2187 // MaybeStartGathering...
2188 network_thread()->Invoke<void>(
2189 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2190 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002191 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002192 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002193 }
2194
2195 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002196 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002197}
2198
2199RTCError PeerConnection::ApplyRemoteDescription(
2200 std::unique_ptr<SessionDescriptionInterface> desc) {
2201 RTC_DCHECK_RUN_ON(signaling_thread());
2202 RTC_DCHECK(desc);
2203
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002204 // Update stats here so that we have the most recent stats for tracks and
2205 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002206 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002207
Steve Antondcc3c022017-12-22 16:02:54 -08002208 // Take a reference to the old remote description since it's used below to
2209 // compare against the new remote description. When setting the new remote
2210 // description, grab ownership of the replaced session description in case it
2211 // is the same as |old_remote_description|, to keep it alive for the duration
2212 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002213 const SessionDescriptionInterface* old_remote_description =
2214 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002215 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002216 SdpType type = desc->GetType();
2217 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002218 replaced_remote_description = pending_remote_description_
2219 ? std::move(pending_remote_description_)
2220 : std::move(current_remote_description_);
2221 current_remote_description_ = std::move(desc);
2222 pending_remote_description_ = nullptr;
2223 current_local_description_ = std::move(pending_local_description_);
2224 } else {
2225 replaced_remote_description = std::move(pending_remote_description_);
2226 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 }
Steve Anton8a006912017-12-04 15:25:56 -08002228 // The session description to apply now must be accessed by
2229 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002230 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231
Zhi Huange830e682018-03-30 10:48:35 -07002232 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2233 if (!error.ok()) {
2234 return error;
2235 }
Steve Anton8a006912017-12-04 15:25:56 -08002236 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002237 if (IsUnifiedPlan()) {
2238 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002239 cricket::CS_REMOTE, *remote_description(), local_description(),
2240 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002241 if (!error.ok()) {
2242 return error;
2243 }
Steve Antondcc3c022017-12-22 16:02:54 -08002244 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002245 // Media channels will be created only when offer is set. These may use new
2246 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002247 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002248 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002249 // description is applied. Restore back to old description.
2250 RTCError error = CreateChannels(*remote_description()->description());
2251 if (!error.ok()) {
2252 return error;
2253 }
2254 }
Steve Antondcc3c022017-12-22 16:02:54 -08002255 // Remove unused channels if MediaContentDescription is rejected.
2256 RemoveUnusedChannels(remote_description()->description());
2257 }
Steve Anton8a006912017-12-04 15:25:56 -08002258
Zhi Huange830e682018-03-30 10:48:35 -07002259 // NOTE: Candidates allocation will be initiated only when
2260 // SetLocalDescription is called.
2261 error = UpdateSessionState(type, cricket::CS_REMOTE,
2262 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002263 if (!error.ok()) {
2264 return error;
2265 }
2266
2267 if (local_description() &&
2268 !UseCandidatesInSessionDescription(remote_description())) {
2269 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2270 }
2271
2272 if (old_remote_description) {
2273 for (const cricket::ContentInfo& content :
2274 old_remote_description->description()->contents()) {
2275 // Check if this new SessionDescription contains new ICE ufrag and
2276 // password that indicates the remote peer requests an ICE restart.
2277 // TODO(deadbeef): When we start storing both the current and pending
2278 // remote description, this should reset pending_ice_restarts and compare
2279 // against the current description.
2280 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2281 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002282 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002283 pending_ice_restarts_.insert(content.name);
2284 }
2285 } else {
2286 // We retain all received candidates only if ICE is not restarted.
2287 // When ICE is restarted, all previous candidates belong to an old
2288 // generation and should not be kept.
2289 // TODO(deadbeef): This goes against the W3C spec which says the remote
2290 // description should only contain candidates from the last set remote
2291 // description plus any candidates added since then. We should remove
2292 // this once we're sure it won't break anything.
2293 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2294 old_remote_description, content.name, mutable_remote_description());
2295 }
2296 }
2297 }
2298
2299 if (session_error() != SessionError::kNone) {
2300 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2301 }
2302
2303 // Set the the ICE connection state to connecting since the connection may
2304 // become writable with peer reflexive candidates before any remote candidate
2305 // is signaled.
2306 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2307 // is to have a new signal the indicates a change in checking state from the
2308 // transport and expose a new checking() member from transport that can be
2309 // read to determine the current checking state. The existing SignalConnecting
2310 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002311 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002312 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002313 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2314 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2315 }
2316
deadbeefab9b2d12015-10-14 11:33:11 -07002317 // If setting the description decided our SSL role, allocate any necessary
2318 // SCTP sids.
2319 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002320 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002321 AllocateSctpSids(role);
2322 }
2323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002325 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002326 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002327 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002328 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002329 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002330 for (auto transceiver : transceivers_) {
2331 const ContentInfo* content =
2332 FindMediaSectionForTransceiver(transceiver, remote_description());
2333 if (!content) {
2334 continue;
2335 }
2336 const MediaContentDescription* media_desc = content->media_description();
2337 RtpTransceiverDirection local_direction =
2338 RtpTransceiverDirectionReversed(media_desc->direction());
2339 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2340 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2341 // transceiver's current direction is neither sendrecv nor recvonly,
2342 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002343 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002344 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002345 // The remote description has signaled the stream IDs.
2346 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002347 }
Steve Antondcc3c022017-12-22 16:02:54 -08002348 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002349 (!transceiver->fired_direction() ||
2350 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002351 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002352 << content->name << " (added to "
2353 << GetStreamIdsString(stream_ids) << ").";
2354
2355 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2356 for (const std::string& stream_id : stream_ids) {
2357 rtc::scoped_refptr<MediaStreamInterface> stream =
2358 remote_streams_->find(stream_id);
2359 if (!stream) {
2360 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2361 MediaStream::Create(stream_id));
2362 remote_streams_->AddStream(stream);
2363 added_streams.push_back(stream);
2364 }
2365 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002366 }
Steve Anton3172c032018-05-03 15:30:18 -07002367 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002368 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2369 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002370 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002371 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002372 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002373 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2374 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2375 // removal of a remote track for the media description, given transceiver,
2376 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002377 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002378 (transceiver->fired_direction() &&
2379 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2380 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2381 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002382 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002383 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2384 transceiver->internal()->set_fired_direction(local_direction);
2385 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2386 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002387 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002388 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2389 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002390 transceiver->internal()->set_current_direction(local_direction);
2391 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002392 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2393 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002394 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002395 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2396 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002397 transceiver->Stop();
2398 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002399 if (!content->rejected &&
2400 RtpTransceiverDirectionHasRecv(local_direction)) {
2401 // Set ssrc to 0 in the case of an unsignalled ssrc.
2402 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002403 if (!media_desc->streams().empty() &&
2404 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002405 ssrc = media_desc->streams()[0].first_ssrc();
2406 }
2407 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002408 }
Steve Antondcc3c022017-12-22 16:02:54 -08002409 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002410 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002411 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002412 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002413 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002414 observer->OnTrack(transceiver);
2415 observer->OnAddTrack(transceiver->receiver(),
2416 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002417 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002418 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002419 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002420 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002421 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002422 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002423 }
2424 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002425 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002426 }
Steve Antondcc3c022017-12-22 16:02:54 -08002427 }
2428
Henrik Boströmfdb92012017-11-09 19:55:44 +01002429 const cricket::ContentInfo* audio_content =
2430 GetFirstAudioContent(remote_description()->description());
2431 const cricket::ContentInfo* video_content =
2432 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002433 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002434 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002435 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002436 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002437 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002438 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002439
2440 // Check if the descriptions include streams, just in case the peer supports
2441 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002442 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002443 (audio_desc && !audio_desc->streams().empty()) ||
2444 (video_desc && !video_desc->streams().empty())) {
2445 remote_peer_supports_msid_ = true;
2446 }
deadbeefab9b2d12015-10-14 11:33:11 -07002447
2448 // We wait to signal new streams until we finish processing the description,
2449 // since only at that point will new streams have all their tracks.
2450 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2451
Steve Antondcc3c022017-12-22 16:02:54 -08002452 if (!IsUnifiedPlan()) {
2453 // TODO(steveanton): When removing RTP senders/receivers in response to a
2454 // rejected media section, there is some cleanup logic that expects the
2455 // voice/ video channel to still be set. But in this method the voice/video
2456 // channel would have been destroyed by the SetRemoteDescription caller
2457 // above so the cleanup that relies on them fails to run. The RemoveSenders
2458 // calls should be moved to right before the DestroyChannel calls to fix
2459 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002460
Steve Antondcc3c022017-12-22 16:02:54 -08002461 // Find all audio rtp streams and create corresponding remote AudioTracks
2462 // and MediaStreams.
2463 if (audio_content) {
2464 if (audio_content->rejected) {
2465 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2466 } else {
2467 bool default_audio_track_needed =
2468 !remote_peer_supports_msid_ &&
2469 RtpTransceiverDirectionHasSend(audio_desc->direction());
2470 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2471 default_audio_track_needed, audio_desc->type(),
2472 new_streams);
2473 }
deadbeeffaac4972015-11-12 15:33:07 -08002474 }
deadbeefab9b2d12015-10-14 11:33:11 -07002475
Steve Antondcc3c022017-12-22 16:02:54 -08002476 // Find all video rtp streams and create corresponding remote VideoTracks
2477 // and MediaStreams.
2478 if (video_content) {
2479 if (video_content->rejected) {
2480 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2481 } else {
2482 bool default_video_track_needed =
2483 !remote_peer_supports_msid_ &&
2484 RtpTransceiverDirectionHasSend(video_desc->direction());
2485 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2486 default_video_track_needed, video_desc->type(),
2487 new_streams);
2488 }
deadbeeffaac4972015-11-12 15:33:07 -08002489 }
deadbeefab9b2d12015-10-14 11:33:11 -07002490
Steve Antondcc3c022017-12-22 16:02:54 -08002491 // Update the DataChannels with the information from the remote peer.
2492 if (data_desc) {
2493 if (rtc::starts_with(data_desc->protocol().data(),
2494 cricket::kMediaProtocolRtpPrefix)) {
2495 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497 }
deadbeefab9b2d12015-10-14 11:33:11 -07002498
Steve Antondcc3c022017-12-22 16:02:54 -08002499 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002500 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002501 for (size_t i = 0; i < new_streams->count(); ++i) {
2502 MediaStreamInterface* new_stream = new_streams->at(i);
2503 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002504 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002505 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2506 }
deadbeefab9b2d12015-10-14 11:33:11 -07002507
Steve Antondcc3c022017-12-22 16:02:54 -08002508 UpdateEndedRemoteMediaStreams();
2509 }
deadbeefab9b2d12015-10-14 11:33:11 -07002510
Steve Anton8a006912017-12-04 15:25:56 -08002511 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002512}
2513
Steve Anton0f5400a2018-07-17 14:25:36 -07002514void PeerConnection::ProcessRemovalOfRemoteTrack(
2515 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2516 transceiver,
2517 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2518 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2519 RTC_DCHECK(transceiver->mid());
2520 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2521 << *transceiver->mid();
2522 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2523 transceiver->internal()->receiver_internal()->streams();
2524 // This will remove the remote track from the streams.
2525 transceiver->internal()->receiver_internal()->set_stream_ids({});
2526 remove_list->push_back(transceiver);
2527 // Remove any streams that no longer have tracks.
2528 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2529 // of streams, see if the stream was removed by checking if this was the
2530 // last receiver with that stream ID.
2531 for (auto stream : media_streams) {
2532 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2533 remote_streams_->RemoveStream(stream);
2534 removed_streams->push_back(stream);
2535 }
2536 }
2537}
2538
Steve Antondcc3c022017-12-22 16:02:54 -08002539RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2540 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002541 const SessionDescriptionInterface& new_session,
2542 const SessionDescriptionInterface* old_local_description,
2543 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002544 RTC_DCHECK(IsUnifiedPlan());
2545
Steve Anton7464fca2018-01-19 11:10:37 -08002546 const cricket::ContentGroup* bundle_group = nullptr;
2547 if (new_session.GetType() == SdpType::kOffer) {
2548 auto bundle_group_or_error =
2549 GetEarlyBundleGroup(*new_session.description());
2550 if (!bundle_group_or_error.ok()) {
2551 return bundle_group_or_error.MoveError();
2552 }
2553 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002554 }
Steve Antondcc3c022017-12-22 16:02:54 -08002555
Steve Antondcc3c022017-12-22 16:02:54 -08002556 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002557 for (size_t i = 0; i < new_contents.size(); ++i) {
2558 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002559 cricket::MediaType media_type = new_content.media_description()->type();
2560 seen_mids_.insert(new_content.name);
2561 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2562 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002563 const cricket::ContentInfo* old_local_content = nullptr;
2564 if (old_local_description &&
2565 i < old_local_description->description()->contents().size()) {
2566 old_local_content =
2567 &old_local_description->description()->contents()[i];
2568 }
2569 const cricket::ContentInfo* old_remote_content = nullptr;
2570 if (old_remote_description &&
2571 i < old_remote_description->description()->contents().size()) {
2572 old_remote_content =
2573 &old_remote_description->description()->contents()[i];
2574 }
Steve Antondcc3c022017-12-22 16:02:54 -08002575 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002576 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2577 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002578 if (!transceiver_or_error.ok()) {
2579 return transceiver_or_error.MoveError();
2580 }
2581 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002582 RTCError error =
2583 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2584 if (!error.ok()) {
2585 return error;
2586 }
2587 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002588 if (GetDataMid() && new_content.name != *GetDataMid()) {
2589 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002590 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2591 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002592 continue;
2593 }
2594 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2595 if (!error.ok()) {
2596 return error;
2597 }
Steve Antondcc3c022017-12-22 16:02:54 -08002598 } else {
2599 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2600 "Unknown section type.");
2601 }
2602 }
2603
2604 return RTCError::OK();
2605}
2606
2607RTCError PeerConnection::UpdateTransceiverChannel(
2608 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2609 transceiver,
2610 const cricket::ContentInfo& content,
2611 const cricket::ContentGroup* bundle_group) {
2612 RTC_DCHECK(IsUnifiedPlan());
2613 RTC_DCHECK(transceiver);
2614 cricket::BaseChannel* channel = transceiver->internal()->channel();
2615 if (content.rejected) {
2616 if (channel) {
2617 transceiver->internal()->SetChannel(nullptr);
2618 DestroyBaseChannel(channel);
2619 }
2620 } else {
2621 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002622 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002623 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002624 } else {
Steve Anton69470252018-02-09 11:43:08 -08002625 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002626 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002627 }
2628 if (!channel) {
2629 LOG_AND_RETURN_ERROR(
2630 RTCErrorType::INTERNAL_ERROR,
2631 "Failed to create channel for mid=" + content.name);
2632 }
2633 transceiver->internal()->SetChannel(channel);
2634 }
2635 }
2636 return RTCError::OK();
2637}
2638
Steve Antonfa2260d2017-12-28 16:38:23 -08002639RTCError PeerConnection::UpdateDataChannel(
2640 cricket::ContentSource source,
2641 const cricket::ContentInfo& content,
2642 const cricket::ContentGroup* bundle_group) {
2643 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002644 // If data channels are disabled, ignore this media section. CreateAnswer
2645 // will take care of rejecting it.
2646 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002647 }
2648 if (content.rejected) {
2649 DestroyDataChannel();
2650 } else {
2651 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002652 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002653 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2654 "Failed to create data channel.");
2655 }
2656 }
2657 if (source == cricket::CS_REMOTE) {
2658 const MediaContentDescription* data_desc = content.media_description();
2659 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2660 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2661 }
2662 }
2663 }
2664 return RTCError::OK();
2665}
2666
Steve Antondcc3c022017-12-22 16:02:54 -08002667RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2668PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002669 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002670 size_t mline_index,
2671 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002672 const ContentInfo* old_local_content,
2673 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002674 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002675 // If this is an offer then the m= section might be recycled. If the m=
2676 // section is being recycled (defined as: rejected in the current local or
2677 // remote description and not rejected in new description), dissociate the
2678 // currently associated RtpTransceiver by setting its mid property to null,
2679 // and discard the mapping between the transceiver and its m= section index.
2680 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2681 old_remote_content)) {
2682 // We want to dissociate the transceiver that has the rejected mid.
2683 const std::string& old_mid =
2684 (old_local_content && old_local_content->rejected)
2685 ? old_local_content->name
2686 : old_remote_content->name;
2687 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002688 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002689 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2690 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002691 old_transceiver->internal()->set_mid(absl::nullopt);
2692 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002693 }
2694 }
2695 const MediaContentDescription* media_desc = content.media_description();
2696 auto transceiver = GetAssociatedTransceiver(content.name);
2697 if (source == cricket::CS_LOCAL) {
2698 // Find the RtpTransceiver that corresponds to this m= section, using the
2699 // mapping between transceivers and m= section indices established when
2700 // creating the offer.
2701 if (!transceiver) {
2702 transceiver = GetTransceiverByMLineIndex(mline_index);
2703 }
2704 if (!transceiver) {
2705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2706 "Unknown transceiver");
2707 }
2708 } else {
2709 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2710 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2711 // of the same type...
2712 if (!transceiver &&
2713 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2714 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2715 }
2716 // If no RtpTransceiver was found in the previous step, create one with a
2717 // recvonly direction.
2718 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002719 RTC_LOG(LS_INFO) << "Adding "
2720 << cricket::MediaTypeToString(media_desc->type())
2721 << " transceiver for MID=" << content.name
2722 << " at i=" << mline_index
2723 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002724 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002725 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002726 std::string receiver_id;
2727 if (!media_desc->streams().empty()) {
2728 receiver_id = media_desc->streams()[0].id;
2729 } else {
2730 receiver_id = rtc::CreateRandomUuid();
2731 }
2732 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002733 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002734 transceiver->internal()->set_direction(
2735 RtpTransceiverDirection::kRecvOnly);
2736 }
2737 }
2738 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002739 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002740 LOG_AND_RETURN_ERROR(
2741 RTCErrorType::INVALID_PARAMETER,
2742 "Transceiver type does not match media description type.");
2743 }
2744 // Associate the found or created RtpTransceiver with the m= section by
2745 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2746 // section, and establish a mapping between the transceiver and the index of
2747 // the m= section.
2748 transceiver->internal()->set_mid(content.name);
2749 transceiver->internal()->set_mline_index(mline_index);
2750 return std::move(transceiver);
2751}
2752
2753rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2754PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2755 RTC_DCHECK(IsUnifiedPlan());
2756 for (auto transceiver : transceivers_) {
2757 if (transceiver->mid() == mid) {
2758 return transceiver;
2759 }
2760 }
2761 return nullptr;
2762}
2763
2764rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2765PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2766 RTC_DCHECK(IsUnifiedPlan());
2767 for (auto transceiver : transceivers_) {
2768 if (transceiver->internal()->mline_index() == mline_index) {
2769 return transceiver;
2770 }
2771 }
2772 return nullptr;
2773}
2774
2775rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2776PeerConnection::FindAvailableTransceiverToReceive(
2777 cricket::MediaType media_type) const {
2778 RTC_DCHECK(IsUnifiedPlan());
2779 // From JSEP section 5.10 (Applying a Remote Description):
2780 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2781 // the same type that were added to the PeerConnection by addTrack and are not
2782 // associated with any m= section and are not stopped, find the first such
2783 // RtpTransceiver.
2784 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002785 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002786 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2787 !transceiver->stopped()) {
2788 return transceiver;
2789 }
2790 }
2791 return nullptr;
2792}
2793
Steve Antoned10bd92017-12-05 10:52:59 -08002794const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2795 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2796 transceiver,
2797 const SessionDescriptionInterface* sdesc) const {
2798 RTC_DCHECK(transceiver);
2799 RTC_DCHECK(sdesc);
2800 if (IsUnifiedPlan()) {
2801 if (!transceiver->internal()->mid()) {
2802 // This transceiver is not associated with a media section yet.
2803 return nullptr;
2804 }
2805 return sdesc->description()->GetContentByName(
2806 *transceiver->internal()->mid());
2807 } else {
2808 // Plan B only allows at most one audio and one video section, so use the
2809 // first media section of that type.
2810 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002811 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002812 }
2813}
2814
deadbeef46c73892016-11-16 19:42:04 -08002815PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2816 return configuration_;
2817}
2818
deadbeef293e9262017-01-11 12:28:30 -08002819bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2820 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002821 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002822 if (IsClosed()) {
2823 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2824 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2825 }
2826
Qingsi Wanga2d60672018-04-11 16:57:45 -07002827 // According to JSEP, after setLocalDescription, changing the candidate pool
2828 // size is not allowed, and changing the set of ICE servers will not result
2829 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002830 if (local_description() && configuration.ice_candidate_pool_size !=
2831 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002832 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2833 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002834 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002835 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002836
deadbeef293e9262017-01-11 12:28:30 -08002837 // The simplest (and most future-compatible) way to tell if the config was
2838 // modified in an invalid way is to copy each property we do support
2839 // modifying, then use operator==. There are far more properties we don't
2840 // support modifying than those we do, and more could be added.
2841 RTCConfiguration modified_config = configuration_;
2842 modified_config.servers = configuration.servers;
2843 modified_config.type = configuration.type;
2844 modified_config.ice_candidate_pool_size =
2845 configuration.ice_candidate_pool_size;
2846 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002847 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002848 modified_config.ice_check_interval_strong_connectivity =
2849 configuration.ice_check_interval_strong_connectivity;
2850 modified_config.ice_check_interval_weak_connectivity =
2851 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002852 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2853 modified_config.ice_unwritable_min_checks =
2854 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002855 modified_config.stun_candidate_keepalive_interval =
2856 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002857 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002858 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002859 modified_config.active_reset_srtp_params =
2860 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002861 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002862 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002863 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2864 }
2865
Steve Anton038834f2017-07-14 15:59:59 -07002866 // Validate the modified configuration.
2867 RTCError validate_error = ValidateConfiguration(modified_config);
2868 if (!validate_error.ok()) {
2869 return SafeSetError(std::move(validate_error), error);
2870 }
2871
deadbeef293e9262017-01-11 12:28:30 -08002872 // Note that this isn't possible through chromium, since it's an unsigned
2873 // short in WebIDL.
2874 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002875 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002876 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2877 }
2878
2879 // Parse ICE servers before hopping to network thread.
2880 cricket::ServerAddresses stun_servers;
2881 std::vector<cricket::RelayServerConfig> turn_servers;
2882 RTCErrorType parse_error =
2883 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2884 if (parse_error != RTCErrorType::NONE) {
2885 return SafeSetError(parse_error, error);
2886 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002887 // Note if STUN or TURN servers were supplied.
2888 if (!stun_servers.empty()) {
2889 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2890 }
2891 if (!turn_servers.empty()) {
2892 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2893 }
deadbeef293e9262017-01-11 12:28:30 -08002894
2895 // In theory this shouldn't fail.
2896 if (!network_thread()->Invoke<bool>(
2897 RTC_FROM_HERE,
2898 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2899 stun_servers, turn_servers, modified_config.type,
2900 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002901 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002902 modified_config.turn_customizer,
2903 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002904 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002905 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2906 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002907
deadbeefd1a38b52016-12-10 13:15:33 -08002908 // As described in JSEP, calling setConfiguration with new ICE servers or
2909 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2910 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002911 if (modified_config.servers != configuration_.servers ||
2912 modified_config.type != configuration_.type ||
2913 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002914 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002915 }
skvladd1f5fda2017-02-03 16:54:05 -08002916
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002917 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002918
Zhi Huangb57e1692018-06-12 11:41:11 -07002919 if (configuration_.active_reset_srtp_params !=
2920 modified_config.active_reset_srtp_params) {
2921 transport_controller_->SetActiveResetSrtpParams(
2922 modified_config.active_reset_srtp_params);
2923 }
2924
deadbeef293e9262017-01-11 12:28:30 -08002925 configuration_ = modified_config;
2926 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002927}
2928
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002929bool PeerConnection::AddIceCandidate(
2930 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002931 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002932 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002933 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002934 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002935 return false;
2936 }
Steve Antond25da372017-11-06 14:50:29 -08002937
2938 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002939 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002940 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002941 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002942 return false;
2943 }
2944
2945 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002946 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002947 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002948 return false;
2949 }
2950
2951 bool valid = false;
2952 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2953 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002954 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002955 return false;
2956 }
2957
2958 // Add this candidate to the remote session description.
2959 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002960 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002961 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002962 return false;
2963 }
2964
2965 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002966 bool result = UseCandidate(ice_candidate);
2967 if (result) {
2968 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2969 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2970 } else {
2971 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2972 }
2973 return result;
Steve Antond25da372017-11-06 14:50:29 -08002974 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002975 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002976 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002977 return true;
2978 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002979}
2980
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002981bool PeerConnection::RemoveIceCandidates(
2982 const std::vector<cricket::Candidate>& candidates) {
2983 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002984 if (IsClosed()) {
2985 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2986 return false;
2987 }
2988
Steve Antond25da372017-11-06 14:50:29 -08002989 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002990 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2991 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002992 return false;
2993 }
2994
2995 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002996 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002997 return false;
2998 }
2999
3000 size_t number_removed =
3001 mutable_remote_description()->RemoveCandidates(candidates);
3002 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003003 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003004 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003005 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003006 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003007 }
3008
3009 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003010 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3011 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003012 RTC_LOG(LS_ERROR)
3013 << "RemoveIceCandidates: Error when removing remote candidates: "
3014 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003015 }
3016 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003017}
3018
Niels Möller0c4f7be2018-05-07 14:01:37 +02003019RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003020 if (!worker_thread()->IsCurrent()) {
3021 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003022 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003023 }
3024
Niels Möller0c4f7be2018-05-07 14:01:37 +02003025 const bool has_min = bitrate.min_bitrate_bps.has_value();
3026 const bool has_start = bitrate.start_bitrate_bps.has_value();
3027 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003028 if (has_min && *bitrate.min_bitrate_bps < 0) {
3029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3030 "min_bitrate_bps <= 0");
3031 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003032 if (has_start) {
3033 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003034 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003035 "start_bitrate_bps < min_bitrate_bps");
3036 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003037 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3038 "curent_bitrate_bps < 0");
3039 }
3040 }
3041 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003042 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003043 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003044 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003045 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3046 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3047 "max_bitrate_bps < min_bitrate_bps");
3048 } else if (*bitrate.max_bitrate_bps < 0) {
3049 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3050 "max_bitrate_bps < 0");
3051 }
3052 }
3053
zstein4b979802017-06-02 14:37:37 -07003054 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003055 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003056
3057 return RTCError::OK();
3058}
3059
Alex Narest78609d52017-10-20 10:37:47 +02003060void PeerConnection::SetBitrateAllocationStrategy(
3061 std::unique_ptr<rtc::BitrateAllocationStrategy>
3062 bitrate_allocation_strategy) {
3063 rtc::Thread* worker_thread = factory_->worker_thread();
3064 if (!worker_thread->IsCurrent()) {
3065 rtc::BitrateAllocationStrategy* strategy_raw =
3066 bitrate_allocation_strategy.release();
3067 auto functor = [this, strategy_raw]() {
3068 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003069 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003070 };
3071 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3072 return;
3073 }
3074 RTC_DCHECK(call_.get());
3075 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3076}
3077
henrika5f6bf242017-11-01 11:06:56 +01003078void PeerConnection::SetAudioPlayout(bool playout) {
3079 if (!worker_thread()->IsCurrent()) {
3080 worker_thread()->Invoke<void>(
3081 RTC_FROM_HERE,
3082 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3083 return;
3084 }
3085 auto audio_state =
3086 factory_->channel_manager()->media_engine()->GetAudioState();
3087 audio_state->SetPlayout(playout);
3088}
3089
3090void PeerConnection::SetAudioRecording(bool recording) {
3091 if (!worker_thread()->IsCurrent()) {
3092 worker_thread()->Invoke<void>(
3093 RTC_FROM_HERE,
3094 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3095 return;
3096 }
3097 auto audio_state =
3098 factory_->channel_manager()->media_engine()->GetAudioState();
3099 audio_state->SetRecording(recording);
3100}
3101
Steve Anton8c0f7a72017-10-03 10:03:10 -07003102std::unique_ptr<rtc::SSLCertificate>
3103PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003104 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3105 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003106 return nullptr;
3107 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003108 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003109}
3110
Zhi Huang70b820f2018-01-27 14:16:15 -08003111std::unique_ptr<rtc::SSLCertChain>
3112PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003113 auto audio_transceiver = GetFirstAudioTransceiver();
3114 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003115 return nullptr;
3116 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003117 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003118 audio_transceiver->internal()->channel()->transport_name());
3119}
3120
3121rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3122PeerConnection::GetFirstAudioTransceiver() const {
3123 for (auto transceiver : transceivers_) {
3124 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3125 return transceiver;
3126 }
3127 }
3128 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003129}
3130
ivoc14d5dbe2016-07-04 07:06:55 -07003131bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3132 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003133 // TODO(eladalon): It would be better to not allow negative values into PC.
3134 const size_t max_size = (max_size_bytes < 0)
3135 ? RtcEventLog::kUnlimitedOutput
3136 : rtc::saturated_cast<size_t>(max_size_bytes);
3137 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003138 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003139 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003140}
3141
Bjorn Tereliusde939432017-11-20 17:38:14 +01003142bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3143 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003144 // TODO(eladalon): In C++14, this can be done with a lambda.
3145 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003146 bool operator()() {
3147 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3148 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003149 PeerConnection* const pc;
3150 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003151 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003152 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003153 return worker_thread()->Invoke<bool>(
3154 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003155}
3156
3157void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003158 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003159 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3160}
3161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003163 return pending_local_description_ ? pending_local_description_.get()
3164 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003165}
3166
3167const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003168 return pending_remote_description_ ? pending_remote_description_.get()
3169 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170}
3171
deadbeeffe4a8a42016-12-20 17:56:17 -08003172const SessionDescriptionInterface* PeerConnection::current_local_description()
3173 const {
Steve Anton75737c02017-11-06 10:37:17 -08003174 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003175}
3176
3177const SessionDescriptionInterface* PeerConnection::current_remote_description()
3178 const {
Steve Anton75737c02017-11-06 10:37:17 -08003179 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003180}
3181
3182const SessionDescriptionInterface* PeerConnection::pending_local_description()
3183 const {
Steve Anton75737c02017-11-06 10:37:17 -08003184 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003185}
3186
3187const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3188 const {
Steve Anton75737c02017-11-06 10:37:17 -08003189 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003190}
3191
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003192void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003193 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194 // Update stats here so that we have the most recent stats for tracks and
3195 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003196 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197
Steve Anton75737c02017-11-06 10:37:17 -08003198 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003199 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003200
Steve Anton8af21862017-12-15 11:20:13 -08003201 for (auto transceiver : transceivers_) {
3202 transceiver->Stop();
3203 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003204
3205 // Ensure that all asynchronous stats requests are completed before destroying
3206 // the transport controller below.
3207 if (stats_collector_) {
3208 stats_collector_->WaitForPendingRequest();
3209 }
3210
3211 // Don't destroy BaseChannels until after stats has been cleaned up so that
3212 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003213 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003214
Qingsi Wang93a84392018-01-30 17:13:09 -08003215 // The event log is used in the transport controller, which must be outlived
3216 // by the former. CreateOffer by the peer connection is implemented
3217 // asynchronously and if the peer connection is closed without resetting the
3218 // WebRTC session description factory, the session description factory would
3219 // call the transport controller.
3220 webrtc_session_desc_factory_.reset();
3221 transport_controller_.reset();
3222
deadbeef42a42632017-03-10 15:18:00 -08003223 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003224 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3225 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003226
Steve Anton978b8762017-09-29 12:15:02 -07003227 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003228 call_.reset();
3229 // The event log must outlive call (and any other object that uses it).
3230 event_log_.reset();
3231 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003232 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003233 // The .h file says that observer can be discarded after close() returns.
3234 // Make sure this is true.
3235 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003236}
3237
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003238void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3241 SetSessionDescriptionMsg* param =
3242 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3243 param->observer->OnSuccess();
3244 delete param;
3245 break;
3246 }
3247 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3248 SetSessionDescriptionMsg* param =
3249 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003250 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 delete param;
3252 break;
3253 }
deadbeefab9b2d12015-10-14 11:33:11 -07003254 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3255 CreateSessionDescriptionMsg* param =
3256 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003257 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003258 delete param;
3259 break;
3260 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 case MSG_GETSTATS: {
3262 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003263 StatsReports reports;
3264 stats_->GetStats(param->track, &reports);
3265 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266 delete param;
3267 break;
3268 }
deadbeefbd292462015-12-14 18:15:29 -08003269 case MSG_FREE_DATACHANNELS: {
3270 sctp_data_channels_to_free_.clear();
3271 break;
3272 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003273 case MSG_REPORT_USAGE_PATTERN: {
3274 ReportUsagePattern();
3275 break;
3276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003278 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 break;
3280 }
3281}
3282
Steve Antonafb0bb72018-02-20 11:35:37 -08003283cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3284 RTC_DCHECK(!IsUnifiedPlan());
3285 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3286 GetAudioTransceiver()->internal()->channel());
3287 if (voice_channel) {
3288 return voice_channel->media_channel();
3289 } else {
3290 return nullptr;
3291 }
3292}
3293
3294cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3295 RTC_DCHECK(!IsUnifiedPlan());
3296 auto* video_channel = static_cast<cricket::VideoChannel*>(
3297 GetVideoTransceiver()->internal()->channel());
3298 if (video_channel) {
3299 return video_channel->media_channel();
3300 } else {
3301 return nullptr;
3302 }
3303}
3304
Steve Anton4171afb2017-11-20 10:20:22 -08003305void PeerConnection::CreateAudioReceiver(
3306 MediaStreamInterface* stream,
3307 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003308 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3309 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003310 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3311 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003312 auto* audio_receiver = new AudioRtpReceiver(
3313 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003314 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003315 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3316 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3317 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003318 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003319 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003320 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321}
3322
Steve Anton4171afb2017-11-20 10:20:22 -08003323void PeerConnection::CreateVideoReceiver(
3324 MediaStreamInterface* stream,
3325 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003326 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3327 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003328 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3329 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003330 auto* video_receiver = new VideoRtpReceiver(
3331 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003332 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003333 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3334 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3335 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003336 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003337 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003338 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339}
3340
deadbeef70ab1a12015-09-28 16:53:55 -07003341// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3342// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003343rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003344 const RtpSenderInfo& remote_sender_info) {
3345 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3346 if (!receiver) {
3347 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3348 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003349 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003350 }
Steve Anton4171afb2017-11-20 10:20:22 -08003351 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3352 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3353 } else {
3354 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3355 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003356 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003359void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3360 MediaStreamInterface* stream) {
3361 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003362 RTC_DCHECK(track);
3363 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003364 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003365 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003366 // We already have a sender for this track, so just change the stream_id
3367 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003368 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003369 return;
3370 }
3371
3372 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003373 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3374 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003375 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003376 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003377 // If the sender has already been configured in SDP, we call SetSsrc,
3378 // which will connect the sender to the underlying transport. This can
3379 // occur if a local session description that contains the ID of the sender
3380 // is set before AddStream is called. It can also occur if the local
3381 // session description is not changed and RemoveStream is called, and
3382 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003383 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003384 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003385 if (sender_info) {
3386 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003387 }
3388}
3389
3390// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3391// indefinitely, when we have unified plan SDP.
3392void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3393 MediaStreamInterface* stream) {
3394 RTC_DCHECK(!IsClosed());
3395 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003396 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003397 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3398 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003399 return;
3400 }
Steve Anton4171afb2017-11-20 10:20:22 -08003401 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003402}
3403
3404void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3405 MediaStreamInterface* stream) {
3406 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003407 RTC_DCHECK(track);
3408 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003409 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003410 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003411 // We already have a sender for this track, so just change the stream_id
3412 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003413 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003414 return;
3415 }
3416
3417 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003418 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3419 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003420 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003421 GetVideoTransceiver()->internal()->AddSender(new_sender);
3422 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003423 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003424 if (sender_info) {
3425 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003426 }
3427}
3428
3429void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3430 MediaStreamInterface* stream) {
3431 RTC_DCHECK(!IsClosed());
3432 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003433 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003434 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3435 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003436 return;
3437 }
Steve Anton4171afb2017-11-20 10:20:22 -08003438 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003439}
3440
Steve Antonba818672017-11-06 10:21:57 -08003441void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003442 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003443 if (ice_connection_state_ == new_state) {
3444 return;
3445 }
3446
deadbeefcbecd352015-09-23 11:50:27 -07003447 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003448 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003449 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003450 return;
3451 }
Steve Antonba818672017-11-06 10:21:57 -08003452
Mirko Bonadei675513b2017-11-09 11:09:25 +01003453 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3454 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003455 RTC_DCHECK(ice_connection_state_ !=
3456 PeerConnectionInterface::kIceConnectionClosed);
3457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003459 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460}
3461
3462void PeerConnection::OnIceGatheringChange(
3463 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003464 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003465 if (IsClosed()) {
3466 return;
3467 }
3468 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003469 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003470}
3471
jbauch81bf7b02017-03-25 08:31:12 -07003472void PeerConnection::OnIceCandidate(
3473 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003474 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003475 if (IsClosed()) {
3476 return;
3477 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003478 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003479 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3480 candidate->candidate().address().IsPrivateIP()) {
3481 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3482 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003483 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003484}
3485
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003486void PeerConnection::OnIceCandidatesRemoved(
3487 const std::vector<cricket::Candidate>& candidates) {
3488 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003489 if (IsClosed()) {
3490 return;
3491 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003492 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003493}
3494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495void PeerConnection::ChangeSignalingState(
3496 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003497 RTC_DCHECK(signaling_thread()->IsCurrent());
3498 if (signaling_state_ == signaling_state) {
3499 return;
3500 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003501 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3502 << GetSignalingStateString(signaling_state_)
3503 << " New state: "
3504 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003505 signaling_state_ = signaling_state;
3506 if (signaling_state == kClosed) {
3507 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003508 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509 if (ice_gathering_state_ != kIceGatheringComplete) {
3510 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003511 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003512 }
3513 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003514 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003515}
3516
deadbeefeb459812015-12-15 19:24:43 -08003517void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3518 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003519 if (IsClosed()) {
3520 return;
3521 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003522 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003523 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003524}
3525
deadbeefeb459812015-12-15 19:24:43 -08003526void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3527 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003528 if (IsClosed()) {
3529 return;
3530 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003531 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003532 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003533}
3534
3535void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3536 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003537 if (IsClosed()) {
3538 return;
3539 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003540 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003541 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003542}
3543
3544void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3545 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003546 if (IsClosed()) {
3547 return;
3548 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003549 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003550 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003551}
3552
Henrik Boström31638672017-11-23 17:48:32 +01003553void PeerConnection::PostSetSessionDescriptionSuccess(
3554 SetSessionDescriptionObserver* observer) {
3555 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3556 signaling_thread()->Post(RTC_FROM_HERE, this,
3557 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3558}
3559
deadbeefab9b2d12015-10-14 11:33:11 -07003560void PeerConnection::PostSetSessionDescriptionFailure(
3561 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003562 RTCError&& error) {
3563 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003564 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003565 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003566 signaling_thread()->Post(RTC_FROM_HERE, this,
3567 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003568}
3569
3570void PeerConnection::PostCreateSessionDescriptionFailure(
3571 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003572 RTCError error) {
3573 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003574 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003575 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003576 signaling_thread()->Post(RTC_FROM_HERE, this,
3577 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003578}
3579
zhihuang1c378ed2017-08-17 14:10:50 -07003580void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003581 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003582 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003583 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003584
Steve Antondcc3c022017-12-22 16:02:54 -08003585 if (IsUnifiedPlan()) {
3586 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3587 } else {
3588 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3589 }
3590
Steve Antonfa2260d2017-12-28 16:38:23 -08003591 // Intentionally unset the data channel type for RTP data channel with the
3592 // second condition. Otherwise the RTP data channels would be successfully
3593 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3594 // when building with chromium. We want to leave RTP data channels broken, so
3595 // people won't try to use them.
3596 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3597 session_options->data_channel_type = data_channel_type();
3598 }
3599
Steve Antondcc3c022017-12-22 16:02:54 -08003600 // Apply ICE restart flag and renomination flag.
3601 for (auto& options : session_options->media_description_options) {
3602 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3603 options.transport_options.enable_ice_renomination =
3604 configuration_.enable_ice_renomination;
3605 }
3606
3607 session_options->rtcp_cname = rtcp_cname_;
3608 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003609 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003610}
3611
3612void PeerConnection::GetOptionsForPlanBOffer(
3613 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3614 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003615 // Figure out transceiver directional preferences.
3616 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3617 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3618
3619 // By default, generate sendrecv/recvonly m= sections.
3620 bool recv_audio = true;
3621 bool recv_video = true;
3622
3623 // By default, only offer a new m= section if we have media to send with it.
3624 bool offer_new_audio_description = send_audio;
3625 bool offer_new_video_description = send_video;
3626 bool offer_new_data_description = HasDataChannels();
3627
3628 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003629 if (offer_answer_options.offer_to_receive_audio !=
3630 RTCOfferAnswerOptions::kUndefined) {
3631 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003632 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003633 offer_new_audio_description ||
3634 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003635 }
Steve Antondcc3c022017-12-22 16:02:54 -08003636 if (offer_answer_options.offer_to_receive_video !=
3637 RTCOfferAnswerOptions::kUndefined) {
3638 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003639 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003640 offer_new_video_description ||
3641 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003642 }
3643
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003644 absl::optional<size_t> audio_index;
3645 absl::optional<size_t> video_index;
3646 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003647 // If a current description exists, generate m= sections in the same order,
3648 // using the first audio/video/data section that appears and rejecting
3649 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003650 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003651 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003652 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003653 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3654 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3655 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003656 }
3657
zhihuang1c378ed2017-08-17 14:10:50 -07003658 // Add audio/video/data m= sections to the end if needed.
3659 if (!audio_index && offer_new_audio_description) {
3660 session_options->media_description_options.push_back(
3661 cricket::MediaDescriptionOptions(
3662 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003663 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3664 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003665 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003666 }
zhihuang1c378ed2017-08-17 14:10:50 -07003667 if (!video_index && offer_new_video_description) {
3668 session_options->media_description_options.push_back(
3669 cricket::MediaDescriptionOptions(
3670 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003671 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3672 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003673 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003674 }
zhihuang1c378ed2017-08-17 14:10:50 -07003675 if (!data_index && offer_new_data_description) {
3676 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003677 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003678 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003679 }
3680
3681 cricket::MediaDescriptionOptions* audio_media_description_options =
3682 !audio_index ? nullptr
3683 : &session_options->media_description_options[*audio_index];
3684 cricket::MediaDescriptionOptions* video_media_description_options =
3685 !video_index ? nullptr
3686 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003687
Steve Anton4171afb2017-11-20 10:20:22 -08003688 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003689 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003690}
3691
3692// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3693// and return a reference to it.
3694// Generated MIDs should be no more than 3 bytes long to take up less space in
3695// the RTP packet.
3696static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3697 RTC_DCHECK(used_mids);
3698 // We're boring: just generate MIDs 0, 1, 2, ...
3699 size_t i = 0;
3700 std::set<std::string>::iterator it;
3701 bool inserted;
3702 do {
3703 std::string mid = rtc::ToString(i++);
3704 auto insert_result = used_mids->insert(mid);
3705 it = insert_result.first;
3706 inserted = insert_result.second;
3707 } while (!inserted);
3708 return *it;
3709}
3710
3711static cricket::MediaDescriptionOptions
3712GetMediaDescriptionOptionsForTransceiver(
3713 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3714 transceiver,
3715 const std::string& mid) {
3716 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003717 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003718 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003719 // This behavior is specified in JSEP. The gist is that:
3720 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3721 // sendrecv.
3722 // 2. If the MSID is included, then it must be included in any subsequent
3723 // offer/answer exactly the same until the RtpTransceiver is stopped.
3724 if (!transceiver->stopped() &&
3725 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3726 transceiver->internal()->has_ever_been_used_to_send())) {
3727 cricket::SenderOptions sender_options;
3728 sender_options.track_id = transceiver->sender()->id();
3729 sender_options.stream_ids = transceiver->sender()->stream_ids();
3730 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3731 // set in the RTP parameters when the transceiver was added.
3732 sender_options.num_sim_layers = 1;
3733 media_description_options.sender_options.push_back(sender_options);
3734 }
Steve Antondcc3c022017-12-22 16:02:54 -08003735 return media_description_options;
3736}
3737
3738void PeerConnection::GetOptionsForUnifiedPlanOffer(
3739 const RTCOfferAnswerOptions& offer_answer_options,
3740 cricket::MediaSessionOptions* session_options) {
3741 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3742 // Offers) and 5.2.2 (Subsequent Offers).
3743 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3744 const ContentInfos& local_contents =
3745 (local_description() ? local_description()->description()->contents()
3746 : ContentInfos());
3747 const ContentInfos& remote_contents =
3748 (remote_description() ? remote_description()->description()->contents()
3749 : ContentInfos());
3750 // The mline indices that can be recycled. New transceivers should reuse these
3751 // slots first.
3752 std::queue<size_t> recycleable_mline_indices;
3753 // Track the MIDs used in previous offer/answer exchanges and the current
3754 // offer so that new, unique MIDs are generated.
3755 std::set<std::string> used_mids = seen_mids_;
3756 // First, go through each media section that exists in either the local or
3757 // remote description and generate a media section in this offer for the
3758 // associated transceiver. If a media section can be recycled, generate a
3759 // default, rejected media section here that can be later overwritten.
3760 for (size_t i = 0;
3761 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3762 // Either |local_content| or |remote_content| is non-null.
3763 const ContentInfo* local_content =
3764 (i < local_contents.size() ? &local_contents[i] : nullptr);
3765 const ContentInfo* remote_content =
3766 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3767 bool had_been_rejected = (local_content && local_content->rejected) ||
3768 (remote_content && remote_content->rejected);
3769 const std::string& mid =
3770 (local_content ? local_content->name : remote_content->name);
3771 cricket::MediaType media_type =
3772 (local_content ? local_content->media_description()->type()
3773 : remote_content->media_description()->type());
3774 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3775 media_type == cricket::MEDIA_TYPE_VIDEO) {
3776 auto transceiver = GetAssociatedTransceiver(mid);
3777 RTC_CHECK(transceiver);
3778 // A media section is considered eligible for recycling if it is marked as
3779 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003780 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003781 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003782 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3783 RtpTransceiverDirection::kInactive,
3784 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003785 recycleable_mline_indices.push(i);
3786 } else {
3787 session_options->media_description_options.push_back(
3788 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3789 // CreateOffer shouldn't really cause any state changes in
3790 // PeerConnection, but we need a way to match new transceivers to new
3791 // media sections in SetLocalDescription and JSEP specifies this is done
3792 // by recording the index of the media section generated for the
3793 // transceiver in the offer.
3794 transceiver->internal()->set_mline_index(i);
3795 }
3796 } else {
3797 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003798 RTC_CHECK(GetDataMid());
3799 if (had_been_rejected || mid != *GetDataMid()) {
3800 session_options->media_description_options.push_back(
3801 GetMediaDescriptionOptionsForRejectedData(mid));
3802 } else {
3803 session_options->media_description_options.push_back(
3804 GetMediaDescriptionOptionsForActiveData(mid));
3805 }
Steve Antondcc3c022017-12-22 16:02:54 -08003806 }
3807 }
3808 // Next, look for transceivers that are newly added (that is, are not stopped
3809 // and not associated). Reuse media sections marked as recyclable first,
3810 // otherwise append to the end of the offer. New media sections should be
3811 // added in the order they were added to the PeerConnection.
3812 for (auto transceiver : transceivers_) {
3813 if (transceiver->mid() || transceiver->stopped()) {
3814 continue;
3815 }
3816 size_t mline_index;
3817 if (!recycleable_mline_indices.empty()) {
3818 mline_index = recycleable_mline_indices.front();
3819 recycleable_mline_indices.pop();
3820 session_options->media_description_options[mline_index] =
3821 GetMediaDescriptionOptionsForTransceiver(transceiver,
3822 AllocateMid(&used_mids));
3823 } else {
3824 mline_index = session_options->media_description_options.size();
3825 session_options->media_description_options.push_back(
3826 GetMediaDescriptionOptionsForTransceiver(transceiver,
3827 AllocateMid(&used_mids)));
3828 }
3829 // See comment above for why CreateOffer changes the transceiver's state.
3830 transceiver->internal()->set_mline_index(mline_index);
3831 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003832 // Lastly, add a m-section if we have local data channels and an m section
3833 // does not already exist.
3834 if (!GetDataMid() && HasDataChannels()) {
3835 session_options->media_description_options.push_back(
3836 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3837 }
Steve Antondcc3c022017-12-22 16:02:54 -08003838}
3839
3840void PeerConnection::GetOptionsForAnswer(
3841 const RTCOfferAnswerOptions& offer_answer_options,
3842 cricket::MediaSessionOptions* session_options) {
3843 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3844
3845 if (IsUnifiedPlan()) {
3846 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3847 } else {
3848 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3849 }
3850
Steve Antonfa2260d2017-12-28 16:38:23 -08003851 // Intentionally unset the data channel type for RTP data channel. Otherwise
3852 // the RTP data channels would be successfully negotiated by default and the
3853 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3854 // We want to leave RTP data channels broken, so people won't try to use them.
3855 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3856 session_options->data_channel_type = data_channel_type();
3857 }
3858
Steve Antondcc3c022017-12-22 16:02:54 -08003859 // Apply ICE renomination flag.
3860 for (auto& options : session_options->media_description_options) {
3861 options.transport_options.enable_ice_renomination =
3862 configuration_.enable_ice_renomination;
3863 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003864
3865 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003866 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003867 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003868}
3869
Steve Antondcc3c022017-12-22 16:02:54 -08003870void PeerConnection::GetOptionsForPlanBAnswer(
3871 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003872 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003873 // Figure out transceiver directional preferences.
3874 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3875 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3876
3877 // By default, generate sendrecv/recvonly m= sections. The direction is also
3878 // restricted by the direction in the offer.
3879 bool recv_audio = true;
3880 bool recv_video = true;
3881
3882 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003883 if (offer_answer_options.offer_to_receive_audio !=
3884 RTCOfferAnswerOptions::kUndefined) {
3885 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003886 }
Steve Antondcc3c022017-12-22 16:02:54 -08003887 if (offer_answer_options.offer_to_receive_video !=
3888 RTCOfferAnswerOptions::kUndefined) {
3889 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003890 }
3891
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003892 absl::optional<size_t> audio_index;
3893 absl::optional<size_t> video_index;
3894 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003895
3896 // Generate m= sections that match those in the offer.
3897 // Note that mediasession.cc will handle intersection our preferred
3898 // direction with the offered direction.
3899 GenerateMediaDescriptionOptions(
3900 remote_description(),
3901 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3902 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3903 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003904
3905 cricket::MediaDescriptionOptions* audio_media_description_options =
3906 !audio_index ? nullptr
3907 : &session_options->media_description_options[*audio_index];
3908 cricket::MediaDescriptionOptions* video_media_description_options =
3909 !video_index ? nullptr
3910 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003911
Steve Anton4171afb2017-11-20 10:20:22 -08003912 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003913 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003914}
zhihuangaf388472016-11-02 16:49:48 -07003915
Steve Antondcc3c022017-12-22 16:02:54 -08003916void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3917 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3918 cricket::MediaSessionOptions* session_options) {
3919 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3920 // Answers) and 5.3.2 (Subsequent Answers).
3921 RTC_DCHECK(remote_description());
3922 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3923 for (const ContentInfo& content :
3924 remote_description()->description()->contents()) {
3925 cricket::MediaType media_type = content.media_description()->type();
3926 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3927 media_type == cricket::MEDIA_TYPE_VIDEO) {
3928 auto transceiver = GetAssociatedTransceiver(content.name);
3929 RTC_CHECK(transceiver);
3930 session_options->media_description_options.push_back(
3931 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3932 } else {
3933 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003934 // Reject all data sections if data channels are disabled.
3935 // Reject a data section if it has already been rejected.
3936 // Reject all data sections except for the first one.
3937 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3938 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003939 session_options->media_description_options.push_back(
3940 GetMediaDescriptionOptionsForRejectedData(content.name));
3941 } else {
3942 session_options->media_description_options.push_back(
3943 GetMediaDescriptionOptionsForActiveData(content.name));
3944 }
Steve Antondcc3c022017-12-22 16:02:54 -08003945 }
3946 }
htaa2a49d92016-03-04 02:51:39 -08003947}
3948
zhihuang1c378ed2017-08-17 14:10:50 -07003949void PeerConnection::GenerateMediaDescriptionOptions(
3950 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003951 RtpTransceiverDirection audio_direction,
3952 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003953 absl::optional<size_t>* audio_index,
3954 absl::optional<size_t>* video_index,
3955 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003956 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003957 for (const cricket::ContentInfo& content :
3958 session_desc->description()->contents()) {
3959 if (IsAudioContent(&content)) {
3960 // If we already have an audio m= section, reject this extra one.
3961 if (*audio_index) {
3962 session_options->media_description_options.push_back(
3963 cricket::MediaDescriptionOptions(
3964 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003965 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003966 } else {
3967 session_options->media_description_options.push_back(
3968 cricket::MediaDescriptionOptions(
3969 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003970 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003971 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003972 }
3973 } else if (IsVideoContent(&content)) {
3974 // If we already have an video m= section, reject this extra one.
3975 if (*video_index) {
3976 session_options->media_description_options.push_back(
3977 cricket::MediaDescriptionOptions(
3978 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003979 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003980 } else {
3981 session_options->media_description_options.push_back(
3982 cricket::MediaDescriptionOptions(
3983 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003984 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003985 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003986 }
3987 } else {
3988 RTC_DCHECK(IsDataContent(&content));
3989 // If we already have an data m= section, reject this extra one.
3990 if (*data_index) {
3991 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003992 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003993 } else {
3994 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003995 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003996 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003997 }
3998 }
htaa2a49d92016-03-04 02:51:39 -08003999 }
deadbeefab9b2d12015-10-14 11:33:11 -07004000}
4001
Steve Antonfa2260d2017-12-28 16:38:23 -08004002cricket::MediaDescriptionOptions
4003PeerConnection::GetMediaDescriptionOptionsForActiveData(
4004 const std::string& mid) const {
4005 // Direction for data sections is meaningless, but legacy endpoints might
4006 // expect sendrecv.
4007 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4008 RtpTransceiverDirection::kSendRecv,
4009 /*stopped=*/false);
4010 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4011 return options;
4012}
4013
4014cricket::MediaDescriptionOptions
4015PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4016 const std::string& mid) const {
4017 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4018 RtpTransceiverDirection::kInactive,
4019 /*stopped=*/true);
4020 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4021 return options;
4022}
4023
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004024absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004025 switch (data_channel_type_) {
4026 case cricket::DCT_RTP:
4027 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004028 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004029 }
4030 return rtp_data_channel_->content_name();
4031 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004032 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004033 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004034 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004035 }
4036}
4037
Steve Anton4171afb2017-11-20 10:20:22 -08004038void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4039 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4040 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004041 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004042}
4043
Steve Anton4171afb2017-11-20 10:20:22 -08004044void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004045 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004046 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004047 cricket::MediaType media_type,
4048 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004049 RTC_DCHECK(!IsUnifiedPlan());
4050
Steve Anton4171afb2017-11-20 10:20:22 -08004051 std::vector<RtpSenderInfo>* current_senders =
4052 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004053
Steve Anton4171afb2017-11-20 10:20:22 -08004054 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004055 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004056 for (auto sender_it = current_senders->begin();
4057 sender_it != current_senders->end();
4058 /* incremented manually */) {
4059 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004060 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004061 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004062 std::string params_stream_id;
4063 if (params) {
4064 params_stream_id =
4065 (!params->first_stream_id().empty() ? params->first_stream_id()
4066 : kDefaultStreamId);
4067 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004068 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004069 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004070 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004071 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004072 sender_exists) {
4073 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004074 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004075 OnRemoteSenderRemoved(info, media_type);
4076 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004077 }
4078 }
4079
Steve Anton4171afb2017-11-20 10:20:22 -08004080 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004081 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004082 if (!params.has_ssrcs()) {
4083 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4084 // sender, this means it is coming from a Unified Plan endpoint,so we just
4085 // create a default.
4086 default_sender_needed = true;
4087 break;
4088 }
4089
Seth Hampson845e8782018-03-02 11:34:10 -08004090 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004091 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004092 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4093 // not supported in Plan B, we just take the first here and create the
4094 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004095 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004096 (!params.first_stream_id().empty() ? params.first_stream_id()
4097 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004098 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004099 uint32_t ssrc = params.first_ssrc();
4100
4101 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004102 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004103 if (!stream) {
4104 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004105 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004106 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004107 remote_streams_->AddStream(stream);
4108 new_streams->AddStream(stream);
4109 }
4110
Steve Anton4171afb2017-11-20 10:20:22 -08004111 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004112 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004113 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004114 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004115 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004116 }
4117 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004118
Steve Anton4171afb2017-11-20 10:20:22 -08004119 // Add default sender if necessary.
4120 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004121 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004122 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004123 if (!default_stream) {
4124 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004125 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004126 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004127 remote_streams_->AddStream(default_stream);
4128 new_streams->AddStream(default_stream);
4129 }
Steve Anton4171afb2017-11-20 10:20:22 -08004130 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4131 ? kDefaultAudioSenderId
4132 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004133 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004134 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004135 if (!default_sender_info) {
4136 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004137 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004138 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004139 }
4140 }
deadbeefab9b2d12015-10-14 11:33:11 -07004141}
4142
Steve Anton4171afb2017-11-20 10:20:22 -08004143void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4144 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004145 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4146 << " receiver for track_id=" << sender_info.sender_id
4147 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004148
Steve Anton3d954a62018-04-02 11:27:23 -07004149 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004150 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004151 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004152 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004153 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004154 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004155 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004156 }
4157}
4158
Steve Anton4171afb2017-11-20 10:20:22 -08004159void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4160 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004161 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4162 << " receiver for track_id=" << sender_info.sender_id
4163 << " and stream_id=" << sender_info.stream_id;
4164
Seth Hampson845e8782018-03-02 11:34:10 -08004165 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004166
Henrik Boström933d8b02017-10-10 10:05:16 -07004167 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004168 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004169 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4170 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004171 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004172 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004173 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004174 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004175 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004176 }
4177 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004178 // Stopping or destroying a VideoRtpReceiver will end the
4179 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004180 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004181 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004182 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004183 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004184 // There's no guarantee the track is still available, e.g. the track may
4185 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004186 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004187 }
4188 } else {
nisseede5da42017-01-12 05:15:36 -08004189 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004190 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004191 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004192 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004193 }
deadbeefab9b2d12015-10-14 11:33:11 -07004194}
4195
4196void PeerConnection::UpdateEndedRemoteMediaStreams() {
4197 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4198 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4199 MediaStreamInterface* stream = remote_streams_->at(i);
4200 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4201 streams_to_remove.push_back(stream);
4202 }
4203 }
4204
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004205 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004206 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004207 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004208 }
4209}
4210
Steve Anton4171afb2017-11-20 10:20:22 -08004211void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004212 const std::vector<cricket::StreamParams>& streams,
4213 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004214 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004215
Seth Hampson845e8782018-03-02 11:34:10 -08004216 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004217 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004218 for (auto sender_it = current_senders->begin();
4219 sender_it != current_senders->end();
4220 /* incremented manually */) {
4221 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004222 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004223 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4224 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004225 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004226 OnLocalSenderRemoved(info, media_type);
4227 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004228 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004229 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004230 }
4231 }
4232
Steve Anton4171afb2017-11-20 10:20:22 -08004233 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004234 for (const cricket::StreamParams& params : streams) {
4235 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004236 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004237 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004238 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004239 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004240 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004241 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004242 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004243 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004244 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004245 }
4246 }
4247}
4248
Steve Anton4171afb2017-11-20 10:20:22 -08004249void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4250 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004251 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004252 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004253 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004254 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4255 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004256 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004257 return;
4258 }
4259
deadbeeffac06552015-11-25 11:26:01 -08004260 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004261 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004262 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004263 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004264 }
deadbeeffac06552015-11-25 11:26:01 -08004265
Seth Hampson5b4f0752018-04-02 16:31:36 -07004266 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004267 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004268}
4269
Steve Anton4171afb2017-11-20 10:20:22 -08004270void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4271 cricket::MediaType media_type) {
4272 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004273 if (!sender) {
4274 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004275 // SessionDescriptions has been renegotiated.
4276 return;
4277 }
deadbeeffac06552015-11-25 11:26:01 -08004278
4279 // A sender has been removed from the SessionDescription but it's still
4280 // associated with the PeerConnection. This only occurs if the SDP doesn't
4281 // match with the calls to CreateSender, AddStream and RemoveStream.
4282 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004283 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004284 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004285 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004286 }
deadbeeffac06552015-11-25 11:26:01 -08004287
Steve Anton4171afb2017-11-20 10:20:22 -08004288 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004289}
4290
4291void PeerConnection::UpdateLocalRtpDataChannels(
4292 const cricket::StreamParamsVec& streams) {
4293 std::vector<std::string> existing_channels;
4294
4295 // Find new and active data channels.
4296 for (const cricket::StreamParams& params : streams) {
4297 // |it->sync_label| is actually the data channel label. The reason is that
4298 // we use the same naming of data channels as we do for
4299 // MediaStreams and Tracks.
4300 // For MediaStreams, the sync_label is the MediaStream label and the
4301 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004302 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004303 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004304 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004305 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004306 continue;
4307 }
4308 // Set the SSRC the data channel should use for sending.
4309 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4310 existing_channels.push_back(data_channel_it->first);
4311 }
4312
4313 UpdateClosingRtpDataChannels(existing_channels, true);
4314}
4315
4316void PeerConnection::UpdateRemoteRtpDataChannels(
4317 const cricket::StreamParamsVec& streams) {
4318 std::vector<std::string> existing_channels;
4319
4320 // Find new and active data channels.
4321 for (const cricket::StreamParams& params : streams) {
4322 // The data channel label is either the mslabel or the SSRC if the mslabel
4323 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004324 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004325 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004326 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004327 auto data_channel_it = rtp_data_channels_.find(label);
4328 if (data_channel_it == rtp_data_channels_.end()) {
4329 // This is a new data channel.
4330 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4331 } else {
4332 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4333 }
4334 existing_channels.push_back(label);
4335 }
4336
4337 UpdateClosingRtpDataChannels(existing_channels, false);
4338}
4339
4340void PeerConnection::UpdateClosingRtpDataChannels(
4341 const std::vector<std::string>& active_channels,
4342 bool is_local_update) {
4343 auto it = rtp_data_channels_.begin();
4344 while (it != rtp_data_channels_.end()) {
4345 DataChannel* data_channel = it->second;
4346 if (std::find(active_channels.begin(), active_channels.end(),
4347 data_channel->label()) != active_channels.end()) {
4348 ++it;
4349 continue;
4350 }
4351
4352 if (is_local_update) {
4353 data_channel->SetSendSsrc(0);
4354 } else {
4355 data_channel->RemotePeerRequestClose();
4356 }
4357
4358 if (data_channel->state() == DataChannel::kClosed) {
4359 rtp_data_channels_.erase(it);
4360 it = rtp_data_channels_.begin();
4361 } else {
4362 ++it;
4363 }
4364 }
4365}
4366
4367void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4368 uint32_t remote_ssrc) {
4369 rtc::scoped_refptr<DataChannel> channel(
4370 InternalCreateDataChannel(label, nullptr));
4371 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004372 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004373 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004374 return;
4375 }
4376 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004377 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4378 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004379 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004380}
4381
4382rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4383 const std::string& label,
4384 const InternalDataChannelInit* config) {
4385 if (IsClosed()) {
4386 return nullptr;
4387 }
Steve Anton75737c02017-11-06 10:37:17 -08004388 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004389 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004390 << "InternalCreateDataChannel: Data is not supported in this call.";
4391 return nullptr;
4392 }
4393 InternalDataChannelInit new_config =
4394 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004395 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004396 if (new_config.id < 0) {
4397 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004398 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004399 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004400 RTC_LOG(LS_ERROR)
4401 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004402 return nullptr;
4403 }
4404 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004405 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004406 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004407 return nullptr;
4408 }
4409 }
4410
Steve Anton75737c02017-11-06 10:37:17 -08004411 rtc::scoped_refptr<DataChannel> channel(
4412 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004413 if (!channel) {
4414 sid_allocator_.ReleaseSid(new_config.id);
4415 return nullptr;
4416 }
4417
4418 if (channel->data_channel_type() == cricket::DCT_RTP) {
4419 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004420 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4421 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004422 return nullptr;
4423 }
4424 rtp_data_channels_[channel->label()] = channel;
4425 } else {
4426 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4427 sctp_data_channels_.push_back(channel);
4428 channel->SignalClosed.connect(this,
4429 &PeerConnection::OnSctpDataChannelClosed);
4430 }
4431
Steve Anton2d8609c2018-01-23 16:38:46 -08004432 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004433 return channel;
4434}
4435
4436bool PeerConnection::HasDataChannels() const {
4437 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4438}
4439
4440void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4441 for (const auto& channel : sctp_data_channels_) {
4442 if (channel->id() < 0) {
4443 int sid;
4444 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004445 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004446 continue;
4447 }
4448 channel->SetSctpSid(sid);
4449 }
4450 }
4451}
4452
4453void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004454 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004455 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4456 ++it) {
4457 if (it->get() == channel) {
4458 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004459 // After the closing procedure is done, it's safe to use this ID for
4460 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004461 sid_allocator_.ReleaseSid(channel->id());
4462 }
deadbeefbd292462015-12-14 18:15:29 -08004463 // Since this method is triggered by a signal from the DataChannel,
4464 // we can't free it directly here; we need to free it asynchronously.
4465 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004466 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004467 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4468 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004469 return;
4470 }
4471 }
4472}
4473
deadbeefab9b2d12015-10-14 11:33:11 -07004474void PeerConnection::OnDataChannelDestroyed() {
4475 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4476 // DataChannel may callback to us and try to modify the list.
4477 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4478 temp_rtp_dcs.swap(rtp_data_channels_);
4479 for (const auto& kv : temp_rtp_dcs) {
4480 kv.second->OnTransportChannelDestroyed();
4481 }
4482
4483 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4484 temp_sctp_dcs.swap(sctp_data_channels_);
4485 for (const auto& channel : temp_sctp_dcs) {
4486 channel->OnTransportChannelDestroyed();
4487 }
4488}
4489
4490void PeerConnection::OnDataChannelOpenMessage(
4491 const std::string& label,
4492 const InternalDataChannelInit& config) {
4493 rtc::scoped_refptr<DataChannel> channel(
4494 InternalCreateDataChannel(label, &config));
4495 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004496 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004497 return;
4498 }
4499
deadbeefa601f5c2016-06-06 14:27:39 -07004500 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4501 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004502 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004503 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004504}
4505
Steve Anton4171afb2017-11-20 10:20:22 -08004506rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4507PeerConnection::GetAudioTransceiver() const {
4508 // This method only works with Plan B SDP, where there is a single
4509 // audio/video transceiver.
4510 RTC_DCHECK(!IsUnifiedPlan());
4511 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004512 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004513 return transceiver;
4514 }
4515 }
4516 RTC_NOTREACHED();
4517 return nullptr;
4518}
4519
4520rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4521PeerConnection::GetVideoTransceiver() const {
4522 // This method only works with Plan B SDP, where there is a single
4523 // audio/video transceiver.
4524 RTC_DCHECK(!IsUnifiedPlan());
4525 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004526 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004527 return transceiver;
4528 }
4529 }
4530 RTC_NOTREACHED();
4531 return nullptr;
4532}
4533
4534// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4535// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004536bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004537 switch (type) {
4538 case cricket::MEDIA_TYPE_AUDIO:
4539 return !GetAudioTransceiver()->internal()->senders().empty();
4540 case cricket::MEDIA_TYPE_VIDEO:
4541 return !GetVideoTransceiver()->internal()->senders().empty();
4542 case cricket::MEDIA_TYPE_DATA:
4543 return false;
4544 }
4545 RTC_NOTREACHED();
4546 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004547}
4548
Steve Anton4171afb2017-11-20 10:20:22 -08004549rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4550PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4551 for (auto transceiver : transceivers_) {
4552 for (auto sender : transceiver->internal()->senders()) {
4553 if (sender->track() == track) {
4554 return sender;
4555 }
4556 }
4557 }
4558 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004559}
4560
Steve Anton4171afb2017-11-20 10:20:22 -08004561rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4562PeerConnection::FindSenderById(const std::string& sender_id) const {
4563 for (auto transceiver : transceivers_) {
4564 for (auto sender : transceiver->internal()->senders()) {
4565 if (sender->id() == sender_id) {
4566 return sender;
4567 }
4568 }
4569 }
4570 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004571}
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4574PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4575 for (auto transceiver : transceivers_) {
4576 for (auto receiver : transceiver->internal()->receivers()) {
4577 if (receiver->id() == receiver_id) {
4578 return receiver;
4579 }
4580 }
4581 }
4582 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004583}
4584
Steve Anton4171afb2017-11-20 10:20:22 -08004585std::vector<PeerConnection::RtpSenderInfo>*
4586PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4587 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4588 media_type == cricket::MEDIA_TYPE_VIDEO);
4589 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4590 ? &remote_audio_sender_infos_
4591 : &remote_video_sender_infos_;
4592}
4593
4594std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004595 cricket::MediaType media_type) {
4596 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4597 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004598 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4599 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004600}
4601
Steve Anton4171afb2017-11-20 10:20:22 -08004602const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4603 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004604 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004605 const std::string sender_id) const {
4606 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004607 if (sender_info.stream_id == stream_id &&
4608 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004609 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004610 }
4611 }
4612 return nullptr;
4613}
4614
4615DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4616 for (const auto& channel : sctp_data_channels_) {
4617 if (channel->id() == sid) {
4618 return channel;
4619 }
4620 }
4621 return nullptr;
4622}
4623
deadbeef91dd5672016-05-18 16:55:30 -07004624bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004625 const cricket::ServerAddresses& stun_servers,
4626 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004627 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004628 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004629 // To handle both internal and externally created port allocator, we will
4630 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004631 port_allocator_flags_ = port_allocator_->flags();
4632 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4633 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4634 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004635 // If the disable-IPv6 flag was specified, we'll not override it
4636 // by experiment.
4637 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004638 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004639 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4640 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004641 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004642 }
4643
zhihuangb09b3f92017-03-07 14:40:51 -08004644 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004645 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004646 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004647 }
4648
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004649 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004650 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004651 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004652 }
4653
honghaiz60347052016-05-31 18:29:12 -07004654 if (configuration.candidate_network_policy ==
4655 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004656 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004658 }
4659
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004660 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004661 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004662 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4663 }
4664
Qingsi Wanga2d60672018-04-11 16:57:45 -07004665 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004666 // No step delay is used while allocating ports.
4667 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4668 port_allocator_->set_candidate_filter(
4669 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004670 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004671
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004672 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004673 for (auto& turn_server : turn_servers_copy) {
4674 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004675 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004676 // Call this last since it may create pooled allocator sessions using the
4677 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004678 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004679 stun_servers, std::move(turn_servers_copy),
4680 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4681 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004682 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004683 return true;
4684}
4685
deadbeef91dd5672016-05-18 16:55:30 -07004686bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004687 const cricket::ServerAddresses& stun_servers,
4688 const std::vector<cricket::RelayServerConfig>& turn_servers,
4689 IceTransportsType type,
4690 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004691 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004692 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004693 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004694 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004695 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004696 // According to JSEP, after setLocalDescription, changing the candidate pool
4697 // size is not allowed, and changing the set of ICE servers will not result
4698 // in new candidates being gathered.
4699 if (local_description()) {
4700 port_allocator_->FreezeCandidatePool();
4701 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004702 // Add the custom tls turn servers if they exist.
4703 auto turn_servers_copy = turn_servers;
4704 for (auto& turn_server : turn_servers_copy) {
4705 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4706 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707 // Call this last since it may create pooled allocator sessions using the
4708 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004709 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004710 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4711 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004712}
4713
Steve Antonba818672017-11-06 10:21:57 -08004714cricket::ChannelManager* PeerConnection::channel_manager() const {
4715 return factory_->channel_manager();
4716}
4717
Elad Alon99c3fe52017-10-13 16:29:40 +02004718bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004719 std::unique_ptr<RtcEventLogOutput> output,
4720 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004721 if (!event_log_) {
4722 return false;
4723 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004724 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004725}
4726
4727void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004728 if (event_log_) {
4729 event_log_->StopLogging();
4730 }
ivoc14d5dbe2016-07-04 07:06:55 -07004731}
nisseeaabdf62017-05-05 02:23:02 -07004732
Steve Anton75737c02017-11-06 10:37:17 -08004733cricket::BaseChannel* PeerConnection::GetChannel(
4734 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004735 for (auto transceiver : transceivers_) {
4736 cricket::BaseChannel* channel = transceiver->internal()->channel();
4737 if (channel && channel->content_name() == content_name) {
4738 return channel;
4739 }
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
4741 if (rtp_data_channel() &&
4742 rtp_data_channel()->content_name() == content_name) {
4743 return rtp_data_channel();
4744 }
4745 return nullptr;
4746}
4747
4748bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4749 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004750 RTC_LOG(LS_INFO)
4751 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004752 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004753 return false;
4754 }
4755 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004756 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004757 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004758 return false;
4759 }
4760
Zhi Huange830e682018-03-30 10:48:35 -07004761 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4762 if (dtls_role) {
4763 *role = *dtls_role;
4764 return true;
4765 }
4766 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004767}
4768
4769bool PeerConnection::GetSslRole(const std::string& content_name,
4770 rtc::SSLRole* role) {
4771 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004772 RTC_LOG(LS_INFO)
4773 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004774 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004775 return false;
4776 }
4777
Zhi Huange830e682018-03-30 10:48:35 -07004778 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4779 if (dtls_role) {
4780 *role = *dtls_role;
4781 return true;
4782 }
4783 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004784}
4785
Steve Antonf8470812017-12-04 10:46:21 -08004786void PeerConnection::SetSessionError(SessionError error,
4787 const std::string& error_desc) {
4788 RTC_DCHECK_RUN_ON(signaling_thread());
4789 if (error != session_error_) {
4790 session_error_ = error;
4791 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004792 }
4793}
4794
Zhi Huange830e682018-03-30 10:48:35 -07004795RTCError PeerConnection::UpdateSessionState(
4796 SdpType type,
4797 cricket::ContentSource source,
4798 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004799 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004800
4801 // If there's already a pending error then no state transition should happen.
4802 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004803 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004804
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004805 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004806 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004807 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004808 }
4809
4810 // Update the signaling state according to the specified state machine (see
4811 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004812 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004813 ChangeSignalingState(source == cricket::CS_LOCAL
4814 ? PeerConnectionInterface::kHaveLocalOffer
4815 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004816 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004817 ChangeSignalingState(source == cricket::CS_LOCAL
4818 ? PeerConnectionInterface::kHaveLocalPrAnswer
4819 : PeerConnectionInterface::kHaveRemotePrAnswer);
4820 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004821 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004822 ChangeSignalingState(PeerConnectionInterface::kStable);
4823 }
4824
4825 // Update internal objects according to the session description's media
4826 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004827 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004828 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004829 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004830 }
4831
Steve Anton8a006912017-12-04 15:25:56 -08004832 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004833}
4834
Steve Anton8a006912017-12-04 15:25:56 -08004835RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004836 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004837 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004838 const SessionDescriptionInterface* sdesc =
4839 (source == cricket::CS_LOCAL ? local_description()
4840 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004841 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004842
4843 // Push down the new SDP media section for each audio/video transceiver.
4844 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004845 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004846 FindMediaSectionForTransceiver(transceiver, sdesc);
4847 cricket::BaseChannel* channel = transceiver->internal()->channel();
4848 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004849 continue;
4850 }
4851 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004852 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004853 if (!content_desc) {
4854 continue;
4855 }
4856 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004857 bool success = (source == cricket::CS_LOCAL)
4858 ? channel->SetLocalContent(content_desc, type, &error)
4859 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004860 if (!success) {
4861 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4862 }
4863 }
4864
4865 // If using the RtpDataChannel, push down the new SDP section for it too.
4866 if (rtp_data_channel_) {
4867 const ContentInfo* data_content =
4868 cricket::GetFirstDataContent(sdesc->description());
4869 if (data_content && !data_content->rejected) {
4870 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004871 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004872 if (data_desc) {
4873 std::string error;
4874 bool success =
4875 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004876 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004877 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004878 if (!success) {
4879 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4880 std::move(error));
4881 }
Steve Anton75737c02017-11-06 10:37:17 -08004882 }
4883 }
4884 }
Steve Antoned10bd92017-12-05 10:52:59 -08004885
Steve Anton75737c02017-11-06 10:37:17 -08004886 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4887 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4888 if (sctp_transport_ && local_description() && remote_description() &&
4889 cricket::GetFirstDataContent(local_description()->description()) &&
4890 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004891 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004892 RTC_FROM_HERE,
4893 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004894 if (!success) {
4895 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4896 "Failed to push down SCTP parameters.");
4897 }
Steve Anton75737c02017-11-06 10:37:17 -08004898 }
Steve Antoned10bd92017-12-05 10:52:59 -08004899
Steve Anton8a006912017-12-04 15:25:56 -08004900 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004901}
4902
4903bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4904 RTC_DCHECK(network_thread()->IsCurrent());
4905 RTC_DCHECK(local_description());
4906 RTC_DCHECK(remote_description());
4907 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4908 // When we support "max-message-size", that would also be pushed down here.
4909 return sctp_transport_->Start(
4910 GetSctpPort(local_description()->description()),
4911 GetSctpPort(remote_description()->description()));
4912}
4913
Steve Anton8a006912017-12-04 15:25:56 -08004914RTCError PeerConnection::PushdownTransportDescription(
4915 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004916 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004917 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004918
Zhi Huange830e682018-03-30 10:48:35 -07004919 if (source == cricket::CS_LOCAL) {
4920 const SessionDescriptionInterface* sdesc = local_description();
4921 RTC_DCHECK(sdesc);
4922 return transport_controller_->SetLocalDescription(type,
4923 sdesc->description());
4924 } else {
4925 const SessionDescriptionInterface* sdesc = remote_description();
4926 RTC_DCHECK(sdesc);
4927 return transport_controller_->SetRemoteDescription(type,
4928 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004929 }
Steve Anton75737c02017-11-06 10:37:17 -08004930}
4931
4932bool PeerConnection::GetTransportDescription(
4933 const SessionDescription* description,
4934 const std::string& content_name,
4935 cricket::TransportDescription* tdesc) {
4936 if (!description || !tdesc) {
4937 return false;
4938 }
4939 const TransportInfo* transport_info =
4940 description->GetTransportInfoByName(content_name);
4941 if (!transport_info) {
4942 return false;
4943 }
4944 *tdesc = transport_info->description;
4945 return true;
4946}
4947
Steve Anton75737c02017-11-06 10:37:17 -08004948cricket::IceConfig PeerConnection::ParseIceConfig(
4949 const PeerConnectionInterface::RTCConfiguration& config) const {
4950 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004951 switch (config.continual_gathering_policy) {
4952 case PeerConnectionInterface::GATHER_ONCE:
4953 gathering_policy = cricket::GATHER_ONCE;
4954 break;
4955 case PeerConnectionInterface::GATHER_CONTINUALLY:
4956 gathering_policy = cricket::GATHER_CONTINUALLY;
4957 break;
4958 default:
4959 RTC_NOTREACHED();
4960 gathering_policy = cricket::GATHER_ONCE;
4961 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004962
Steve Anton75737c02017-11-06 10:37:17 -08004963 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004964 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4965 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004966 ice_config.prioritize_most_likely_candidate_pairs =
4967 config.prioritize_most_likely_ice_candidate_pairs;
4968 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004969 RTCConfigurationToIceConfigOptionalInt(
4970 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004971 ice_config.continual_gathering_policy = gathering_policy;
4972 ice_config.presume_writable_when_fully_relayed =
4973 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004974 ice_config.ice_check_interval_strong_connectivity =
4975 config.ice_check_interval_strong_connectivity;
4976 ice_config.ice_check_interval_weak_connectivity =
4977 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004978 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004979 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004980 ice_config.regather_all_networks_interval_range =
4981 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004982 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004983 return ice_config;
4984}
4985
Steve Anton75737c02017-11-06 10:37:17 -08004986bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4987 std::string* track_id) {
4988 if (!local_description()) {
4989 return false;
4990 }
4991 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4992 track_id);
4993}
4994
4995bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4996 std::string* track_id) {
4997 if (!remote_description()) {
4998 return false;
4999 }
5000 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5001 track_id);
5002}
5003
5004bool PeerConnection::SendData(const cricket::SendDataParams& params,
5005 const rtc::CopyOnWriteBuffer& payload,
5006 cricket::SendDataResult* result) {
5007 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005008 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005009 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005010 return false;
5011 }
5012 return rtp_data_channel_
5013 ? rtp_data_channel_->SendData(params, payload, result)
5014 : network_thread()->Invoke<bool>(
5015 RTC_FROM_HERE,
5016 Bind(&cricket::SctpTransportInternal::SendData,
5017 sctp_transport_.get(), params, payload, result));
5018}
5019
5020bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5021 if (!rtp_data_channel_ && !sctp_transport_) {
5022 // Don't log an error here, because DataChannels are expected to call
5023 // ConnectDataChannel in this state. It's the only way to initially tell
5024 // whether or not the underlying transport is ready.
5025 return false;
5026 }
5027 if (rtp_data_channel_) {
5028 rtp_data_channel_->SignalReadyToSendData.connect(
5029 webrtc_data_channel, &DataChannel::OnChannelReady);
5030 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5031 &DataChannel::OnDataReceived);
5032 } else {
5033 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5034 &DataChannel::OnChannelReady);
5035 SignalSctpDataReceived.connect(webrtc_data_channel,
5036 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005037 SignalSctpClosingProcedureStartedRemotely.connect(
5038 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5039 SignalSctpClosingProcedureComplete.connect(
5040 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005041 }
5042 return true;
5043}
5044
5045void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5046 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005047 RTC_LOG(LS_ERROR)
5048 << "DisconnectDataChannel called when rtp_data_channel_ and "
5049 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005050 return;
5051 }
5052 if (rtp_data_channel_) {
5053 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5054 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5055 } else {
5056 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5057 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005058 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5059 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005060 }
5061}
5062
5063void PeerConnection::AddSctpDataStream(int sid) {
5064 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005065 RTC_LOG(LS_ERROR)
5066 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005067 return;
5068 }
5069 network_thread()->Invoke<void>(
5070 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5071 sctp_transport_.get(), sid));
5072}
5073
5074void PeerConnection::RemoveSctpDataStream(int sid) {
5075 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005076 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005077 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005078 return;
5079 }
5080 network_thread()->Invoke<void>(
5081 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5082 sctp_transport_.get(), sid));
5083}
5084
5085bool PeerConnection::ReadyToSendData() const {
5086 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5087 sctp_ready_to_send_data_;
5088}
5089
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005090absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005091 if (sctp_mid_ && transport_controller_) {
5092 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5093 if (dtls_transport) {
5094 return dtls_transport->transport_name();
5095 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005096 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005097 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005098 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005099}
5100
Qingsi Wang72a43a12018-02-20 16:03:18 -08005101cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5102 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005103 network_thread()->Invoke<void>(
5104 RTC_FROM_HERE,
5105 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5106 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005107 return candidate_states_list;
5108}
5109
Steve Anton5dfde182018-02-06 10:34:40 -08005110std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5111 const {
5112 std::map<std::string, std::string> transport_names_by_mid;
5113 for (auto transceiver : transceivers_) {
5114 cricket::BaseChannel* channel = transceiver->internal()->channel();
5115 if (channel) {
5116 transport_names_by_mid[channel->content_name()] =
5117 channel->transport_name();
5118 }
Steve Anton75737c02017-11-06 10:37:17 -08005119 }
Steve Anton5dfde182018-02-06 10:34:40 -08005120 if (rtp_data_channel_) {
5121 transport_names_by_mid[rtp_data_channel_->content_name()] =
5122 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005123 }
5124 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005125 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005126 RTC_DCHECK(transport_name);
5127 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005128 }
Steve Anton5dfde182018-02-06 10:34:40 -08005129 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005130}
5131
Steve Anton5dfde182018-02-06 10:34:40 -08005132std::map<std::string, cricket::TransportStats>
5133PeerConnection::GetTransportStatsByNames(
5134 const std::set<std::string>& transport_names) {
5135 if (!network_thread()->IsCurrent()) {
5136 return network_thread()
5137 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5138 RTC_FROM_HERE,
5139 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
Steve Anton5dfde182018-02-06 10:34:40 -08005141 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5142 for (const std::string& transport_name : transport_names) {
5143 cricket::TransportStats transport_stats;
5144 bool success =
5145 transport_controller_->GetStats(transport_name, &transport_stats);
5146 if (success) {
5147 transport_stats_by_name[transport_name] = std::move(transport_stats);
5148 } else {
5149 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5150 << transport_name;
5151 }
5152 }
5153 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005154}
5155
5156bool PeerConnection::GetLocalCertificate(
5157 const std::string& transport_name,
5158 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005159 if (!certificate) {
5160 return false;
5161 }
5162 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5163 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005164}
5165
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005166std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005167 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005168 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005169}
5170
5171cricket::DataChannelType PeerConnection::data_channel_type() const {
5172 return data_channel_type_;
5173}
5174
5175bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5176 return pending_ice_restarts_.find(content_name) !=
5177 pending_ice_restarts_.end();
5178}
5179
Steve Anton75737c02017-11-06 10:37:17 -08005180bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5181 return transport_controller_->NeedsIceRestart(content_name);
5182}
5183
5184void PeerConnection::OnCertificateReady(
5185 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5186 transport_controller_->SetLocalCertificate(certificate);
5187}
5188
5189void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005190 SetSessionError(SessionError::kTransport,
5191 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005192}
5193
5194void PeerConnection::OnTransportControllerConnectionState(
5195 cricket::IceConnectionState state) {
5196 switch (state) {
5197 case cricket::kIceConnectionConnecting:
5198 // If the current state is Connected or Completed, then there were
5199 // writable channels but now there are not, so the next state must
5200 // be Disconnected.
5201 // kIceConnectionConnecting is currently used as the default,
5202 // un-connected state by the TransportController, so its only use is
5203 // detecting disconnections.
5204 if (ice_connection_state_ ==
5205 PeerConnectionInterface::kIceConnectionConnected ||
5206 ice_connection_state_ ==
5207 PeerConnectionInterface::kIceConnectionCompleted) {
5208 SetIceConnectionState(
5209 PeerConnectionInterface::kIceConnectionDisconnected);
5210 }
5211 break;
5212 case cricket::kIceConnectionFailed:
5213 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5214 break;
5215 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005216 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005217 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005218 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005219 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005220 break;
5221 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005222 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005223 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005224 if (ice_connection_state_ !=
5225 PeerConnectionInterface::kIceConnectionConnected) {
5226 // If jumping directly from "checking" to "connected",
5227 // signal "connected" first.
5228 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5229 }
5230 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005231 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005232 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005233 break;
5234 default:
5235 RTC_NOTREACHED();
5236 }
5237}
5238
5239void PeerConnection::OnTransportControllerCandidatesGathered(
5240 const std::string& transport_name,
5241 const cricket::Candidates& candidates) {
5242 RTC_DCHECK(signaling_thread()->IsCurrent());
5243 int sdp_mline_index;
5244 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005245 RTC_LOG(LS_ERROR)
5246 << "OnTransportControllerCandidatesGathered: content name "
5247 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005248 return;
5249 }
5250
5251 for (cricket::Candidates::const_iterator citer = candidates.begin();
5252 citer != candidates.end(); ++citer) {
5253 // Use transport_name as the candidate media id.
5254 std::unique_ptr<JsepIceCandidate> candidate(
5255 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5256 if (local_description()) {
5257 mutable_local_description()->AddCandidate(candidate.get());
5258 }
5259 OnIceCandidate(std::move(candidate));
5260 }
5261}
5262
5263void PeerConnection::OnTransportControllerCandidatesRemoved(
5264 const std::vector<cricket::Candidate>& candidates) {
5265 RTC_DCHECK(signaling_thread()->IsCurrent());
5266 // Sanity check.
5267 for (const cricket::Candidate& candidate : candidates) {
5268 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005269 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005270 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005271 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005272 return;
5273 }
5274 }
5275
5276 if (local_description()) {
5277 mutable_local_description()->RemoveCandidates(candidates);
5278 }
5279 OnIceCandidatesRemoved(candidates);
5280}
5281
5282void PeerConnection::OnTransportControllerDtlsHandshakeError(
5283 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005284 RTC_HISTOGRAM_ENUMERATION(
5285 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5286 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005287}
5288
Steve Antoned10bd92017-12-05 10:52:59 -08005289void PeerConnection::EnableSending() {
5290 for (auto transceiver : transceivers_) {
5291 cricket::BaseChannel* channel = transceiver->internal()->channel();
5292 if (channel && !channel->enabled()) {
5293 channel->Enable(true);
5294 }
Steve Anton75737c02017-11-06 10:37:17 -08005295 }
5296
Steve Anton4171afb2017-11-20 10:20:22 -08005297 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005298 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005299 }
Steve Anton75737c02017-11-06 10:37:17 -08005300}
5301
5302// Returns the media index for a local ice candidate given the content name.
5303bool PeerConnection::GetLocalCandidateMediaIndex(
5304 const std::string& content_name,
5305 int* sdp_mline_index) {
5306 if (!local_description() || !sdp_mline_index) {
5307 return false;
5308 }
5309
5310 bool content_found = false;
5311 const ContentInfos& contents = local_description()->description()->contents();
5312 for (size_t index = 0; index < contents.size(); ++index) {
5313 if (contents[index].name == content_name) {
5314 *sdp_mline_index = static_cast<int>(index);
5315 content_found = true;
5316 break;
5317 }
5318 }
5319 return content_found;
5320}
5321
5322bool PeerConnection::UseCandidatesInSessionDescription(
5323 const SessionDescriptionInterface* remote_desc) {
5324 if (!remote_desc) {
5325 return true;
5326 }
5327 bool ret = true;
5328
5329 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5330 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5331 for (size_t n = 0; n < candidates->count(); ++n) {
5332 const IceCandidateInterface* candidate = candidates->at(n);
5333 bool valid = false;
5334 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5335 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005336 RTC_LOG(LS_INFO)
5337 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005338 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005339 }
5340 continue;
5341 }
5342 ret = UseCandidate(candidate);
5343 if (!ret) {
5344 break;
5345 }
5346 }
5347 }
5348 return ret;
5349}
5350
5351bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5352 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5353 size_t remote_content_size =
5354 remote_description()->description()->contents().size();
5355 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005356 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005357 return false;
5358 }
5359
5360 cricket::ContentInfo content =
5361 remote_description()->description()->contents()[mediacontent_index];
5362 std::vector<cricket::Candidate> candidates;
5363 candidates.push_back(candidate->candidate());
5364 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005365 RTCError error =
5366 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005367 if (error.ok()) {
5368 // Candidates successfully submitted for checking.
5369 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5370 ice_connection_state_ ==
5371 PeerConnectionInterface::kIceConnectionDisconnected) {
5372 // If state is New, then the session has just gotten its first remote ICE
5373 // candidates, so go to Checking.
5374 // If state is Disconnected, the session is re-using old candidates or
5375 // receiving additional ones, so go to Checking.
5376 // If state is Connected, stay Connected.
5377 // TODO(bemasc): If state is Connected, and the new candidates are for a
5378 // newly added transport, then the state actually _should_ move to
5379 // checking. Add a way to distinguish that case.
5380 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5381 }
5382 // TODO(bemasc): If state is Completed, go back to Connected.
5383 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005384 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005385 }
5386 return true;
5387}
5388
5389void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005390 // Destroy video channel first since it may have a pointer to the
5391 // voice channel.
5392 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005393 if (!video_info || video_info->rejected) {
5394 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005395 }
5396
Steve Anton6fec8802017-12-04 10:37:29 -08005397 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5398 if (!audio_info || audio_info->rejected) {
5399 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005400 }
5401
5402 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5403 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005404 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005405 }
5406}
5407
Steve Antondcc3c022017-12-22 16:02:54 -08005408RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5409 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005410 const cricket::ContentGroup* bundle_group = nullptr;
5411 if (configuration_.bundle_policy ==
5412 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005413 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005414 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5416 "max-bundle configured but session description "
5417 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005418 }
5419 }
Steve Antondcc3c022017-12-22 16:02:54 -08005420 return std::move(bundle_group);
5421}
5422
5423RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005424 // Creating the media channels. Transports should already have been created
5425 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005426 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005427 if (voice && !voice->rejected &&
5428 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005429 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005430 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5432 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005433 }
5434 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5435 }
5436
Steve Antondcc3c022017-12-22 16:02:54 -08005437 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005438 if (video && !video->rejected &&
5439 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005440 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005441 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005442 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5443 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005445 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005446 }
5447
Steve Antondcc3c022017-12-22 16:02:54 -08005448 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005449 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5450 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005451 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005452 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5453 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005454 }
5455 }
5456
Steve Anton8a006912017-12-04 15:25:56 -08005457 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005458}
5459
Steve Anton4171afb2017-11-20 10:20:22 -08005460// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005461cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005462 const std::string& mid) {
5463 RtpTransportInternal* rtp_transport =
5464 transport_controller_->GetRtpTransport(mid);
5465 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005466 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005467 call_.get(), configuration_.media_config, rtp_transport,
5468 signaling_thread(), mid, SrtpRequired(),
5469 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005470 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005471 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005472 }
Steve Anton75737c02017-11-06 10:37:17 -08005473 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5474 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005475 voice_channel->SignalSentPacket.connect(this,
5476 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005477 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005478
Steve Antoneda6ccd2017-12-04 10:21:55 -08005479 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005480}
5481
Steve Anton4171afb2017-11-20 10:20:22 -08005482// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005483cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005484 const std::string& mid) {
5485 RtpTransportInternal* rtp_transport =
5486 transport_controller_->GetRtpTransport(mid);
5487 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005488 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005489 call_.get(), configuration_.media_config, rtp_transport,
5490 signaling_thread(), mid, SrtpRequired(),
5491 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005492 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005493 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005494 }
Steve Anton75737c02017-11-06 10:37:17 -08005495 video_channel->SignalDtlsSrtpSetupFailure.connect(
5496 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005497 video_channel->SignalSentPacket.connect(this,
5498 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005499 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005500
Steve Antoneda6ccd2017-12-04 10:21:55 -08005501 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005502}
5503
Zhi Huange830e682018-03-30 10:48:35 -07005504bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005505 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5506 if (sctp) {
5507 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005508 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005509 << "Trying to create SCTP transport, but didn't compile with "
5510 "SCTP support (HAVE_SCTP)";
5511 return false;
5512 }
5513 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005514 RTC_FROM_HERE,
5515 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005516 return false;
5517 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005518 for (const auto& channel : sctp_data_channels_) {
5519 channel->OnTransportChannelCreated();
5520 }
Steve Anton75737c02017-11-06 10:37:17 -08005521 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005522 RtpTransportInternal* rtp_transport =
5523 transport_controller_->GetRtpTransport(mid);
5524 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005525 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005526 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5527 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005528 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005529 return false;
5530 }
Steve Anton75737c02017-11-06 10:37:17 -08005531 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5532 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5533 rtp_data_channel_->SignalSentPacket.connect(
5534 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005535 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005536 }
5537
Steve Anton75737c02017-11-06 10:37:17 -08005538 return true;
5539}
5540
5541Call::Stats PeerConnection::GetCallStats() {
5542 if (!worker_thread()->IsCurrent()) {
5543 return worker_thread()->Invoke<Call::Stats>(
5544 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5545 }
5546 if (call_) {
5547 return call_->GetStats();
5548 } else {
5549 return Call::Stats();
5550 }
5551}
5552
Zhi Huange830e682018-03-30 10:48:35 -07005553bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005554 RTC_DCHECK(network_thread()->IsCurrent());
5555 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005556 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005557 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005558 RTC_DCHECK(dtls_transport);
5559 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005560 RTC_DCHECK(sctp_transport_);
5561 sctp_invoker_.reset(new rtc::AsyncInvoker());
5562 sctp_transport_->SignalReadyToSendData.connect(
5563 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5564 sctp_transport_->SignalDataReceived.connect(
5565 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005566 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5567 // another thread. Would be nice if there was a helper class similar to
5568 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5569 // code.
5570 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5571 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5572 sctp_transport_->SignalClosingProcedureComplete.connect(
5573 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005574 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005575 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005576 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005577}
5578
5579void PeerConnection::DestroySctpTransport_n() {
5580 RTC_DCHECK(network_thread()->IsCurrent());
5581 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005582 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005583 sctp_invoker_.reset(nullptr);
5584 sctp_ready_to_send_data_ = false;
5585}
5586
5587void PeerConnection::OnSctpTransportReadyToSendData_n() {
5588 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5589 RTC_DCHECK(network_thread()->IsCurrent());
5590 // Note: Cannot use rtc::Bind here because it will grab a reference to
5591 // PeerConnection and potentially cause PeerConnection to live longer than
5592 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5593 // be destroyed before PeerConnection is destroyed, and at that point all
5594 // pending tasks will be cleared.
5595 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5596 OnSctpTransportReadyToSendData_s(true);
5597 });
5598}
5599
5600void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5601 RTC_DCHECK(signaling_thread()->IsCurrent());
5602 sctp_ready_to_send_data_ = ready;
5603 SignalSctpReadyToSendData(ready);
5604}
5605
5606void PeerConnection::OnSctpTransportDataReceived_n(
5607 const cricket::ReceiveDataParams& params,
5608 const rtc::CopyOnWriteBuffer& payload) {
5609 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5610 RTC_DCHECK(network_thread()->IsCurrent());
5611 // Note: Cannot use rtc::Bind here because it will grab a reference to
5612 // PeerConnection and potentially cause PeerConnection to live longer than
5613 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5614 // be destroyed before PeerConnection is destroyed, and at that point all
5615 // pending tasks will be cleared.
5616 sctp_invoker_->AsyncInvoke<void>(
5617 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5618 OnSctpTransportDataReceived_s(params, payload);
5619 });
5620}
5621
5622void PeerConnection::OnSctpTransportDataReceived_s(
5623 const cricket::ReceiveDataParams& params,
5624 const rtc::CopyOnWriteBuffer& payload) {
5625 RTC_DCHECK(signaling_thread()->IsCurrent());
5626 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5627 // Received OPEN message; parse and signal that a new data channel should
5628 // be created.
5629 std::string label;
5630 InternalDataChannelInit config;
5631 config.id = params.ssrc;
5632 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005633 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5634 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005635 return;
5636 }
5637 config.open_handshake_role = InternalDataChannelInit::kAcker;
5638 OnDataChannelOpenMessage(label, config);
5639 } else {
5640 // Otherwise just forward the signal.
5641 SignalSctpDataReceived(params, payload);
5642 }
5643}
5644
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005645void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005646 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5647 RTC_DCHECK(network_thread()->IsCurrent());
5648 sctp_invoker_->AsyncInvoke<void>(
5649 RTC_FROM_HERE, signaling_thread(),
5650 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005651 &SignalSctpClosingProcedureStartedRemotely, sid));
5652}
5653
5654void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5655 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5656 RTC_DCHECK(network_thread()->IsCurrent());
5657 sctp_invoker_->AsyncInvoke<void>(
5658 RTC_FROM_HERE, signaling_thread(),
5659 rtc::Bind(&sigslot::signal1<int>::operator(),
5660 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005661}
5662
5663// Returns false if bundle is enabled and rtcp_mux is disabled.
5664bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5665 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5666 if (!bundle_enabled)
5667 return true;
5668
5669 const cricket::ContentGroup* bundle_group =
5670 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5671 RTC_DCHECK(bundle_group != NULL);
5672
5673 const cricket::ContentInfos& contents = desc->contents();
5674 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5675 citer != contents.end(); ++citer) {
5676 const cricket::ContentInfo* content = (&*citer);
5677 RTC_DCHECK(content != NULL);
5678 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005679 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005680 if (!HasRtcpMuxEnabled(content))
5681 return false;
5682 }
5683 }
5684 // RTCP-MUX is enabled in all the contents.
5685 return true;
5686}
5687
5688bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005689 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005690}
5691
Steve Anton8a006912017-12-04 15:25:56 -08005692RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005693 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005694 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005695 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005696 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005697 }
5698
5699 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702
Steve Anton3828c062017-12-06 10:34:51 -08005703 SdpType type = sdesc->GetType();
5704 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5705 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005706 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005707 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005708 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005709 }
5710
5711 // Verify crypto settings.
5712 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005713 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5714 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005715 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005716 if (!crypto_error.ok()) {
5717 return crypto_error;
5718 }
Steve Anton75737c02017-11-06 10:37:17 -08005719 }
5720
5721 // Verify ice-ufrag and ice-pwd.
5722 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005723 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5724 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005725 }
5726
5727 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005728 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5729 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005730 }
5731
5732 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5733 // m-lines that do not rtcp-mux enabled.
5734
5735 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005736 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005737 // With an answer we want to compare the new answer session description with
5738 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005739 const cricket::SessionDescription* offer_desc =
5740 (source == cricket::CS_LOCAL) ? remote_description()->description()
5741 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005742 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5743 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5744 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5746 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005747 }
5748 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005749 // The re-offers should respect the order of m= sections in current
5750 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005751 // With a re-offer, either the current local or current remote descriptions
5752 // could be the most up to date, so we would like to check against both of
5753 // them if they exist. It could be the case that one of them has a 0 port
5754 // for a media section, but the other does not. This is important to check
5755 // against in the case that we are recycling an m= section.
5756 const cricket::SessionDescription* current_desc = nullptr;
5757 const cricket::SessionDescription* secondary_current_desc = nullptr;
5758 if (local_description()) {
5759 current_desc = local_description()->description();
5760 if (remote_description()) {
5761 secondary_current_desc = remote_description()->description();
5762 }
5763 } else if (remote_description()) {
5764 current_desc = remote_description()->description();
5765 }
Steve Anton75737c02017-11-06 10:37:17 -08005766 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005767 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5768 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005769 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5770 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005771 }
5772 }
5773
Steve Antonba42e992018-04-09 14:10:01 -07005774 if (IsUnifiedPlan()) {
5775 // Ensure that each audio and video media section has at most one
5776 // "StreamParams". This will return an error if receiving a session
5777 // description from a "Plan B" endpoint which adds multiple tracks of the
5778 // same type. With Unified Plan, there can only be at most one track per
5779 // media section.
5780 for (const ContentInfo& content : sdesc->description()->contents()) {
5781 const MediaContentDescription& desc = *content.description;
5782 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5783 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5784 desc.streams().size() > 1u) {
5785 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5786 "Media section has more than one track specified "
5787 "with a=ssrc lines which is not supported with "
5788 "Unified Plan.");
5789 }
5790 }
5791 }
5792
Steve Anton8a006912017-12-04 15:25:56 -08005793 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005794}
5795
Steve Anton3828c062017-12-06 10:34:51 -08005796bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005797 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005798 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005799 return (state == PeerConnectionInterface::kStable) ||
5800 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005801 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005802 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005803 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5804 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5805 }
5806}
5807
Steve Anton3828c062017-12-06 10:34:51 -08005808bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005809 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005810 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005811 return (state == PeerConnectionInterface::kStable) ||
5812 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005813 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005814 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005815 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5816 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5817 }
5818}
5819
Steve Antonf8470812017-12-04 10:46:21 -08005820const char* PeerConnection::SessionErrorToString(SessionError error) const {
5821 switch (error) {
5822 case SessionError::kNone:
5823 return "ERROR_NONE";
5824 case SessionError::kContent:
5825 return "ERROR_CONTENT";
5826 case SessionError::kTransport:
5827 return "ERROR_TRANSPORT";
5828 }
5829 RTC_NOTREACHED();
5830 return "";
5831}
5832
Steve Anton75737c02017-11-06 10:37:17 -08005833std::string PeerConnection::GetSessionErrorMsg() {
5834 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005835 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5836 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005837 return desc.str();
5838}
5839
Steve Anton8e20f172018-03-06 10:55:04 -08005840void PeerConnection::ReportSdpFormatReceived(
5841 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005842 int num_audio_mlines = 0;
5843 int num_video_mlines = 0;
5844 int num_audio_tracks = 0;
5845 int num_video_tracks = 0;
5846 for (const ContentInfo& content : remote_offer.description()->contents()) {
5847 cricket::MediaType media_type = content.media_description()->type();
5848 int num_tracks = std::max(
5849 1, static_cast<int>(content.media_description()->streams().size()));
5850 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5851 num_audio_mlines += 1;
5852 num_audio_tracks += num_tracks;
5853 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5854 num_video_mlines += 1;
5855 num_video_tracks += num_tracks;
5856 }
5857 }
5858 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5859 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5860 format = kSdpFormatReceivedComplexUnifiedPlan;
5861 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5862 format = kSdpFormatReceivedComplexPlanB;
5863 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5864 format = kSdpFormatReceivedSimple;
5865 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005866 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5867 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005868}
5869
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005870void PeerConnection::NoteUsageEvent(UsageEvent event) {
5871 RTC_DCHECK_RUN_ON(signaling_thread());
5872 usage_event_accumulator_ |= static_cast<int>(event);
5873}
5874
5875void PeerConnection::ReportUsagePattern() const {
5876 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005877 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5878 usage_event_accumulator_,
5879 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005880 const int bad_bits =
5881 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5882 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5883 const int good_bits =
5884 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5885 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5886 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5887 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5888 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005889 // If called after close(), we can't report, because observer may have
5890 // been deallocated, and therefore pointer is null. Write to log instead.
5891 if (observer_) {
5892 Observer()->OnInterestingUsage(usage_event_accumulator_);
5893 } else {
5894 RTC_LOG(LS_INFO) << "Interesting usage signature "
5895 << usage_event_accumulator_
5896 << " observed after observer shutdown";
5897 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005898 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005899}
5900
Steve Anton0ffaaa22018-02-23 10:31:30 -08005901void PeerConnection::ReportNegotiatedSdpSemantics(
5902 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005903 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005904 switch (answer.description()->msid_signaling()) {
5905 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005906 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005907 break;
5908 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005909 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005910 break;
5911 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005912 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005913 break;
5914 case cricket::kMsidSignalingMediaSection |
5915 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005916 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005917 break;
5918 default:
5919 RTC_NOTREACHED();
5920 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005921 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5922 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005923}
5924
Steve Anton75737c02017-11-06 10:37:17 -08005925// We need to check the local/remote description for the Transport instead of
5926// the session, because a new Transport added during renegotiation may have
5927// them unset while the session has them set from the previous negotiation.
5928// Not doing so may trigger the auto generation of transport description and
5929// mess up DTLS identity information, ICE credential, etc.
5930bool PeerConnection::ReadyToUseRemoteCandidate(
5931 const IceCandidateInterface* candidate,
5932 const SessionDescriptionInterface* remote_desc,
5933 bool* valid) {
5934 *valid = true;
5935
5936 const SessionDescriptionInterface* current_remote_desc =
5937 remote_desc ? remote_desc : remote_description();
5938
5939 if (!current_remote_desc) {
5940 return false;
5941 }
5942
5943 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5944 size_t remote_content_size =
5945 current_remote_desc->description()->contents().size();
5946 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005947 RTC_LOG(LS_ERROR)
5948 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5949 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005950
5951 *valid = false;
5952 return false;
5953 }
5954
5955 cricket::ContentInfo content =
5956 current_remote_desc->description()->contents()[mediacontent_index];
5957
5958 const std::string transport_name = GetTransportName(content.name);
5959 if (transport_name.empty()) {
5960 return false;
5961 }
Zhi Huange830e682018-03-30 10:48:35 -07005962 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005963}
5964
5965bool PeerConnection::SrtpRequired() const {
5966 return dtls_enabled_ ||
5967 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5968}
5969
5970void PeerConnection::OnTransportControllerGatheringState(
5971 cricket::IceGatheringState state) {
5972 RTC_DCHECK(signaling_thread()->IsCurrent());
5973 if (state == cricket::kIceGatheringGathering) {
5974 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5975 } else if (state == cricket::kIceGatheringComplete) {
5976 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5977 }
5978}
5979
5980void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005981 std::map<std::string, std::set<cricket::MediaType>>
5982 media_types_by_transport_name;
5983 for (auto transceiver : transceivers_) {
5984 if (transceiver->internal()->channel()) {
5985 const std::string& transport_name =
5986 transceiver->internal()->channel()->transport_name();
5987 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005988 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005989 }
Steve Anton75737c02017-11-06 10:37:17 -08005990 }
5991 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005992 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5993 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005994 }
Zhi Huange830e682018-03-30 10:48:35 -07005995
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005996 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005997 if (transport_name) {
5998 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005999 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006000 }
Zhi Huange830e682018-03-30 10:48:35 -07006001
Steve Antonc7b964c2018-02-01 14:39:45 -08006002 for (const auto& entry : media_types_by_transport_name) {
6003 const std::string& transport_name = entry.first;
6004 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006005 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006006 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006007 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006008 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006009 }
6010 }
6011}
6012// Walk through the ConnectionInfos to gather best connection usage
6013// for IPv4 and IPv6.
6014void PeerConnection::ReportBestConnectionState(
6015 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006016 for (const cricket::TransportChannelStats& channel_stats :
6017 stats.channel_stats) {
6018 for (const cricket::ConnectionInfo& connection_info :
6019 channel_stats.connection_infos) {
6020 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006021 continue;
6022 }
6023
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 const cricket::Candidate& local = connection_info.local_candidate;
6025 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006026
6027 // Increment the counter for IceCandidatePairType.
6028 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6029 (local.type() == RELAY_PORT_TYPE &&
6030 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006031 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6032 GetIceCandidatePairCounter(local, remote),
6033 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006034 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006035 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6036 GetIceCandidatePairCounter(local, remote),
6037 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006038 } else {
6039 RTC_CHECK(0);
6040 }
Steve Anton75737c02017-11-06 10:37:17 -08006041
6042 // Increment the counter for IP type.
6043 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006044 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6045 kBestConnections_IPv4,
6046 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006047 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006048 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6049 kBestConnections_IPv6,
6050 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006051 } else {
6052 RTC_CHECK(0);
6053 }
6054
6055 return;
6056 }
6057 }
6058}
6059
6060void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 const cricket::TransportStats& stats,
6062 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006063 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6064 return;
6065 }
6066
6067 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6068 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6069 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6070 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6071 return;
6072 }
6073
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006074 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6075 for (cricket::MediaType media_type : media_types) {
6076 switch (media_type) {
6077 case cricket::MEDIA_TYPE_AUDIO:
6078 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6079 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6080 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6081 break;
6082 case cricket::MEDIA_TYPE_VIDEO:
6083 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6084 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6085 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6086 break;
6087 case cricket::MEDIA_TYPE_DATA:
6088 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6089 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6090 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6091 break;
6092 default:
6093 RTC_NOTREACHED();
6094 continue;
6095 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006096 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006097 }
6098
6099 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6100 for (cricket::MediaType media_type : media_types) {
6101 switch (media_type) {
6102 case cricket::MEDIA_TYPE_AUDIO:
6103 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6104 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6105 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6106 break;
6107 case cricket::MEDIA_TYPE_VIDEO:
6108 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6109 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6110 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6111 break;
6112 case cricket::MEDIA_TYPE_DATA:
6113 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6114 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6115 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6116 break;
6117 default:
6118 RTC_NOTREACHED();
6119 continue;
6120 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006121 }
Steve Anton75737c02017-11-06 10:37:17 -08006122 }
6123}
6124
6125void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6126 RTC_DCHECK(worker_thread()->IsCurrent());
6127 RTC_DCHECK(call_);
6128 call_->OnSentPacket(sent_packet);
6129}
6130
6131const std::string PeerConnection::GetTransportName(
6132 const std::string& content_name) {
6133 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006134 if (channel) {
6135 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006136 }
Steve Anton6fec8802017-12-04 10:37:29 -08006137 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006138 RTC_DCHECK(sctp_mid_);
6139 if (content_name == *sctp_mid_) {
6140 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006141 }
6142 }
6143 // Return an empty string if failed to retrieve the transport name.
6144 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006145}
6146
Steve Anton6fec8802017-12-04 10:37:29 -08006147void PeerConnection::DestroyTransceiverChannel(
6148 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6149 transceiver) {
6150 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006151
Steve Anton6fec8802017-12-04 10:37:29 -08006152 cricket::BaseChannel* channel = transceiver->internal()->channel();
6153 if (channel) {
6154 transceiver->internal()->SetChannel(nullptr);
6155 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006156 }
6157}
6158
6159void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006160 if (rtp_data_channel_) {
6161 OnDataChannelDestroyed();
6162 DestroyBaseChannel(rtp_data_channel_);
6163 rtp_data_channel_ = nullptr;
6164 }
6165
6166 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6167 // grab a reference to this PeerConnection. If this is called from the
6168 // PeerConnection destructor, the RefCountedObject vtable will have already
6169 // been destroyed (since it is a subclass of PeerConnection) and using
6170 // rtc::Bind will cause "Pure virtual function called" error to appear.
6171
6172 if (sctp_transport_) {
6173 OnDataChannelDestroyed();
6174 network_thread()->Invoke<void>(RTC_FROM_HERE,
6175 [this] { DestroySctpTransport_n(); });
6176 }
6177}
6178
6179void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6180 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006181 switch (channel->media_type()) {
6182 case cricket::MEDIA_TYPE_AUDIO:
6183 channel_manager()->DestroyVoiceChannel(
6184 static_cast<cricket::VoiceChannel*>(channel));
6185 break;
6186 case cricket::MEDIA_TYPE_VIDEO:
6187 channel_manager()->DestroyVideoChannel(
6188 static_cast<cricket::VideoChannel*>(channel));
6189 break;
6190 case cricket::MEDIA_TYPE_DATA:
6191 channel_manager()->DestroyRtpDataChannel(
6192 static_cast<cricket::RtpDataChannel*>(channel));
6193 break;
6194 default:
6195 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6196 break;
6197 }
Zhi Huange830e682018-03-30 10:48:35 -07006198}
Steve Anton6fec8802017-12-04 10:37:29 -08006199
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006200bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006201 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006202 RtpTransportInternal* rtp_transport,
6203 cricket::DtlsTransportInternal* dtls_transport) {
6204 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006205 auto base_channel = GetChannel(mid);
6206 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006207 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006208 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006209 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006210 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006211 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006212 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006213}
6214
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006215PeerConnectionObserver* PeerConnection::Observer() const {
6216 // In earlier production code, the pointer was not cleared on close,
6217 // which might have led to undefined behavior if the observer was not
6218 // deallocated, or strange crashes if it was.
6219 // We use CHECK in order to catch such behavior if it exists.
6220 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6221 RTC_CHECK(observer_);
6222 return observer_;
6223}
6224
Harald Alvestrand89061872018-01-02 14:08:34 +01006225void PeerConnection::ClearStatsCache() {
6226 if (stats_collector_) {
6227 stats_collector_->ClearCachedStatsReport();
6228 }
6229}
6230
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006231void PeerConnection::RequestUsagePatternReportForTesting() {
6232 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6233 nullptr);
6234}
6235
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006236} // namespace webrtc