blob: 7bc25706f0cd8adedc0ad1095c4a166e3f3fa475 [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,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200176 cricket::MediaDescriptionOptions* video_media_description_options,
177 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700178 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700179 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
180 if (audio_media_description_options) {
181 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700182 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700183 }
184 } else {
185 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
186 if (video_media_description_options) {
187 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200188 sender->id(), sender->internal()->stream_ids(),
189 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700190 }
191 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700192 }
zhihuang1c378ed2017-08-17 14:10:50 -0700193}
olka3c747662017-08-17 06:50:32 -0700194
zhihuang1c378ed2017-08-17 14:10:50 -0700195// Add options to |session_options| from |rtp_data_channels|.
196void AddRtpDataChannelOptions(
197 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
198 rtp_data_channels,
199 cricket::MediaDescriptionOptions* data_media_description_options) {
200 if (!data_media_description_options) {
201 return;
202 }
deadbeefab9b2d12015-10-14 11:33:11 -0700203 // Check for data channels.
204 for (const auto& kv : rtp_data_channels) {
205 const DataChannel* channel = kv.second;
206 if (channel->state() == DataChannel::kConnecting ||
207 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700208 // Legacy RTP data channels are signaled with the track/stream ID set to
209 // the data channel's label.
210 data_media_description_options->AddRtpDataChannel(channel->label(),
211 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700212 }
213 }
214}
215
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700216uint32_t ConvertIceTransportTypeToCandidateFilter(
217 PeerConnectionInterface::IceTransportsType type) {
218 switch (type) {
219 case PeerConnectionInterface::kNone:
220 return cricket::CF_NONE;
221 case PeerConnectionInterface::kRelay:
222 return cricket::CF_RELAY;
223 case PeerConnectionInterface::kNoHost:
224 return (cricket::CF_ALL & ~cricket::CF_HOST);
225 case PeerConnectionInterface::kAll:
226 return cricket::CF_ALL;
227 default:
nissec80e7412017-01-11 05:56:46 -0800228 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700229 }
230 return cricket::CF_NONE;
231}
232
deadbeef293e9262017-01-11 12:28:30 -0800233// Helper to set an error and return from a method.
234bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
235 if (error) {
236 error->set_type(type);
237 }
238 return type == webrtc::RTCErrorType::NONE;
239}
240
Steve Anton038834f2017-07-14 15:59:59 -0700241bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700242 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700243 if (error_out) {
244 *error_out = std::move(error);
245 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700246 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700247}
248
Steve Antonba818672017-11-06 10:21:57 -0800249std::string GetSignalingStateString(
250 PeerConnectionInterface::SignalingState state) {
251 switch (state) {
252 case PeerConnectionInterface::kStable:
253 return "kStable";
254 case PeerConnectionInterface::kHaveLocalOffer:
255 return "kHaveLocalOffer";
256 case PeerConnectionInterface::kHaveLocalPrAnswer:
257 return "kHavePrAnswer";
258 case PeerConnectionInterface::kHaveRemoteOffer:
259 return "kHaveRemoteOffer";
260 case PeerConnectionInterface::kHaveRemotePrAnswer:
261 return "kHaveRemotePrAnswer";
262 case PeerConnectionInterface::kClosed:
263 return "kClosed";
264 }
265 RTC_NOTREACHED();
266 return "";
267}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700268
Steve Anton75737c02017-11-06 10:37:17 -0800269IceCandidatePairType GetIceCandidatePairCounter(
270 const cricket::Candidate& local,
271 const cricket::Candidate& remote) {
272 const auto& l = local.type();
273 const auto& r = remote.type();
274 const auto& host = LOCAL_PORT_TYPE;
275 const auto& srflx = STUN_PORT_TYPE;
276 const auto& relay = RELAY_PORT_TYPE;
277 const auto& prflx = PRFLX_PORT_TYPE;
278 if (l == host && r == host) {
279 bool local_private = IPIsPrivate(local.address().ipaddr());
280 bool remote_private = IPIsPrivate(remote.address().ipaddr());
281 if (local_private) {
282 if (remote_private) {
283 return kIceCandidatePairHostPrivateHostPrivate;
284 } else {
285 return kIceCandidatePairHostPrivateHostPublic;
286 }
287 } else {
288 if (remote_private) {
289 return kIceCandidatePairHostPublicHostPrivate;
290 } else {
291 return kIceCandidatePairHostPublicHostPublic;
292 }
293 }
294 }
295 if (l == host && r == srflx)
296 return kIceCandidatePairHostSrflx;
297 if (l == host && r == relay)
298 return kIceCandidatePairHostRelay;
299 if (l == host && r == prflx)
300 return kIceCandidatePairHostPrflx;
301 if (l == srflx && r == host)
302 return kIceCandidatePairSrflxHost;
303 if (l == srflx && r == srflx)
304 return kIceCandidatePairSrflxSrflx;
305 if (l == srflx && r == relay)
306 return kIceCandidatePairSrflxRelay;
307 if (l == srflx && r == prflx)
308 return kIceCandidatePairSrflxPrflx;
309 if (l == relay && r == host)
310 return kIceCandidatePairRelayHost;
311 if (l == relay && r == srflx)
312 return kIceCandidatePairRelaySrflx;
313 if (l == relay && r == relay)
314 return kIceCandidatePairRelayRelay;
315 if (l == relay && r == prflx)
316 return kIceCandidatePairRelayPrflx;
317 if (l == prflx && r == host)
318 return kIceCandidatePairPrflxHost;
319 if (l == prflx && r == srflx)
320 return kIceCandidatePairPrflxSrflx;
321 if (l == prflx && r == relay)
322 return kIceCandidatePairPrflxRelay;
323 return kIceCandidatePairMax;
324}
325
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800326// Logic to decide if an m= section can be recycled. This means that the new
327// m= section is not rejected, but the old local or remote m= section is
328// rejected. |old_content_one| and |old_content_two| refer to the m= section
329// of the old remote and old local descriptions in no particular order.
330// We need to check both the old local and remote because either
331// could be the most current from the latest negotation.
332bool IsMediaSectionBeingRecycled(SdpType type,
333 const ContentInfo& content,
334 const ContentInfo* old_content_one,
335 const ContentInfo* old_content_two) {
336 return type == SdpType::kOffer && !content.rejected &&
337 ((old_content_one && old_content_one->rejected) ||
338 (old_content_two && old_content_two->rejected));
339}
340
Steve Anton75737c02017-11-06 10:37:17 -0800341// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800342// |current_desc|. The number of m= sections in |new_desc| should be no
343// less than |current_desc|. In the case of checking an answer's
344// |new_desc|, the |current_desc| is the last offer that was set as the
345// local or remote. In the case of checking an offer's |new_desc| we
346// check against the local and remote descriptions stored from the last
347// negotiation, because either of these could be the most up to date for
348// possible rejected m sections. These are the |current_desc| and
349// |secondary_current_desc|.
350bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
351 const SessionDescription* secondary_current_desc,
352 const SessionDescription& new_desc,
353 const SdpType type) {
354 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800355 return false;
356 }
357
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800358 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
359 const cricket::ContentInfo* secondary_content_info = nullptr;
360 if (secondary_current_desc &&
361 i < secondary_current_desc->contents().size()) {
362 secondary_content_info = &secondary_current_desc->contents()[i];
363 }
364 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
365 &current_desc.contents()[i],
366 secondary_content_info)) {
367 // For new offer descriptions, if the media section can be recycled, it's
368 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800369 continue;
370 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800371 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800375 new_desc.contents()[i].media_description();
376 const MediaContentDescription* current_desc_mdesc =
377 current_desc.contents()[i].media_description();
378 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 return false;
380 }
381 }
382 return true;
383}
384
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800385bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
386 const SessionDescription& desc2) {
387 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800388}
389
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700390void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
391 cricket::MediaType media_type) {
392 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
393 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700412 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
413 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100414 }
415}
416
Harald Alvestrand76829d72018-07-18 23:24:36 +0200417void NoteAddIceCandidateResult(int result) {
418 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
419 kAddIceCandidateMax);
420}
421
Steve Anton75737c02017-11-06 10:37:17 -0800422// Checks that each non-rejected content has SDES crypto keys or a DTLS
423// fingerprint, unless it's in a BUNDLE group, in which case only the
424// BUNDLE-tag section (first media section/description in the BUNDLE group)
425// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
426// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
427// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700428RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800429 const cricket::ContentGroup* bundle =
430 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800431 for (const cricket::ContentInfo& content_info : desc->contents()) {
432 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800433 continue;
434 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100435 // Note what media is used with each crypto protocol, for all sections.
436 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
437 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800439 const std::string& mid = content_info.name;
440 if (bundle && bundle->HasContentName(mid) &&
441 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800442 // This isn't the first media section in the BUNDLE group, so it's not
443 // required to have crypto attributes, since only the crypto attributes
444 // from the first section actually get used.
445 continue;
446 }
447
448 // If the content isn't rejected or bundled into another m= section, crypto
449 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800450 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800451 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800452 if (!media || !tinfo) {
453 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800455 }
456 if (dtls_enabled) {
457 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_WARNING)
459 << "Session description must have DTLS fingerprint if "
460 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800461 return RTCError(RTCErrorType::INVALID_PARAMETER,
462 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800463 }
464 } else {
465 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800467 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800468 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800469 }
470 }
471 }
Steve Anton8a006912017-12-04 15:25:56 -0800472 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800473}
474
475// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
476// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
477// media section/description in the BUNDLE group) needs a ufrag and pwd.
478bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
479 const cricket::ContentGroup* bundle =
480 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800481 for (const cricket::ContentInfo& content_info : desc->contents()) {
482 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800483 continue;
484 }
Steve Anton8a006912017-12-04 15:25:56 -0800485 const std::string& mid = content_info.name;
486 if (bundle && bundle->HasContentName(mid) &&
487 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800488 // This isn't the first media section in the BUNDLE group, so it's not
489 // required to have ufrag/password, since only the ufrag/password from
490 // the first section actually get used.
491 continue;
492 }
493
494 // If the content isn't rejected or bundled into another m= section,
495 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800496 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800497 if (!tinfo) {
498 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800500 return false;
501 }
502 if (tinfo->description.ice_ufrag.empty() ||
503 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100504 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800505 return false;
506 }
507 }
508 return true;
509}
510
511bool GetTrackIdBySsrc(const SessionDescription* session_description,
512 uint32_t ssrc,
513 std::string* track_id) {
514 RTC_DCHECK(track_id != NULL);
515
Steve Antonb1c1de12017-12-21 15:14:30 -0800516 const cricket::AudioContentDescription* audio_desc =
517 cricket::GetFirstAudioContentDescription(session_description);
518 if (audio_desc) {
519 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800520 if (found) {
521 *track_id = found->id;
522 return true;
523 }
524 }
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::VideoContentDescription* video_desc =
527 cricket::GetFirstVideoContentDescription(session_description);
528 if (video_desc) {
529 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535 return false;
536}
537
538// Get the SCTP port out of a SessionDescription.
539// Return -1 if not found.
540int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800541 const cricket::DataContentDescription* data_desc =
542 GetFirstDataContentDescription(session_description);
543 RTC_DCHECK(data_desc);
544 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800545 return -1;
546 }
Steve Anton75737c02017-11-06 10:37:17 -0800547 std::string value;
548 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
549 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 if (!codec.Matches(match_pattern)) {
552 continue;
553 }
554 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
555 return rtc::FromString<int>(value);
556 }
557 }
558 return -1;
559}
560
Steve Anton75737c02017-11-06 10:37:17 -0800561// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
562bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
563 const SessionDescriptionInterface* new_desc,
564 const std::string& content_name) {
565 if (!old_desc) {
566 return false;
567 }
568 const SessionDescription* new_sd = new_desc->description();
569 const SessionDescription* old_sd = old_desc->description();
570 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
571 if (!cinfo || cinfo->rejected) {
572 return false;
573 }
574 // If the content isn't rejected, check if ufrag and password has changed.
575 const cricket::TransportDescription* new_transport_desc =
576 new_sd->GetTransportDescriptionByName(content_name);
577 const cricket::TransportDescription* old_transport_desc =
578 old_sd->GetTransportDescriptionByName(content_name);
579 if (!new_transport_desc || !old_transport_desc) {
580 // No transport description exists. This is not an ICE restart.
581 return false;
582 }
583 if (cricket::IceCredentialsChanged(
584 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
585 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
587 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800588 return true;
589 }
590 return false;
591}
592
Steve Anton80dd7b52018-02-16 17:08:42 -0800593// Generates a string error message for SetLocalDescription/SetRemoteDescription
594// from an RTCError.
595std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
596 SdpType type,
597 const RTCError& error) {
598 std::ostringstream oss;
599 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
600 << " " << SdpTypeToString(type) << " sdp: " << error.message();
601 return oss.str();
602}
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
605 std::string output = "streams=[";
606 const char* separator = "";
607 for (const auto& stream_id : stream_ids) {
608 output.append(separator).append(stream_id);
609 separator = ", ";
610 }
611 output.append("]");
612 return output;
613}
614
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200615absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700616 int rtc_configuration_parameter) {
617 if (rtc_configuration_parameter ==
618 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200619 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700620 }
621 return rtc_configuration_parameter;
622}
623
Steve Anton75737c02017-11-06 10:37:17 -0800624} // namespace
625
Henrik Boström31638672017-11-23 17:48:32 +0100626// Upon completion, posts a task to execute the callback of the
627// SetSessionDescriptionObserver asynchronously on the same thread. At this
628// point, the state of the peer connection might no longer reflect the effects
629// of the SetRemoteDescription operation, as the peer connection could have been
630// modified during the post.
631// TODO(hbos): Remove this class once we remove the version of
632// PeerConnectionInterface::SetRemoteDescription() that takes a
633// SetSessionDescriptionObserver as an argument.
634class PeerConnection::SetRemoteDescriptionObserverAdapter
635 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
636 public:
637 SetRemoteDescriptionObserverAdapter(
638 rtc::scoped_refptr<PeerConnection> pc,
639 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
640 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
641
642 // SetRemoteDescriptionObserverInterface implementation.
643 void OnSetRemoteDescriptionComplete(RTCError error) override {
644 if (error.ok())
645 pc_->PostSetSessionDescriptionSuccess(wrapper_);
646 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100647 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100648 }
649
650 private:
651 rtc::scoped_refptr<PeerConnection> pc_;
652 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
653};
654
deadbeef293e9262017-01-11 12:28:30 -0800655bool PeerConnectionInterface::RTCConfiguration::operator==(
656 const PeerConnectionInterface::RTCConfiguration& o) const {
657 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800659 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000660 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800662 BundlePolicy bundle_policy;
663 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700664 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
665 int ice_candidate_pool_size;
666 bool disable_ipv6;
667 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700668 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100669 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200671 absl::optional<int> screencast_min_bitrate;
672 absl::optional<bool> combined_audio_video_bwe;
673 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800674 TcpCandidatePolicy tcp_candidate_policy;
675 CandidateNetworkPolicy candidate_network_policy;
676 int audio_jitter_buffer_max_packets;
677 bool audio_jitter_buffer_fast_accelerate;
678 int ice_connection_receiving_timeout;
679 int ice_backup_candidate_pair_ping_interval;
680 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800681 bool prioritize_most_likely_ice_candidate_pairs;
682 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800683 bool prune_turn_ports;
684 bool presume_writable_when_fully_relayed;
685 bool enable_ice_renomination;
686 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200687 absl::optional<int> ice_check_interval_strong_connectivity;
688 absl::optional<int> ice_check_interval_weak_connectivity;
689 absl::optional<int> ice_check_min_interval;
690 absl::optional<int> ice_unwritable_timeout;
691 absl::optional<int> ice_unwritable_min_checks;
692 absl::optional<int> stun_candidate_keepalive_interval;
693 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200694 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800695 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200696 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700697 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800698 };
699 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
700 "Did you add something to RTCConfiguration and forget to "
701 "update operator==?");
702 return type == o.type && servers == o.servers &&
703 bundle_policy == o.bundle_policy &&
704 rtcp_mux_policy == o.rtcp_mux_policy &&
705 tcp_candidate_policy == o.tcp_candidate_policy &&
706 candidate_network_policy == o.candidate_network_policy &&
707 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
708 audio_jitter_buffer_fast_accelerate ==
709 o.audio_jitter_buffer_fast_accelerate &&
710 ice_connection_receiving_timeout ==
711 o.ice_connection_receiving_timeout &&
712 ice_backup_candidate_pair_ping_interval ==
713 o.ice_backup_candidate_pair_ping_interval &&
714 continual_gathering_policy == o.continual_gathering_policy &&
715 certificates == o.certificates &&
716 prioritize_most_likely_ice_candidate_pairs ==
717 o.prioritize_most_likely_ice_candidate_pairs &&
718 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800719 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700720 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100721 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800722 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800723 screencast_min_bitrate == o.screencast_min_bitrate &&
724 combined_audio_video_bwe == o.combined_audio_video_bwe &&
725 enable_dtls_srtp == o.enable_dtls_srtp &&
726 ice_candidate_pool_size == o.ice_candidate_pool_size &&
727 prune_turn_ports == o.prune_turn_ports &&
728 presume_writable_when_fully_relayed ==
729 o.presume_writable_when_fully_relayed &&
730 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800731 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800732 ice_check_interval_strong_connectivity ==
733 o.ice_check_interval_strong_connectivity &&
734 ice_check_interval_weak_connectivity ==
735 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700737 ice_unwritable_timeout == o.ice_unwritable_timeout &&
738 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800739 stun_candidate_keepalive_interval ==
740 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200741 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800742 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800743 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700744 network_preference == o.network_preference &&
745 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800746}
747
748bool PeerConnectionInterface::RTCConfiguration::operator!=(
749 const PeerConnectionInterface::RTCConfiguration& o) const {
750 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800751}
752
zhihuang8f65cdf2016-05-06 18:40:30 -0700753// Generate a RTCP CNAME when a PeerConnection is created.
754std::string GenerateRtcpCname() {
755 std::string cname;
756 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100757 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800758 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700759 }
760 return cname;
761}
762
zhihuang1c378ed2017-08-17 14:10:50 -0700763bool ValidateOfferAnswerOptions(
764 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
765 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
766 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700767}
768
zhihuang1c378ed2017-08-17 14:10:50 -0700769// From |rtc_options|, fill parts of |session_options| shared by all generated
770// m= sections (in other words, nothing that involves a map/array).
771void ExtractSharedMediaSessionOptions(
772 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
773 cricket::MediaSessionOptions* session_options) {
774 session_options->vad_enabled = rtc_options.voice_activity_detection;
775 session_options->bundle_enabled = rtc_options.use_rtp_mux;
776}
zhihuanga77e6bb2017-08-14 18:17:48 -0700777
zhihuang38ede132017-06-15 12:52:32 -0700778PeerConnection::PeerConnection(PeerConnectionFactory* factory,
779 std::unique_ptr<RtcEventLog> event_log,
780 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700782 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700783 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700784 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700785 remote_streams_(StreamCollection::Create()),
786 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000787
788PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100789 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800790 RTC_DCHECK_RUN_ON(signaling_thread());
791
Steve Anton8af21862017-12-15 11:20:13 -0800792 // Need to stop transceivers before destroying the stats collector because
793 // AudioRtpSender has a reference to the StatsCollector it will update when
794 // stopping.
795 for (auto transceiver : transceivers_) {
796 transceiver->Stop();
797 }
Steve Anton4171afb2017-11-20 10:20:22 -0800798
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700799 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800800 if (stats_collector_) {
801 stats_collector_->WaitForPendingRequest();
802 stats_collector_ = nullptr;
803 }
Steve Anton75737c02017-11-06 10:37:17 -0800804
Steve Anton8af21862017-12-15 11:20:13 -0800805 // Don't destroy BaseChannels until after stats has been cleaned up so that
806 // the last stats request can still read from the channels.
807 DestroyAllChannels();
808
Mirko Bonadei675513b2017-11-09 11:09:25 +0100809 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800810
811 webrtc_session_desc_factory_.reset();
812 sctp_invoker_.reset();
813 sctp_factory_.reset();
814 transport_controller_.reset();
815
deadbeef91dd5672016-05-18 16:55:30 -0700816 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700817 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700818 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700819 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700820 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700821 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800822 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700823 event_log_.reset();
824 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825}
826
Steve Anton8af21862017-12-15 11:20:13 -0800827void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800828 // Destroy video channels first since they may have a pointer to a voice
829 // channel.
830 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800831 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800832 DestroyTransceiverChannel(transceiver);
833 }
834 }
835 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800836 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800837 DestroyTransceiverChannel(transceiver);
838 }
839 }
840 DestroyDataChannel();
841}
842
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000844 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700845 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100846 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700847
848 RTCError config_error = ValidateConfiguration(configuration);
849 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700851 return false;
852 }
853
Benjamin Wrightcab58882018-05-02 15:12:47 -0700854 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100855 RTC_LOG(LS_ERROR)
856 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100857 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800858 return false;
859 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200860
Benjamin Wrightcab58882018-05-02 15:12:47 -0700861 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800862 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100863 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100864 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800865 return false;
866 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700867
Benjamin Wrightcab58882018-05-02 15:12:47 -0700868 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700869 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700870 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700871 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800872
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200873 cricket::ServerAddresses stun_servers;
874 std::vector<cricket::RelayServerConfig> turn_servers;
875
876 RTCErrorType parse_error =
877 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
878 if (parse_error != RTCErrorType::NONE) {
879 return false;
880 }
881
deadbeef91dd5672016-05-18 16:55:30 -0700882 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700883 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700884 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200885 RTC_FROM_HERE,
886 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
887 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888 return false;
889 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200890 // If initialization was successful, note if STUN or TURN servers
891 // were supplied.
892 if (!stun_servers.empty()) {
893 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
894 }
895 if (!turn_servers.empty()) {
896 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
897 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700899 // Send information about IPv4/IPv6 status.
900 PeerConnectionAddressFamilyCounter address_family;
901 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
902 address_family = kPeerConnection_IPv6;
903 } else {
904 address_family = kPeerConnection_IPv4;
905 }
906 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
907 kPeerConnectionAddressFamilyCounter_Max);
908
Zhi Huange830e682018-03-30 10:48:35 -0700909 const PeerConnectionFactoryInterface::Options& options = factory_->options();
910
Steve Anton75737c02017-11-06 10:37:17 -0800911 // RFC 3264: The numeric value of the session id and version in the
912 // o line MUST be representable with a "64 bit signed integer".
913 // Due to this constraint session id |session_id_| is max limited to
914 // LLONG_MAX.
915 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700916 JsepTransportController::Config config;
917 config.redetermine_role_on_ice_restart =
918 configuration.redetermine_role_on_ice_restart;
919 config.ssl_max_version = factory_->options().ssl_max_version;
920 config.disable_encryption = options.disable_encryption;
921 config.bundle_policy = configuration.bundle_policy;
922 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
923 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700924 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700925 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700926#if defined(ENABLE_EXTERNAL_AUTH)
927 config.enable_external_auth = true;
928#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700929 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700930 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700931 signaling_thread(), network_thread(), port_allocator_.get(),
932 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700933 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800934 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700935 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800936 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700937 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800938 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700939 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800940 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
941 transport_controller_->SignalDtlsHandshakeError.connect(
942 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
943
944 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700945
deadbeefab9b2d12015-10-14 11:33:11 -0700946 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700947 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948
Steve Antonba818672017-11-06 10:21:57 -0800949 configuration_ = configuration;
950
Steve Anton75737c02017-11-06 10:37:17 -0800951 // Obtain a certificate from RTCConfiguration if any were provided (optional).
952 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
953 if (!configuration.certificates.empty()) {
954 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
955 // just picking the first one. The decision should be made based on the DTLS
956 // handshake. The DTLS negotiations need to know about all certificates.
957 certificate = configuration.certificates[0];
958 }
959
Steve Antond25da372017-11-06 14:50:29 -0800960 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800961
962 if (options.disable_encryption) {
963 dtls_enabled_ = false;
964 } else {
965 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700966 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800967 // |configuration| can override the default |dtls_enabled_| value.
968 if (configuration.enable_dtls_srtp) {
969 dtls_enabled_ = *(configuration.enable_dtls_srtp);
970 }
971 }
972
973 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
974 // It takes precendence over the disable_sctp_data_channels
975 // PeerConnectionFactoryInterface::Options.
976 if (configuration.enable_rtp_data_channel) {
977 data_channel_type_ = cricket::DCT_RTP;
978 } else {
979 // DTLS has to be enabled to use SCTP.
980 if (!options.disable_sctp_data_channels && dtls_enabled_) {
981 data_channel_type_ = cricket::DCT_SCTP;
982 }
983 }
984
985 video_options_.screencast_min_bitrate_kbps =
986 configuration.screencast_min_bitrate;
987 audio_options_.combined_audio_video_bwe =
988 configuration.combined_audio_video_bwe;
989
990 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100991 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800992
993 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100994 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800995
996 // Whether the certificate generator/certificate is null or not determines
997 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
998 // the right instructions by clearing the variables if needed.
999 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001000 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001001 certificate = nullptr;
1002 } else if (certificate) {
1003 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001004 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001005 }
1006
1007 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1008 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001009 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001010 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1011 this, &PeerConnection::OnCertificateReady);
1012
1013 if (options.disable_encryption) {
1014 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1015 }
1016
1017 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1018 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019
Steve Anton4171afb2017-11-20 10:20:22 -08001020 // Add default audio/video transceivers for Plan B SDP.
1021 if (!IsUnifiedPlan()) {
1022 transceivers_.push_back(
1023 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1024 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1025 transceivers_.push_back(
1026 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1027 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1028 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001029 int delay_ms =
1030 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1031 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1032 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033 return true;
1034}
1035
Steve Anton038834f2017-07-14 15:59:59 -07001036RTCError PeerConnection::ValidateConfiguration(
1037 const RTCConfiguration& config) const {
1038 if (config.ice_regather_interval_range &&
1039 config.continual_gathering_policy == GATHER_ONCE) {
1040 return RTCError(RTCErrorType::INVALID_PARAMETER,
1041 "ice_regather_interval_range specified but continual "
1042 "gathering policy is GATHER_ONCE");
1043 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001044 auto result =
1045 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1046 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001047}
1048
Yves Gerey665174f2018-06-19 15:03:05 +02001049rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001050 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1051 "Plan SdpSemantics. Please use GetSenders "
1052 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001053 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001054}
1055
Yves Gerey665174f2018-06-19 15:03:05 +02001056rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001057 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1058 "Plan SdpSemantics. Please use GetReceivers "
1059 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001060 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061}
1062
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001063bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1065 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001066 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 if (IsClosed()) {
1068 return false;
1069 }
deadbeefab9b2d12015-10-14 11:33:11 -07001070 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071 return false;
1072 }
deadbeefab9b2d12015-10-14 11:33:11 -07001073
1074 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001075 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1076 observer->SignalAudioTrackAdded.connect(this,
1077 &PeerConnection::OnAudioTrackAdded);
1078 observer->SignalAudioTrackRemoved.connect(
1079 this, &PeerConnection::OnAudioTrackRemoved);
1080 observer->SignalVideoTrackAdded.connect(this,
1081 &PeerConnection::OnVideoTrackAdded);
1082 observer->SignalVideoTrackRemoved.connect(
1083 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001084 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001085
deadbeefab9b2d12015-10-14 11:33:11 -07001086 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001087 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001088 }
1089 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001090 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001091 }
1092
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001093 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001094 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 return true;
1096}
1097
1098void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001099 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1100 "Plan SdpSemantics. Please use RemoveTrack "
1101 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001102 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001103 if (!IsClosed()) {
1104 for (const auto& track : local_stream->GetAudioTracks()) {
1105 RemoveAudioTrack(track.get(), local_stream);
1106 }
1107 for (const auto& track : local_stream->GetVideoTracks()) {
1108 RemoveVideoTrack(track.get(), local_stream);
1109 }
deadbeefab9b2d12015-10-14 11:33:11 -07001110 }
deadbeefab9b2d12015-10-14 11:33:11 -07001111 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001112 stream_observers_.erase(
1113 std::remove_if(
1114 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001115 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001116 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001117 }),
1118 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001119
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120 if (IsClosed()) {
1121 return;
1122 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001123 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001124}
1125
Steve Anton2d6c76a2018-01-05 17:10:52 -08001126RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001127 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001128 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001129 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001130 if (!track) {
1131 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1132 }
1133 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1134 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1135 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1136 "Track has invalid kind: " + track->kind());
1137 }
Steve Antonf9381f02017-12-14 10:23:57 -08001138 if (IsClosed()) {
1139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1140 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001141 }
Steve Anton4171afb2017-11-20 10:20:22 -08001142 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001143 LOG_AND_RETURN_ERROR(
1144 RTCErrorType::INVALID_PARAMETER,
1145 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001146 }
Steve Antonf9381f02017-12-14 10:23:57 -08001147 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001148 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1149 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001150 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001151 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001152 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001153 }
1154 return sender_or_error;
1155}
deadbeefe1f9d832016-01-14 15:35:42 -08001156
Steve Antonf9381f02017-12-14 10:23:57 -08001157RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1158PeerConnection::AddTrackPlanB(
1159 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001160 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001161 if (stream_ids.size() > 1u) {
1162 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1163 "AddTrack with more than one stream is not "
1164 "supported with Plan B semantics.");
1165 }
1166 std::vector<std::string> adjusted_stream_ids = stream_ids;
1167 if (adjusted_stream_ids.empty()) {
1168 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1169 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001170 cricket::MediaType media_type =
1171 (track->kind() == MediaStreamTrackInterface::kAudioKind
1172 ? cricket::MEDIA_TYPE_AUDIO
1173 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001174 auto new_sender =
1175 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001176 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001177 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001178 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001179 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001180 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001181 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001182 if (sender_info) {
1183 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001184 }
Steve Antonf9381f02017-12-14 10:23:57 -08001185 } else {
1186 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001187 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001188 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001189 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001190 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001191 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001192 if (sender_info) {
1193 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
deadbeefe1f9d832016-01-14 15:35:42 -08001195 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001196 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001197}
deadbeefe1f9d832016-01-14 15:35:42 -08001198
Steve Antonf9381f02017-12-14 10:23:57 -08001199RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1200PeerConnection::AddTrackUnifiedPlan(
1201 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001202 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001203 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1204 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001205 RTC_LOG(LS_INFO) << "Reusing an existing "
1206 << cricket::MediaTypeToString(transceiver->media_type())
1207 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001208 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001209 transceiver->internal()->set_direction(
1210 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001211 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001212 transceiver->internal()->set_direction(
1213 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001215 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001216 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001217 } else {
1218 cricket::MediaType media_type =
1219 (track->kind() == MediaStreamTrackInterface::kAudioKind
1220 ? cricket::MEDIA_TYPE_AUDIO
1221 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001222 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1223 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001224 std::string sender_id = track->id();
1225 // Avoid creating a sender with an existing ID by generating a random ID.
1226 // This can happen if this is the second time AddTrack has created a sender
1227 // for this track.
1228 if (FindSenderById(sender_id)) {
1229 sender_id = rtc::CreateRandomUuid();
1230 }
1231 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001232 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1233 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001234 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001235 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001236 }
Steve Antonf9381f02017-12-14 10:23:57 -08001237 return transceiver->sender();
1238}
1239
1240rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1241PeerConnection::FindFirstTransceiverForAddedTrack(
1242 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1243 RTC_DCHECK(track);
1244 for (auto transceiver : transceivers_) {
1245 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001246 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001247 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001248 !transceiver->internal()->has_ever_been_used_to_send() &&
1249 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001250 return transceiver;
1251 }
1252 }
1253 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001254}
1255
1256bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1257 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001258 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001259}
1260
Steve Anton24db5732018-07-23 10:27:33 -07001261RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001262 rtc::scoped_refptr<RtpSenderInterface> sender) {
1263 if (!sender) {
1264 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1265 }
deadbeefe1f9d832016-01-14 15:35:42 -08001266 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001267 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1268 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001269 }
Steve Antonf9381f02017-12-14 10:23:57 -08001270 if (IsUnifiedPlan()) {
1271 auto transceiver = FindTransceiverBySender(sender);
1272 if (!transceiver || !sender->track()) {
1273 return RTCError::OK();
1274 }
1275 sender->SetTrack(nullptr);
1276 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001277 transceiver->internal()->set_direction(
1278 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001279 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001280 transceiver->internal()->set_direction(
1281 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001282 }
Steve Anton4171afb2017-11-20 10:20:22 -08001283 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001284 bool removed;
1285 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1286 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1287 } else {
1288 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1289 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1290 }
1291 if (!removed) {
1292 LOG_AND_RETURN_ERROR(
1293 RTCErrorType::INVALID_PARAMETER,
1294 "Couldn't find sender " + sender->id() + " to remove.");
1295 }
Steve Anton4171afb2017-11-20 10:20:22 -08001296 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001297 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001298 return RTCError::OK();
1299}
1300
1301rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1302PeerConnection::FindTransceiverBySender(
1303 rtc::scoped_refptr<RtpSenderInterface> sender) {
1304 for (auto transceiver : transceivers_) {
1305 if (transceiver->sender() == sender) {
1306 return transceiver;
1307 }
1308 }
1309 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001310}
1311
Steve Anton9158ef62017-11-27 13:01:52 -08001312RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1313PeerConnection::AddTransceiver(
1314 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1315 return AddTransceiver(track, RtpTransceiverInit());
1316}
1317
1318RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1319PeerConnection::AddTransceiver(
1320 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1321 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001322 RTC_CHECK(IsUnifiedPlan())
1323 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001324 if (!track) {
1325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1326 }
1327 cricket::MediaType media_type;
1328 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1329 media_type = cricket::MEDIA_TYPE_AUDIO;
1330 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1331 media_type = cricket::MEDIA_TYPE_VIDEO;
1332 } else {
1333 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1334 "Track kind is not audio or video");
1335 }
1336 return AddTransceiver(media_type, track, init);
1337}
1338
1339RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1340PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1341 return AddTransceiver(media_type, RtpTransceiverInit());
1342}
1343
1344RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1345PeerConnection::AddTransceiver(cricket::MediaType media_type,
1346 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001347 RTC_CHECK(IsUnifiedPlan())
1348 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001349 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1350 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "media type is not audio or video");
1353 }
1354 return AddTransceiver(media_type, nullptr, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(
1359 cricket::MediaType media_type,
1360 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001361 const RtpTransceiverInit& init,
1362 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001363 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1364 media_type == cricket::MEDIA_TYPE_VIDEO));
1365 if (track) {
1366 RTC_DCHECK_EQ(media_type,
1367 (track->kind() == MediaStreamTrackInterface::kAudioKind
1368 ? cricket::MEDIA_TYPE_AUDIO
1369 : cricket::MEDIA_TYPE_VIDEO));
1370 }
1371
1372 // TODO(bugs.webrtc.org/7600): Verify init.
1373
Steve Anton3d954a62018-04-02 11:27:23 -07001374 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1375 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001376 // Set the sender ID equal to the track ID if the track is specified unless
1377 // that sender ID is already in use.
1378 std::string sender_id =
1379 (track && !FindSenderById(track->id()) ? track->id()
1380 : rtc::CreateRandomUuid());
1381 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001382 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1383 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1384 transceiver->internal()->set_direction(init.direction);
1385
Steve Anton22da89f2018-01-25 13:58:07 -08001386 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001387 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001388 }
Steve Antonf9381f02017-12-14 10:23:57 -08001389
1390 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1391}
1392
Steve Anton02ee47c2018-01-10 16:26:06 -08001393rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1394PeerConnection::CreateSender(
1395 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001396 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001397 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001398 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001399 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001400 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1401 RTC_DCHECK(!track ||
1402 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1403 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1404 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001405 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001406 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001407 } else {
1408 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1409 RTC_DCHECK(!track ||
1410 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1411 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001412 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001413 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001414 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001415 bool set_track_succeeded = sender->SetTrack(track);
1416 RTC_DCHECK(set_track_succeeded);
1417 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001418 return sender;
1419}
1420
1421rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1422PeerConnection::CreateReceiver(cricket::MediaType media_type,
1423 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1425 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001427 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001428 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1429 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001430 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001431 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001433 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001434 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1435 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001436 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001437 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001438 return receiver;
1439}
1440
1441rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1442PeerConnection::CreateAndAddTransceiver(
1443 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1444 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1445 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001446 // Ensure that the new sender does not have an ID that is already in use by
1447 // another sender.
1448 // Allow receiver IDs to conflict since those come from remote SDP (which
1449 // could be invalid, but should not cause a crash).
1450 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1452 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001453 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001454 transceiver->internal()->SignalNegotiationNeeded.connect(
1455 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001456 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001457}
1458
Steve Anton52d86772018-02-20 15:48:12 -08001459void PeerConnection::OnNegotiationNeeded() {
1460 RTC_DCHECK_RUN_ON(signaling_thread());
1461 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001462 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001463}
1464
deadbeeffac06552015-11-25 11:26:01 -08001465rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001466 const std::string& kind,
1467 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001468 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1469 "Plan SdpSemantics. Please use AddTransceiver "
1470 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001471 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001472 if (IsClosed()) {
1473 return nullptr;
1474 }
Steve Anton4171afb2017-11-20 10:20:22 -08001475
Seth Hampson5b4f0752018-04-02 16:31:36 -07001476 // Internally we need to have one stream with Plan B semantics, so we
1477 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001478 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001479 if (stream_id.empty()) {
1480 stream_ids.push_back(rtc::CreateRandomUuid());
1481 RTC_LOG(LS_INFO)
1482 << "No stream_id specified for sender. Generated stream ID: "
1483 << stream_ids[0];
1484 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001485 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001486 }
1487
Steve Anton4171afb2017-11-20 10:20:22 -08001488 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001489 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001490 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001491 auto* audio_sender = new AudioRtpSender(
1492 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001493 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001494 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001496 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001497 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001498 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001499 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001500 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001501 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001503 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001504 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001505 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001506 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001507 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001508 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001509
deadbeefe1f9d832016-01-14 15:35:42 -08001510 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001511}
1512
deadbeef70ab1a12015-09-28 16:53:55 -07001513std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1514 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001515 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001516 for (auto sender : GetSendersInternal()) {
1517 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001518 }
1519 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001520}
1521
Steve Anton4171afb2017-11-20 10:20:22 -08001522std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1523PeerConnection::GetSendersInternal() const {
1524 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1525 all_senders;
1526 for (auto transceiver : transceivers_) {
1527 auto senders = transceiver->internal()->senders();
1528 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1529 }
1530 return all_senders;
1531}
1532
deadbeef70ab1a12015-09-28 16:53:55 -07001533std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1534PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001535 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001536 for (const auto& receiver : GetReceiversInternal()) {
1537 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001538 }
1539 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001540}
1541
Steve Anton4171afb2017-11-20 10:20:22 -08001542std::vector<
1543 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1544PeerConnection::GetReceiversInternal() const {
1545 std::vector<
1546 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1547 all_receivers;
1548 for (auto transceiver : transceivers_) {
1549 auto receivers = transceiver->internal()->receivers();
1550 all_receivers.insert(all_receivers.end(), receivers.begin(),
1551 receivers.end());
1552 }
1553 return all_receivers;
1554}
1555
Steve Anton9158ef62017-11-27 13:01:52 -08001556std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1557PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001558 RTC_CHECK(IsUnifiedPlan())
1559 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001560 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1561 for (auto transceiver : transceivers_) {
1562 all_transceivers.push_back(transceiver);
1563 }
1564 return all_transceivers;
1565}
1566
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001568 MediaStreamTrackInterface* track,
1569 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001570 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001571 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001572 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001573 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 return false;
1575 }
1576
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001577 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001578 // The StatsCollector is used to tell if a track is valid because it may
1579 // remember tracks that the PeerConnection previously removed.
1580 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1582 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001583 return false;
1584 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001585 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001586 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001587 return true;
1588}
1589
hbos74e1a4f2016-09-15 23:33:01 -07001590void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001591 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001592 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001593 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001594 stats_collector_->GetStatsReport(callback);
1595}
1596
Henrik Boström1df1bf82018-03-20 13:24:20 +01001597void PeerConnection::GetStats(
1598 rtc::scoped_refptr<RtpSenderInterface> selector,
1599 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1600 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1601 RTC_DCHECK(callback);
1602 RTC_DCHECK(stats_collector_);
1603 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1604 if (selector) {
1605 for (const auto& proxy_transceiver : transceivers_) {
1606 for (const auto& proxy_sender :
1607 proxy_transceiver->internal()->senders()) {
1608 if (proxy_sender == selector) {
1609 internal_sender = proxy_sender->internal();
1610 break;
1611 }
1612 }
1613 if (internal_sender)
1614 break;
1615 }
1616 }
1617 // If there is no |internal_sender| then |selector| is either null or does not
1618 // belong to the PeerConnection (in Plan B, senders can be removed from the
1619 // PeerConnection). This means that "all the stats objects representing the
1620 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1621 // produces an empty stats report.
1622 stats_collector_->GetStatsReport(internal_sender, callback);
1623}
1624
1625void PeerConnection::GetStats(
1626 rtc::scoped_refptr<RtpReceiverInterface> selector,
1627 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1628 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1629 RTC_DCHECK(callback);
1630 RTC_DCHECK(stats_collector_);
1631 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1632 if (selector) {
1633 for (const auto& proxy_transceiver : transceivers_) {
1634 for (const auto& proxy_receiver :
1635 proxy_transceiver->internal()->receivers()) {
1636 if (proxy_receiver == selector) {
1637 internal_receiver = proxy_receiver->internal();
1638 break;
1639 }
1640 }
1641 if (internal_receiver)
1642 break;
1643 }
1644 }
1645 // If there is no |internal_receiver| then |selector| is either null or does
1646 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1647 // the PeerConnection). This means that "all the stats objects representing
1648 // the selector" is an empty set. Invoking GetStatsReport() with a null
1649 // selector produces an empty stats report.
1650 stats_collector_->GetStatsReport(internal_receiver, callback);
1651}
1652
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001653PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1654 return signaling_state_;
1655}
1656
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657PeerConnectionInterface::IceConnectionState
1658PeerConnection::ice_connection_state() {
1659 return ice_connection_state_;
1660}
1661
1662PeerConnectionInterface::IceGatheringState
1663PeerConnection::ice_gathering_state() {
1664 return ice_gathering_state_;
1665}
1666
Yves Gerey665174f2018-06-19 15:03:05 +02001667rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668 const std::string& label,
1669 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001670 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001671
deadbeefab9b2d12015-10-14 11:33:11 -07001672 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001673
kwibergd1fe2812016-04-27 06:47:29 -07001674 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001675 if (config) {
1676 internal_config.reset(new InternalDataChannelInit(*config));
1677 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001678 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001679 InternalCreateDataChannel(label, internal_config.get()));
1680 if (!channel.get()) {
1681 return nullptr;
1682 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001684 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1685 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001686 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001687 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001688 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001689 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 return DataChannelProxy::Create(signaling_thread(), channel.get());
1691}
1692
1693void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001694 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001695 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001696
nisse7ce109a2017-01-31 00:57:56 -08001697 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001698 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001699 return;
1700 }
deadbeefab9b2d12015-10-14 11:33:11 -07001701
Steve Anton8d3444d2017-10-20 15:30:51 -07001702 if (IsClosed()) {
1703 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001704 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001705 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001706 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001707 return;
1708 }
1709
zhihuang1c378ed2017-08-17 14:10:50 -07001710 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001711 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001712 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001713 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001714 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001715 return;
1716 }
1717
Steve Anton22da89f2018-01-25 13:58:07 -08001718 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1719 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1720 if (IsUnifiedPlan()) {
1721 RTCError error = HandleLegacyOfferOptions(options);
1722 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001723 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001724 return;
1725 }
1726 }
1727
zhihuang1c378ed2017-08-17 14:10:50 -07001728 cricket::MediaSessionOptions session_options;
1729 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001730 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731}
1732
Steve Anton22da89f2018-01-25 13:58:07 -08001733RTCError PeerConnection::HandleLegacyOfferOptions(
1734 const RTCOfferAnswerOptions& options) {
1735 RTC_DCHECK(IsUnifiedPlan());
1736
1737 if (options.offer_to_receive_audio == 0) {
1738 RemoveRecvDirectionFromReceivingTransceiversOfType(
1739 cricket::MEDIA_TYPE_AUDIO);
1740 } else if (options.offer_to_receive_audio == 1) {
1741 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1742 } else if (options.offer_to_receive_audio > 1) {
1743 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1744 "offer_to_receive_audio > 1 is not supported.");
1745 }
1746
1747 if (options.offer_to_receive_video == 0) {
1748 RemoveRecvDirectionFromReceivingTransceiversOfType(
1749 cricket::MEDIA_TYPE_VIDEO);
1750 } else if (options.offer_to_receive_video == 1) {
1751 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1752 } else if (options.offer_to_receive_video > 1) {
1753 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1754 "offer_to_receive_video > 1 is not supported.");
1755 }
1756
1757 return RTCError::OK();
1758}
1759
1760void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1761 cricket::MediaType media_type) {
1762 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001763 RtpTransceiverDirection new_direction =
1764 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1765 if (new_direction != transceiver->direction()) {
1766 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1767 << " transceiver (MID="
1768 << transceiver->mid().value_or("<not set>") << ") from "
1769 << RtpTransceiverDirectionToString(
1770 transceiver->direction())
1771 << " to "
1772 << RtpTransceiverDirectionToString(new_direction)
1773 << " since CreateOffer specified offer_to_receive=0";
1774 transceiver->internal()->set_direction(new_direction);
1775 }
Steve Anton22da89f2018-01-25 13:58:07 -08001776 }
1777}
1778
1779void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1780 cricket::MediaType media_type) {
1781 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001782 RTC_LOG(LS_INFO)
1783 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1784 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001785 RtpTransceiverInit init;
1786 init.direction = RtpTransceiverDirection::kRecvOnly;
1787 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1788 }
1789}
1790
1791std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1792PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1793 std::vector<
1794 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1795 receiving_transceivers;
1796 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001797 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001798 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1799 receiving_transceivers.push_back(transceiver);
1800 }
1801 }
1802 return receiving_transceivers;
1803}
1804
htaa2a49d92016-03-04 02:51:39 -08001805void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1806 const RTCOfferAnswerOptions& options) {
1807 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001808 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001809 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001810 return;
1811 }
1812
Steve Antondffead82018-02-06 10:31:29 -08001813 if (!(signaling_state_ == kHaveRemoteOffer ||
1814 signaling_state_ == kHaveLocalPrAnswer)) {
1815 std::string error =
1816 "PeerConnection cannot create an answer in a state other than "
1817 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001818 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001819 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001820 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001821 return;
1822 }
1823
Steve Antondffead82018-02-06 10:31:29 -08001824 // The remote description should be set if we're in the right state.
1825 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001826
Steve Anton22da89f2018-01-25 13:58:07 -08001827 if (IsUnifiedPlan()) {
1828 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1829 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1830 "supported with Unified Plan semantics. Use the "
1831 "RtpTransceiver API instead.";
1832 }
1833 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1834 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1835 "supported with Unified Plan semantics. Use the "
1836 "RtpTransceiver API instead.";
1837 }
1838 }
1839
htaa2a49d92016-03-04 02:51:39 -08001840 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001841 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001842
Steve Antond25da372017-11-06 14:50:29 -08001843 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844}
1845
1846void PeerConnection::SetLocalDescription(
1847 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001848 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001849 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001850
Steve Anton80dd7b52018-02-16 17:08:42 -08001851 // The SetLocalDescription contract is that we take ownership of the session
1852 // description regardless of the outcome, so wrap it in a unique_ptr right
1853 // away. Ideally, SetLocalDescription's signature will be changed to take the
1854 // description as a unique_ptr argument to formalize this agreement.
1855 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1856
nisse7ce109a2017-01-31 00:57:56 -08001857 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001858 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 return;
1860 }
Steve Anton8a006912017-12-04 15:25:56 -08001861
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001863 PostSetSessionDescriptionFailure(
1864 observer,
1865 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866 return;
1867 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001868
Steve Anton80dd7b52018-02-16 17:08:42 -08001869 // If a session error has occurred the PeerConnection is in a possibly
1870 // inconsistent state so fail right away.
1871 if (session_error() != SessionError::kNone) {
1872 std::string error_message = GetSessionErrorMsg();
1873 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001874 PostSetSessionDescriptionFailure(
1875 observer,
1876 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001877 return;
1878 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001879
Steve Anton80dd7b52018-02-16 17:08:42 -08001880 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1881 if (!error.ok()) {
1882 std::string error_message = GetSetDescriptionErrorMessage(
1883 cricket::CS_LOCAL, desc->GetType(), error);
1884 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001885 PostSetSessionDescriptionFailure(
1886 observer,
1887 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001888 return;
1889 }
1890
1891 // Grab the description type before moving ownership to ApplyLocalDescription,
1892 // which may destroy it before returning.
1893 const SdpType type = desc->GetType();
1894
1895 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001896 // |desc| may be destroyed at this point.
1897
1898 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001899 // If ApplyLocalDescription fails, the PeerConnection could be in an
1900 // inconsistent state, so act conservatively here and set the session error
1901 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1902 SetSessionError(SessionError::kContent, error.message());
1903 std::string error_message =
1904 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1905 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001906 PostSetSessionDescriptionFailure(
1907 observer,
1908 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001909 return;
1910 }
Steve Anton8a006912017-12-04 15:25:56 -08001911 RTC_DCHECK(local_description());
1912
1913 PostSetSessionDescriptionSuccess(observer);
1914
Steve Anton8a006912017-12-04 15:25:56 -08001915 // MaybeStartGathering needs to be called after posting
1916 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1917 // before signaling that SetLocalDescription completed.
1918 transport_controller_->MaybeStartGathering();
1919
Steve Antona3a92c22017-12-07 10:27:41 -08001920 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001921 // TODO(deadbeef): We already had to hop to the network thread for
1922 // MaybeStartGathering...
1923 network_thread()->Invoke<void>(
1924 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1925 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001926 // Make UMA notes about what was agreed to.
1927 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001928 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001929 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001930}
1931
1932RTCError PeerConnection::ApplyLocalDescription(
1933 std::unique_ptr<SessionDescriptionInterface> desc) {
1934 RTC_DCHECK_RUN_ON(signaling_thread());
1935 RTC_DCHECK(desc);
1936
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937 // Update stats here so that we have the most recent stats for tracks and
1938 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001939 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001940
Steve Antondcc3c022017-12-22 16:02:54 -08001941 // Take a reference to the old local description since it's used below to
1942 // compare against the new local description. When setting the new local
1943 // description, grab ownership of the replaced session description in case it
1944 // is the same as |old_local_description|, to keep it alive for the duration
1945 // of the method.
1946 const SessionDescriptionInterface* old_local_description =
1947 local_description();
1948 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001949 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001950 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001951 replaced_local_description = pending_local_description_
1952 ? std::move(pending_local_description_)
1953 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001954 current_local_description_ = std::move(desc);
1955 pending_local_description_ = nullptr;
1956 current_remote_description_ = std::move(pending_remote_description_);
1957 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001958 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001959 pending_local_description_ = std::move(desc);
1960 }
1961 // The session description to apply now must be accessed by
1962 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001963 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001964
Zhi Huange830e682018-03-30 10:48:35 -07001965 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1966 if (!error.ok()) {
1967 return error;
1968 }
1969
Steve Antondcc3c022017-12-22 16:02:54 -08001970 if (IsUnifiedPlan()) {
1971 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001972 cricket::CS_LOCAL, *local_description(), old_local_description,
1973 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001974 if (!error.ok()) {
1975 return error;
1976 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001977 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1978 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001979 for (auto transceiver : transceivers_) {
1980 const ContentInfo* content =
1981 FindMediaSectionForTransceiver(transceiver, local_description());
1982 if (!content) {
1983 continue;
1984 }
1985 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001986 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1987 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001988 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001989 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1990 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
1991 // "recvonly", process the removal of a remote track for the media
1992 // description, given transceiver, removeList, and muteTracks.
1993 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
1994 (transceiver->internal()->fired_direction() &&
1995 RtpTransceiverDirectionHasRecv(
1996 *transceiver->internal()->fired_direction()))) {
1997 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
1998 &removed_streams);
1999 }
2000 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2001 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002002 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002003 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002004 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002005 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002006 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002007 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002008 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002009 }
2010 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002011 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002012 }
2013 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002014 // Media channels will be created only when offer is set. These may use new
2015 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002016 if (type == SdpType::kOffer) {
2017 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2018 // description is applied. Restore back to old description.
2019 RTCError error = CreateChannels(*local_description()->description());
2020 if (!error.ok()) {
2021 return error;
2022 }
2023 }
Steve Antondcc3c022017-12-22 16:02:54 -08002024 // Remove unused channels if MediaContentDescription is rejected.
2025 RemoveUnusedChannels(local_description()->description());
2026 }
Steve Anton8a006912017-12-04 15:25:56 -08002027
Zhi Huange830e682018-03-30 10:48:35 -07002028 error = UpdateSessionState(type, cricket::CS_LOCAL,
2029 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002030 if (!error.ok()) {
2031 return error;
2032 }
Steve Antondcc3c022017-12-22 16:02:54 -08002033
Steve Anton8a006912017-12-04 15:25:56 -08002034 if (remote_description()) {
2035 // Now that we have a local description, we can push down remote candidates.
2036 UseCandidatesInSessionDescription(remote_description());
2037 }
2038
2039 pending_ice_restarts_.clear();
2040 if (session_error() != SessionError::kNone) {
2041 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2042 }
2043
deadbeefab9b2d12015-10-14 11:33:11 -07002044 // If setting the description decided our SSL role, allocate any necessary
2045 // SCTP sids.
2046 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002047 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002048 AllocateSctpSids(role);
2049 }
2050
Steve Antond3679212018-01-17 17:41:02 -08002051 if (IsUnifiedPlan()) {
2052 for (auto transceiver : transceivers_) {
2053 const ContentInfo* content =
2054 FindMediaSectionForTransceiver(transceiver, local_description());
2055 if (!content) {
2056 continue;
2057 }
Steve Anton74255ff2018-01-24 18:32:57 -08002058 const auto& streams = content->media_description()->streams();
2059 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002060 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002061 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002062 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002063 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002064 } else {
2065 // 0 is a special value meaning "this sender has no associated send
2066 // stream". Need to call this so the sender won't attempt to configure
2067 // a no longer existing stream and run into DCHECKs in the lower
2068 // layers.
2069 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002070 }
2071 }
2072 } else {
2073 // Plan B semantics.
2074
Steve Antondcc3c022017-12-22 16:02:54 -08002075 // Update state and SSRC of local MediaStreams and DataChannels based on the
2076 // local session description.
2077 const cricket::ContentInfo* audio_content =
2078 GetFirstAudioContent(local_description()->description());
2079 if (audio_content) {
2080 if (audio_content->rejected) {
2081 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2082 } else {
2083 const cricket::AudioContentDescription* audio_desc =
2084 audio_content->media_description()->as_audio();
2085 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2086 }
deadbeeffaac4972015-11-12 15:33:07 -08002087 }
deadbeefab9b2d12015-10-14 11:33:11 -07002088
Steve Antondcc3c022017-12-22 16:02:54 -08002089 const cricket::ContentInfo* video_content =
2090 GetFirstVideoContent(local_description()->description());
2091 if (video_content) {
2092 if (video_content->rejected) {
2093 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2094 } else {
2095 const cricket::VideoContentDescription* video_desc =
2096 video_content->media_description()->as_video();
2097 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2098 }
deadbeeffaac4972015-11-12 15:33:07 -08002099 }
deadbeefab9b2d12015-10-14 11:33:11 -07002100 }
2101
2102 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002103 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002104 if (data_content) {
2105 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002106 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002107 if (rtc::starts_with(data_desc->protocol().data(),
2108 cricket::kMediaProtocolRtpPrefix)) {
2109 UpdateLocalRtpDataChannels(data_desc->streams());
2110 }
2111 }
2112
Steve Anton8a006912017-12-04 15:25:56 -08002113 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114}
2115
2116void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002117 SetSessionDescriptionObserver* observer,
2118 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002119 SetRemoteDescription(
2120 std::unique_ptr<SessionDescriptionInterface>(desc),
2121 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2122 new SetRemoteDescriptionObserverAdapter(this, observer)));
2123}
2124
2125void PeerConnection::SetRemoteDescription(
2126 std::unique_ptr<SessionDescriptionInterface> desc,
2127 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002128 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002129
nisse7ce109a2017-01-31 00:57:56 -08002130 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002131 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 return;
2133 }
Steve Anton8a006912017-12-04 15:25:56 -08002134
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002136 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002137 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 return;
2139 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002140
Steve Anton80dd7b52018-02-16 17:08:42 -08002141 // If a session error has occurred the PeerConnection is in a possibly
2142 // inconsistent state so fail right away.
2143 if (session_error() != SessionError::kNone) {
2144 std::string error_message = GetSessionErrorMsg();
2145 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2146 observer->OnSetRemoteDescriptionComplete(
2147 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2148 return;
2149 }
Steve Anton71439a62018-02-15 11:53:06 -08002150
Steve Antonba42e992018-04-09 14:10:01 -07002151 if (desc->GetType() == SdpType::kOffer) {
2152 // Report to UMA the format of the received offer.
2153 ReportSdpFormatReceived(*desc);
2154 }
2155
Steve Anton80dd7b52018-02-16 17:08:42 -08002156 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002157 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002158 std::string error_message = GetSetDescriptionErrorMessage(
2159 cricket::CS_REMOTE, desc->GetType(), error);
2160 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002161 observer->OnSetRemoteDescriptionComplete(
2162 RTCError(error.type(), std::move(error_message)));
2163 return;
2164 }
Steve Anton71439a62018-02-15 11:53:06 -08002165
Steve Anton80dd7b52018-02-16 17:08:42 -08002166 // Grab the description type before moving ownership to
2167 // ApplyRemoteDescription, which may destroy it before returning.
2168 const SdpType type = desc->GetType();
2169
2170 error = ApplyRemoteDescription(std::move(desc));
2171 // |desc| may be destroyed at this point.
2172
2173 if (!error.ok()) {
2174 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2175 // inconsistent state, so act conservatively here and set the session error
2176 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2177 SetSessionError(SessionError::kContent, error.message());
2178 std::string error_message =
2179 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2180 RTC_LOG(LS_ERROR) << error_message;
2181 observer->OnSetRemoteDescriptionComplete(
2182 RTCError(error.type(), std::move(error_message)));
2183 return;
2184 }
2185 RTC_DCHECK(remote_description());
2186
2187 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002188 // TODO(deadbeef): We already had to hop to the network thread for
2189 // MaybeStartGathering...
2190 network_thread()->Invoke<void>(
2191 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2192 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002193 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002194 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002195 }
2196
2197 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002198 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002199}
2200
2201RTCError PeerConnection::ApplyRemoteDescription(
2202 std::unique_ptr<SessionDescriptionInterface> desc) {
2203 RTC_DCHECK_RUN_ON(signaling_thread());
2204 RTC_DCHECK(desc);
2205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 // Update stats here so that we have the most recent stats for tracks and
2207 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002208 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002209
Steve Antondcc3c022017-12-22 16:02:54 -08002210 // Take a reference to the old remote description since it's used below to
2211 // compare against the new remote description. When setting the new remote
2212 // description, grab ownership of the replaced session description in case it
2213 // is the same as |old_remote_description|, to keep it alive for the duration
2214 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002215 const SessionDescriptionInterface* old_remote_description =
2216 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002217 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002218 SdpType type = desc->GetType();
2219 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002220 replaced_remote_description = pending_remote_description_
2221 ? std::move(pending_remote_description_)
2222 : std::move(current_remote_description_);
2223 current_remote_description_ = std::move(desc);
2224 pending_remote_description_ = nullptr;
2225 current_local_description_ = std::move(pending_local_description_);
2226 } else {
2227 replaced_remote_description = std::move(pending_remote_description_);
2228 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 }
Steve Anton8a006912017-12-04 15:25:56 -08002230 // The session description to apply now must be accessed by
2231 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002232 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002233
Zhi Huange830e682018-03-30 10:48:35 -07002234 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2235 if (!error.ok()) {
2236 return error;
2237 }
Steve Anton8a006912017-12-04 15:25:56 -08002238 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002239 if (IsUnifiedPlan()) {
2240 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002241 cricket::CS_REMOTE, *remote_description(), local_description(),
2242 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002243 if (!error.ok()) {
2244 return error;
2245 }
Steve Antondcc3c022017-12-22 16:02:54 -08002246 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002247 // Media channels will be created only when offer is set. These may use new
2248 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002249 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002250 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002251 // description is applied. Restore back to old description.
2252 RTCError error = CreateChannels(*remote_description()->description());
2253 if (!error.ok()) {
2254 return error;
2255 }
2256 }
Steve Antondcc3c022017-12-22 16:02:54 -08002257 // Remove unused channels if MediaContentDescription is rejected.
2258 RemoveUnusedChannels(remote_description()->description());
2259 }
Steve Anton8a006912017-12-04 15:25:56 -08002260
Zhi Huange830e682018-03-30 10:48:35 -07002261 // NOTE: Candidates allocation will be initiated only when
2262 // SetLocalDescription is called.
2263 error = UpdateSessionState(type, cricket::CS_REMOTE,
2264 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002265 if (!error.ok()) {
2266 return error;
2267 }
2268
2269 if (local_description() &&
2270 !UseCandidatesInSessionDescription(remote_description())) {
2271 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2272 }
2273
2274 if (old_remote_description) {
2275 for (const cricket::ContentInfo& content :
2276 old_remote_description->description()->contents()) {
2277 // Check if this new SessionDescription contains new ICE ufrag and
2278 // password that indicates the remote peer requests an ICE restart.
2279 // TODO(deadbeef): When we start storing both the current and pending
2280 // remote description, this should reset pending_ice_restarts and compare
2281 // against the current description.
2282 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2283 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002284 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002285 pending_ice_restarts_.insert(content.name);
2286 }
2287 } else {
2288 // We retain all received candidates only if ICE is not restarted.
2289 // When ICE is restarted, all previous candidates belong to an old
2290 // generation and should not be kept.
2291 // TODO(deadbeef): This goes against the W3C spec which says the remote
2292 // description should only contain candidates from the last set remote
2293 // description plus any candidates added since then. We should remove
2294 // this once we're sure it won't break anything.
2295 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2296 old_remote_description, content.name, mutable_remote_description());
2297 }
2298 }
2299 }
2300
2301 if (session_error() != SessionError::kNone) {
2302 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2303 }
2304
2305 // Set the the ICE connection state to connecting since the connection may
2306 // become writable with peer reflexive candidates before any remote candidate
2307 // is signaled.
2308 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2309 // is to have a new signal the indicates a change in checking state from the
2310 // transport and expose a new checking() member from transport that can be
2311 // read to determine the current checking state. The existing SignalConnecting
2312 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002313 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002314 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002315 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2316 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2317 }
2318
deadbeefab9b2d12015-10-14 11:33:11 -07002319 // If setting the description decided our SSL role, allocate any necessary
2320 // SCTP sids.
2321 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002322 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002323 AllocateSctpSids(role);
2324 }
2325
Steve Antondcc3c022017-12-22 16:02:54 -08002326 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002327 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002328 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002329 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002330 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002331 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002332 for (auto transceiver : transceivers_) {
2333 const ContentInfo* content =
2334 FindMediaSectionForTransceiver(transceiver, remote_description());
2335 if (!content) {
2336 continue;
2337 }
2338 const MediaContentDescription* media_desc = content->media_description();
2339 RtpTransceiverDirection local_direction =
2340 RtpTransceiverDirectionReversed(media_desc->direction());
2341 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2342 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2343 // transceiver's current direction is neither sendrecv nor recvonly,
2344 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002345 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002347 // The remote description has signaled the stream IDs.
2348 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002349 }
Steve Antondcc3c022017-12-22 16:02:54 -08002350 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002351 (!transceiver->fired_direction() ||
2352 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002353 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002354 << content->name << " (added to "
2355 << GetStreamIdsString(stream_ids) << ").";
2356
2357 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2358 for (const std::string& stream_id : stream_ids) {
2359 rtc::scoped_refptr<MediaStreamInterface> stream =
2360 remote_streams_->find(stream_id);
2361 if (!stream) {
2362 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2363 MediaStream::Create(stream_id));
2364 remote_streams_->AddStream(stream);
2365 added_streams.push_back(stream);
2366 }
2367 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002368 }
Steve Anton3172c032018-05-03 15:30:18 -07002369 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002370 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2371 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002372 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002373 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002374 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002375 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2376 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2377 // removal of a remote track for the media description, given transceiver,
2378 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002379 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002380 (transceiver->fired_direction() &&
2381 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2382 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2383 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002384 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002385 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2386 transceiver->internal()->set_fired_direction(local_direction);
2387 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2388 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002389 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002390 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2391 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002392 transceiver->internal()->set_current_direction(local_direction);
2393 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002394 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2395 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002396 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002397 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2398 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002399 transceiver->Stop();
2400 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002401 if (!content->rejected &&
2402 RtpTransceiverDirectionHasRecv(local_direction)) {
2403 // Set ssrc to 0 in the case of an unsignalled ssrc.
2404 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002405 if (!media_desc->streams().empty() &&
2406 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002407 ssrc = media_desc->streams()[0].first_ssrc();
2408 }
2409 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002410 }
Steve Antondcc3c022017-12-22 16:02:54 -08002411 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002412 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002413 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002414 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002415 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002416 observer->OnTrack(transceiver);
2417 observer->OnAddTrack(transceiver->receiver(),
2418 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002419 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002420 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002421 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002422 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002423 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002424 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002425 }
2426 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002427 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002428 }
Steve Antondcc3c022017-12-22 16:02:54 -08002429 }
2430
Henrik Boströmfdb92012017-11-09 19:55:44 +01002431 const cricket::ContentInfo* audio_content =
2432 GetFirstAudioContent(remote_description()->description());
2433 const cricket::ContentInfo* video_content =
2434 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002435 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002436 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002437 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002438 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002439 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002440 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002441
2442 // Check if the descriptions include streams, just in case the peer supports
2443 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002444 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002445 (audio_desc && !audio_desc->streams().empty()) ||
2446 (video_desc && !video_desc->streams().empty())) {
2447 remote_peer_supports_msid_ = true;
2448 }
deadbeefab9b2d12015-10-14 11:33:11 -07002449
2450 // We wait to signal new streams until we finish processing the description,
2451 // since only at that point will new streams have all their tracks.
2452 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2453
Steve Antondcc3c022017-12-22 16:02:54 -08002454 if (!IsUnifiedPlan()) {
2455 // TODO(steveanton): When removing RTP senders/receivers in response to a
2456 // rejected media section, there is some cleanup logic that expects the
2457 // voice/ video channel to still be set. But in this method the voice/video
2458 // channel would have been destroyed by the SetRemoteDescription caller
2459 // above so the cleanup that relies on them fails to run. The RemoveSenders
2460 // calls should be moved to right before the DestroyChannel calls to fix
2461 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002462
Steve Antondcc3c022017-12-22 16:02:54 -08002463 // Find all audio rtp streams and create corresponding remote AudioTracks
2464 // and MediaStreams.
2465 if (audio_content) {
2466 if (audio_content->rejected) {
2467 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2468 } else {
2469 bool default_audio_track_needed =
2470 !remote_peer_supports_msid_ &&
2471 RtpTransceiverDirectionHasSend(audio_desc->direction());
2472 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2473 default_audio_track_needed, audio_desc->type(),
2474 new_streams);
2475 }
deadbeeffaac4972015-11-12 15:33:07 -08002476 }
deadbeefab9b2d12015-10-14 11:33:11 -07002477
Steve Antondcc3c022017-12-22 16:02:54 -08002478 // Find all video rtp streams and create corresponding remote VideoTracks
2479 // and MediaStreams.
2480 if (video_content) {
2481 if (video_content->rejected) {
2482 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2483 } else {
2484 bool default_video_track_needed =
2485 !remote_peer_supports_msid_ &&
2486 RtpTransceiverDirectionHasSend(video_desc->direction());
2487 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2488 default_video_track_needed, video_desc->type(),
2489 new_streams);
2490 }
deadbeeffaac4972015-11-12 15:33:07 -08002491 }
deadbeefab9b2d12015-10-14 11:33:11 -07002492
Steve Antondcc3c022017-12-22 16:02:54 -08002493 // Update the DataChannels with the information from the remote peer.
2494 if (data_desc) {
2495 if (rtc::starts_with(data_desc->protocol().data(),
2496 cricket::kMediaProtocolRtpPrefix)) {
2497 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2498 }
deadbeefab9b2d12015-10-14 11:33:11 -07002499 }
deadbeefab9b2d12015-10-14 11:33:11 -07002500
Steve Antondcc3c022017-12-22 16:02:54 -08002501 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002502 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002503 for (size_t i = 0; i < new_streams->count(); ++i) {
2504 MediaStreamInterface* new_stream = new_streams->at(i);
2505 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002506 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002507 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2508 }
deadbeefab9b2d12015-10-14 11:33:11 -07002509
Steve Antondcc3c022017-12-22 16:02:54 -08002510 UpdateEndedRemoteMediaStreams();
2511 }
deadbeefab9b2d12015-10-14 11:33:11 -07002512
Steve Anton8a006912017-12-04 15:25:56 -08002513 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002514}
2515
Steve Anton0f5400a2018-07-17 14:25:36 -07002516void PeerConnection::ProcessRemovalOfRemoteTrack(
2517 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2518 transceiver,
2519 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2520 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2521 RTC_DCHECK(transceiver->mid());
2522 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2523 << *transceiver->mid();
2524 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2525 transceiver->internal()->receiver_internal()->streams();
2526 // This will remove the remote track from the streams.
2527 transceiver->internal()->receiver_internal()->set_stream_ids({});
2528 remove_list->push_back(transceiver);
2529 // Remove any streams that no longer have tracks.
2530 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2531 // of streams, see if the stream was removed by checking if this was the
2532 // last receiver with that stream ID.
2533 for (auto stream : media_streams) {
2534 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2535 remote_streams_->RemoveStream(stream);
2536 removed_streams->push_back(stream);
2537 }
2538 }
2539}
2540
Steve Antondcc3c022017-12-22 16:02:54 -08002541RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2542 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002543 const SessionDescriptionInterface& new_session,
2544 const SessionDescriptionInterface* old_local_description,
2545 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002546 RTC_DCHECK(IsUnifiedPlan());
2547
Steve Anton7464fca2018-01-19 11:10:37 -08002548 const cricket::ContentGroup* bundle_group = nullptr;
2549 if (new_session.GetType() == SdpType::kOffer) {
2550 auto bundle_group_or_error =
2551 GetEarlyBundleGroup(*new_session.description());
2552 if (!bundle_group_or_error.ok()) {
2553 return bundle_group_or_error.MoveError();
2554 }
2555 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002556 }
Steve Antondcc3c022017-12-22 16:02:54 -08002557
Steve Antondcc3c022017-12-22 16:02:54 -08002558 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002559 for (size_t i = 0; i < new_contents.size(); ++i) {
2560 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002561 cricket::MediaType media_type = new_content.media_description()->type();
2562 seen_mids_.insert(new_content.name);
2563 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2564 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002565 const cricket::ContentInfo* old_local_content = nullptr;
2566 if (old_local_description &&
2567 i < old_local_description->description()->contents().size()) {
2568 old_local_content =
2569 &old_local_description->description()->contents()[i];
2570 }
2571 const cricket::ContentInfo* old_remote_content = nullptr;
2572 if (old_remote_description &&
2573 i < old_remote_description->description()->contents().size()) {
2574 old_remote_content =
2575 &old_remote_description->description()->contents()[i];
2576 }
Steve Antondcc3c022017-12-22 16:02:54 -08002577 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002578 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2579 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002580 if (!transceiver_or_error.ok()) {
2581 return transceiver_or_error.MoveError();
2582 }
2583 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002584 RTCError error =
2585 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2586 if (!error.ok()) {
2587 return error;
2588 }
2589 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002590 if (GetDataMid() && new_content.name != *GetDataMid()) {
2591 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002592 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2593 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002594 continue;
2595 }
2596 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2597 if (!error.ok()) {
2598 return error;
2599 }
Steve Antondcc3c022017-12-22 16:02:54 -08002600 } else {
2601 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2602 "Unknown section type.");
2603 }
2604 }
2605
2606 return RTCError::OK();
2607}
2608
2609RTCError PeerConnection::UpdateTransceiverChannel(
2610 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2611 transceiver,
2612 const cricket::ContentInfo& content,
2613 const cricket::ContentGroup* bundle_group) {
2614 RTC_DCHECK(IsUnifiedPlan());
2615 RTC_DCHECK(transceiver);
2616 cricket::BaseChannel* channel = transceiver->internal()->channel();
2617 if (content.rejected) {
2618 if (channel) {
2619 transceiver->internal()->SetChannel(nullptr);
2620 DestroyBaseChannel(channel);
2621 }
2622 } else {
2623 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002624 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002625 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002626 } else {
Steve Anton69470252018-02-09 11:43:08 -08002627 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002628 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002629 }
2630 if (!channel) {
2631 LOG_AND_RETURN_ERROR(
2632 RTCErrorType::INTERNAL_ERROR,
2633 "Failed to create channel for mid=" + content.name);
2634 }
2635 transceiver->internal()->SetChannel(channel);
2636 }
2637 }
2638 return RTCError::OK();
2639}
2640
Steve Antonfa2260d2017-12-28 16:38:23 -08002641RTCError PeerConnection::UpdateDataChannel(
2642 cricket::ContentSource source,
2643 const cricket::ContentInfo& content,
2644 const cricket::ContentGroup* bundle_group) {
2645 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002646 // If data channels are disabled, ignore this media section. CreateAnswer
2647 // will take care of rejecting it.
2648 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002649 }
2650 if (content.rejected) {
2651 DestroyDataChannel();
2652 } else {
2653 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002654 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002655 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2656 "Failed to create data channel.");
2657 }
2658 }
2659 if (source == cricket::CS_REMOTE) {
2660 const MediaContentDescription* data_desc = content.media_description();
2661 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2662 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2663 }
2664 }
2665 }
2666 return RTCError::OK();
2667}
2668
Steve Antondcc3c022017-12-22 16:02:54 -08002669RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2670PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002671 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002672 size_t mline_index,
2673 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002674 const ContentInfo* old_local_content,
2675 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002676 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002677 // If this is an offer then the m= section might be recycled. If the m=
2678 // section is being recycled (defined as: rejected in the current local or
2679 // remote description and not rejected in new description), dissociate the
2680 // currently associated RtpTransceiver by setting its mid property to null,
2681 // and discard the mapping between the transceiver and its m= section index.
2682 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2683 old_remote_content)) {
2684 // We want to dissociate the transceiver that has the rejected mid.
2685 const std::string& old_mid =
2686 (old_local_content && old_local_content->rejected)
2687 ? old_local_content->name
2688 : old_remote_content->name;
2689 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002690 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002691 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2692 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002693 old_transceiver->internal()->set_mid(absl::nullopt);
2694 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002695 }
2696 }
2697 const MediaContentDescription* media_desc = content.media_description();
2698 auto transceiver = GetAssociatedTransceiver(content.name);
2699 if (source == cricket::CS_LOCAL) {
2700 // Find the RtpTransceiver that corresponds to this m= section, using the
2701 // mapping between transceivers and m= section indices established when
2702 // creating the offer.
2703 if (!transceiver) {
2704 transceiver = GetTransceiverByMLineIndex(mline_index);
2705 }
2706 if (!transceiver) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2708 "Unknown transceiver");
2709 }
2710 } else {
2711 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2712 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2713 // of the same type...
2714 if (!transceiver &&
2715 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2716 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2717 }
2718 // If no RtpTransceiver was found in the previous step, create one with a
2719 // recvonly direction.
2720 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002721 RTC_LOG(LS_INFO) << "Adding "
2722 << cricket::MediaTypeToString(media_desc->type())
2723 << " transceiver for MID=" << content.name
2724 << " at i=" << mline_index
2725 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002726 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002727 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002728 std::string receiver_id;
2729 if (!media_desc->streams().empty()) {
2730 receiver_id = media_desc->streams()[0].id;
2731 } else {
2732 receiver_id = rtc::CreateRandomUuid();
2733 }
2734 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002735 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002736 transceiver->internal()->set_direction(
2737 RtpTransceiverDirection::kRecvOnly);
2738 }
2739 }
2740 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002741 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002742 LOG_AND_RETURN_ERROR(
2743 RTCErrorType::INVALID_PARAMETER,
2744 "Transceiver type does not match media description type.");
2745 }
2746 // Associate the found or created RtpTransceiver with the m= section by
2747 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2748 // section, and establish a mapping between the transceiver and the index of
2749 // the m= section.
2750 transceiver->internal()->set_mid(content.name);
2751 transceiver->internal()->set_mline_index(mline_index);
2752 return std::move(transceiver);
2753}
2754
2755rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2756PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2757 RTC_DCHECK(IsUnifiedPlan());
2758 for (auto transceiver : transceivers_) {
2759 if (transceiver->mid() == mid) {
2760 return transceiver;
2761 }
2762 }
2763 return nullptr;
2764}
2765
2766rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2767PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2768 RTC_DCHECK(IsUnifiedPlan());
2769 for (auto transceiver : transceivers_) {
2770 if (transceiver->internal()->mline_index() == mline_index) {
2771 return transceiver;
2772 }
2773 }
2774 return nullptr;
2775}
2776
2777rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2778PeerConnection::FindAvailableTransceiverToReceive(
2779 cricket::MediaType media_type) const {
2780 RTC_DCHECK(IsUnifiedPlan());
2781 // From JSEP section 5.10 (Applying a Remote Description):
2782 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2783 // the same type that were added to the PeerConnection by addTrack and are not
2784 // associated with any m= section and are not stopped, find the first such
2785 // RtpTransceiver.
2786 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002787 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002788 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2789 !transceiver->stopped()) {
2790 return transceiver;
2791 }
2792 }
2793 return nullptr;
2794}
2795
Steve Antoned10bd92017-12-05 10:52:59 -08002796const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2797 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2798 transceiver,
2799 const SessionDescriptionInterface* sdesc) const {
2800 RTC_DCHECK(transceiver);
2801 RTC_DCHECK(sdesc);
2802 if (IsUnifiedPlan()) {
2803 if (!transceiver->internal()->mid()) {
2804 // This transceiver is not associated with a media section yet.
2805 return nullptr;
2806 }
2807 return sdesc->description()->GetContentByName(
2808 *transceiver->internal()->mid());
2809 } else {
2810 // Plan B only allows at most one audio and one video section, so use the
2811 // first media section of that type.
2812 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002813 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002814 }
2815}
2816
deadbeef46c73892016-11-16 19:42:04 -08002817PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2818 return configuration_;
2819}
2820
deadbeef293e9262017-01-11 12:28:30 -08002821bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2822 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002823 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002824 if (IsClosed()) {
2825 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2826 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2827 }
2828
Qingsi Wanga2d60672018-04-11 16:57:45 -07002829 // According to JSEP, after setLocalDescription, changing the candidate pool
2830 // size is not allowed, and changing the set of ICE servers will not result
2831 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002832 if (local_description() && configuration.ice_candidate_pool_size !=
2833 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002834 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2835 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002836 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002837 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002838
deadbeef293e9262017-01-11 12:28:30 -08002839 // The simplest (and most future-compatible) way to tell if the config was
2840 // modified in an invalid way is to copy each property we do support
2841 // modifying, then use operator==. There are far more properties we don't
2842 // support modifying than those we do, and more could be added.
2843 RTCConfiguration modified_config = configuration_;
2844 modified_config.servers = configuration.servers;
2845 modified_config.type = configuration.type;
2846 modified_config.ice_candidate_pool_size =
2847 configuration.ice_candidate_pool_size;
2848 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002849 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002850 modified_config.ice_check_interval_strong_connectivity =
2851 configuration.ice_check_interval_strong_connectivity;
2852 modified_config.ice_check_interval_weak_connectivity =
2853 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002854 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2855 modified_config.ice_unwritable_min_checks =
2856 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002857 modified_config.stun_candidate_keepalive_interval =
2858 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002859 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002860 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002861 modified_config.active_reset_srtp_params =
2862 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002863 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002864 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002865 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2866 }
2867
Steve Anton038834f2017-07-14 15:59:59 -07002868 // Validate the modified configuration.
2869 RTCError validate_error = ValidateConfiguration(modified_config);
2870 if (!validate_error.ok()) {
2871 return SafeSetError(std::move(validate_error), error);
2872 }
2873
deadbeef293e9262017-01-11 12:28:30 -08002874 // Note that this isn't possible through chromium, since it's an unsigned
2875 // short in WebIDL.
2876 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002877 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002878 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2879 }
2880
2881 // Parse ICE servers before hopping to network thread.
2882 cricket::ServerAddresses stun_servers;
2883 std::vector<cricket::RelayServerConfig> turn_servers;
2884 RTCErrorType parse_error =
2885 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2886 if (parse_error != RTCErrorType::NONE) {
2887 return SafeSetError(parse_error, error);
2888 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002889 // Note if STUN or TURN servers were supplied.
2890 if (!stun_servers.empty()) {
2891 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2892 }
2893 if (!turn_servers.empty()) {
2894 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2895 }
deadbeef293e9262017-01-11 12:28:30 -08002896
2897 // In theory this shouldn't fail.
2898 if (!network_thread()->Invoke<bool>(
2899 RTC_FROM_HERE,
2900 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2901 stun_servers, turn_servers, modified_config.type,
2902 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002903 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002904 modified_config.turn_customizer,
2905 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002906 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002907 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2908 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002909
deadbeefd1a38b52016-12-10 13:15:33 -08002910 // As described in JSEP, calling setConfiguration with new ICE servers or
2911 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2912 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002913 if (modified_config.servers != configuration_.servers ||
2914 modified_config.type != configuration_.type ||
2915 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002916 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002917 }
skvladd1f5fda2017-02-03 16:54:05 -08002918
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002919 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002920
Zhi Huangb57e1692018-06-12 11:41:11 -07002921 if (configuration_.active_reset_srtp_params !=
2922 modified_config.active_reset_srtp_params) {
2923 transport_controller_->SetActiveResetSrtpParams(
2924 modified_config.active_reset_srtp_params);
2925 }
2926
deadbeef293e9262017-01-11 12:28:30 -08002927 configuration_ = modified_config;
2928 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002929}
2930
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931bool PeerConnection::AddIceCandidate(
2932 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002933 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002934 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002935 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002936 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002937 return false;
2938 }
Steve Antond25da372017-11-06 14:50:29 -08002939
2940 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002941 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002942 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002943 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002944 return false;
2945 }
2946
2947 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002948 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002949 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002950 return false;
2951 }
2952
2953 bool valid = false;
2954 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2955 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002956 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002957 return false;
2958 }
2959
2960 // Add this candidate to the remote session description.
2961 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002962 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002963 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002964 return false;
2965 }
2966
2967 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002968 bool result = UseCandidate(ice_candidate);
2969 if (result) {
2970 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2971 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2972 } else {
2973 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2974 }
2975 return result;
Steve Antond25da372017-11-06 14:50:29 -08002976 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002977 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002978 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002979 return true;
2980 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981}
2982
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002983bool PeerConnection::RemoveIceCandidates(
2984 const std::vector<cricket::Candidate>& candidates) {
2985 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002986 if (IsClosed()) {
2987 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2988 return false;
2989 }
2990
Steve Antond25da372017-11-06 14:50:29 -08002991 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002992 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2993 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002994 return false;
2995 }
2996
2997 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002998 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002999 return false;
3000 }
3001
3002 size_t number_removed =
3003 mutable_remote_description()->RemoveCandidates(candidates);
3004 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003005 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003006 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003007 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003008 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003009 }
3010
3011 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003012 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3013 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR)
3015 << "RemoveIceCandidates: Error when removing remote candidates: "
3016 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003017 }
3018 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003019}
3020
Niels Möller0c4f7be2018-05-07 14:01:37 +02003021RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003022 if (!worker_thread()->IsCurrent()) {
3023 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003024 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003025 }
3026
Niels Möller0c4f7be2018-05-07 14:01:37 +02003027 const bool has_min = bitrate.min_bitrate_bps.has_value();
3028 const bool has_start = bitrate.start_bitrate_bps.has_value();
3029 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003030 if (has_min && *bitrate.min_bitrate_bps < 0) {
3031 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3032 "min_bitrate_bps <= 0");
3033 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003034 if (has_start) {
3035 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003036 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003037 "start_bitrate_bps < min_bitrate_bps");
3038 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003039 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3040 "curent_bitrate_bps < 0");
3041 }
3042 }
3043 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003044 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003045 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003046 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003047 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3049 "max_bitrate_bps < min_bitrate_bps");
3050 } else if (*bitrate.max_bitrate_bps < 0) {
3051 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3052 "max_bitrate_bps < 0");
3053 }
3054 }
3055
zstein4b979802017-06-02 14:37:37 -07003056 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003057 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003058
3059 return RTCError::OK();
3060}
3061
Alex Narest78609d52017-10-20 10:37:47 +02003062void PeerConnection::SetBitrateAllocationStrategy(
3063 std::unique_ptr<rtc::BitrateAllocationStrategy>
3064 bitrate_allocation_strategy) {
3065 rtc::Thread* worker_thread = factory_->worker_thread();
3066 if (!worker_thread->IsCurrent()) {
3067 rtc::BitrateAllocationStrategy* strategy_raw =
3068 bitrate_allocation_strategy.release();
3069 auto functor = [this, strategy_raw]() {
3070 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003071 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003072 };
3073 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3074 return;
3075 }
3076 RTC_DCHECK(call_.get());
3077 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3078}
3079
henrika5f6bf242017-11-01 11:06:56 +01003080void PeerConnection::SetAudioPlayout(bool playout) {
3081 if (!worker_thread()->IsCurrent()) {
3082 worker_thread()->Invoke<void>(
3083 RTC_FROM_HERE,
3084 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3085 return;
3086 }
3087 auto audio_state =
3088 factory_->channel_manager()->media_engine()->GetAudioState();
3089 audio_state->SetPlayout(playout);
3090}
3091
3092void PeerConnection::SetAudioRecording(bool recording) {
3093 if (!worker_thread()->IsCurrent()) {
3094 worker_thread()->Invoke<void>(
3095 RTC_FROM_HERE,
3096 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3097 return;
3098 }
3099 auto audio_state =
3100 factory_->channel_manager()->media_engine()->GetAudioState();
3101 audio_state->SetRecording(recording);
3102}
3103
Steve Anton8c0f7a72017-10-03 10:03:10 -07003104std::unique_ptr<rtc::SSLCertificate>
3105PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003106 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3107 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003108 return nullptr;
3109 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003110 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003111}
3112
Zhi Huang70b820f2018-01-27 14:16:15 -08003113std::unique_ptr<rtc::SSLCertChain>
3114PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003115 auto audio_transceiver = GetFirstAudioTransceiver();
3116 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003117 return nullptr;
3118 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003119 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003120 audio_transceiver->internal()->channel()->transport_name());
3121}
3122
3123rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3124PeerConnection::GetFirstAudioTransceiver() const {
3125 for (auto transceiver : transceivers_) {
3126 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3127 return transceiver;
3128 }
3129 }
3130 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003131}
3132
ivoc14d5dbe2016-07-04 07:06:55 -07003133bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3134 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003135 // TODO(eladalon): It would be better to not allow negative values into PC.
3136 const size_t max_size = (max_size_bytes < 0)
3137 ? RtcEventLog::kUnlimitedOutput
3138 : rtc::saturated_cast<size_t>(max_size_bytes);
3139 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003140 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003141 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003142}
3143
Bjorn Tereliusde939432017-11-20 17:38:14 +01003144bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3145 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003146 // TODO(eladalon): In C++14, this can be done with a lambda.
3147 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003148 bool operator()() {
3149 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3150 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003151 PeerConnection* const pc;
3152 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003153 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003154 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003155 return worker_thread()->Invoke<bool>(
3156 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003157}
3158
3159void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003160 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003161 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3162}
3163
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003164const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003165 return pending_local_description_ ? pending_local_description_.get()
3166 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167}
3168
3169const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003170 return pending_remote_description_ ? pending_remote_description_.get()
3171 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172}
3173
deadbeeffe4a8a42016-12-20 17:56:17 -08003174const SessionDescriptionInterface* PeerConnection::current_local_description()
3175 const {
Steve Anton75737c02017-11-06 10:37:17 -08003176 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003177}
3178
3179const SessionDescriptionInterface* PeerConnection::current_remote_description()
3180 const {
Steve Anton75737c02017-11-06 10:37:17 -08003181 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003182}
3183
3184const SessionDescriptionInterface* PeerConnection::pending_local_description()
3185 const {
Steve Anton75737c02017-11-06 10:37:17 -08003186 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003187}
3188
3189const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3190 const {
Steve Anton75737c02017-11-06 10:37:17 -08003191 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003192}
3193
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003195 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003196 // Update stats here so that we have the most recent stats for tracks and
3197 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003198 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003199
Steve Anton75737c02017-11-06 10:37:17 -08003200 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003201 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003202
Steve Anton8af21862017-12-15 11:20:13 -08003203 for (auto transceiver : transceivers_) {
3204 transceiver->Stop();
3205 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003206
3207 // Ensure that all asynchronous stats requests are completed before destroying
3208 // the transport controller below.
3209 if (stats_collector_) {
3210 stats_collector_->WaitForPendingRequest();
3211 }
3212
3213 // Don't destroy BaseChannels until after stats has been cleaned up so that
3214 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003215 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003216
Qingsi Wang93a84392018-01-30 17:13:09 -08003217 // The event log is used in the transport controller, which must be outlived
3218 // by the former. CreateOffer by the peer connection is implemented
3219 // asynchronously and if the peer connection is closed without resetting the
3220 // WebRTC session description factory, the session description factory would
3221 // call the transport controller.
3222 webrtc_session_desc_factory_.reset();
3223 transport_controller_.reset();
3224
deadbeef42a42632017-03-10 15:18:00 -08003225 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003226 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3227 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003228
Steve Anton978b8762017-09-29 12:15:02 -07003229 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003230 call_.reset();
3231 // The event log must outlive call (and any other object that uses it).
3232 event_log_.reset();
3233 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003234 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003235 // The .h file says that observer can be discarded after close() returns.
3236 // Make sure this is true.
3237 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238}
3239
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003240void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003241 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3243 SetSessionDescriptionMsg* param =
3244 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3245 param->observer->OnSuccess();
3246 delete param;
3247 break;
3248 }
3249 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3250 SetSessionDescriptionMsg* param =
3251 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003252 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 delete param;
3254 break;
3255 }
deadbeefab9b2d12015-10-14 11:33:11 -07003256 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3257 CreateSessionDescriptionMsg* param =
3258 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003259 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003260 delete param;
3261 break;
3262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 case MSG_GETSTATS: {
3264 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003265 StatsReports reports;
3266 stats_->GetStats(param->track, &reports);
3267 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003268 delete param;
3269 break;
3270 }
deadbeefbd292462015-12-14 18:15:29 -08003271 case MSG_FREE_DATACHANNELS: {
3272 sctp_data_channels_to_free_.clear();
3273 break;
3274 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003275 case MSG_REPORT_USAGE_PATTERN: {
3276 ReportUsagePattern();
3277 break;
3278 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003280 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281 break;
3282 }
3283}
3284
Steve Antonafb0bb72018-02-20 11:35:37 -08003285cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3286 RTC_DCHECK(!IsUnifiedPlan());
3287 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3288 GetAudioTransceiver()->internal()->channel());
3289 if (voice_channel) {
3290 return voice_channel->media_channel();
3291 } else {
3292 return nullptr;
3293 }
3294}
3295
3296cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3297 RTC_DCHECK(!IsUnifiedPlan());
3298 auto* video_channel = static_cast<cricket::VideoChannel*>(
3299 GetVideoTransceiver()->internal()->channel());
3300 if (video_channel) {
3301 return video_channel->media_channel();
3302 } else {
3303 return nullptr;
3304 }
3305}
3306
Steve Anton4171afb2017-11-20 10:20:22 -08003307void PeerConnection::CreateAudioReceiver(
3308 MediaStreamInterface* stream,
3309 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003310 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3311 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003312 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3313 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003314 auto* audio_receiver = new AudioRtpReceiver(
3315 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003316 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003317 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3318 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3319 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003320 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003321 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003322 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323}
3324
Steve Anton4171afb2017-11-20 10:20:22 -08003325void PeerConnection::CreateVideoReceiver(
3326 MediaStreamInterface* stream,
3327 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003328 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3329 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003330 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3331 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003332 auto* video_receiver = new VideoRtpReceiver(
3333 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003334 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003335 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3336 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3337 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003338 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003339 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003340 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341}
3342
deadbeef70ab1a12015-09-28 16:53:55 -07003343// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3344// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003345rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003346 const RtpSenderInfo& remote_sender_info) {
3347 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3348 if (!receiver) {
3349 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3350 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003351 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003352 }
Steve Anton4171afb2017-11-20 10:20:22 -08003353 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3354 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3355 } else {
3356 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3357 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003358 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003359}
3360
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003361void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3362 MediaStreamInterface* stream) {
3363 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003364 RTC_DCHECK(track);
3365 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003366 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003367 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003368 // We already have a sender for this track, so just change the stream_id
3369 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003370 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003371 return;
3372 }
3373
3374 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003375 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3376 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003377 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003378 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003379 // If the sender has already been configured in SDP, we call SetSsrc,
3380 // which will connect the sender to the underlying transport. This can
3381 // occur if a local session description that contains the ID of the sender
3382 // is set before AddStream is called. It can also occur if the local
3383 // session description is not changed and RemoveStream is called, and
3384 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003385 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003386 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003387 if (sender_info) {
3388 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003389 }
3390}
3391
3392// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3393// indefinitely, when we have unified plan SDP.
3394void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3395 MediaStreamInterface* stream) {
3396 RTC_DCHECK(!IsClosed());
3397 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003398 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003399 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3400 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003401 return;
3402 }
Steve Anton4171afb2017-11-20 10:20:22 -08003403 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003404}
3405
3406void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3407 MediaStreamInterface* stream) {
3408 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003409 RTC_DCHECK(track);
3410 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003411 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003412 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003413 // We already have a sender for this track, so just change the stream_id
3414 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003415 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003416 return;
3417 }
3418
3419 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003420 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3421 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003422 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003423 GetVideoTransceiver()->internal()->AddSender(new_sender);
3424 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003425 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003426 if (sender_info) {
3427 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003428 }
3429}
3430
3431void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3432 MediaStreamInterface* stream) {
3433 RTC_DCHECK(!IsClosed());
3434 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003435 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003436 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3437 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438 return;
3439 }
Steve Anton4171afb2017-11-20 10:20:22 -08003440 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003441}
3442
Steve Antonba818672017-11-06 10:21:57 -08003443void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003444 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003445 if (ice_connection_state_ == new_state) {
3446 return;
3447 }
3448
deadbeefcbecd352015-09-23 11:50:27 -07003449 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003450 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003451 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003452 return;
3453 }
Steve Antonba818672017-11-06 10:21:57 -08003454
Mirko Bonadei675513b2017-11-09 11:09:25 +01003455 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3456 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003457 RTC_DCHECK(ice_connection_state_ !=
3458 PeerConnectionInterface::kIceConnectionClosed);
3459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003461 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462}
3463
3464void PeerConnection::OnIceGatheringChange(
3465 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003466 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467 if (IsClosed()) {
3468 return;
3469 }
3470 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003471 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003472}
3473
jbauch81bf7b02017-03-25 08:31:12 -07003474void PeerConnection::OnIceCandidate(
3475 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003476 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003477 if (IsClosed()) {
3478 return;
3479 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003480 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003481 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3482 candidate->candidate().address().IsPrivateIP()) {
3483 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3484 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003485 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003486}
3487
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003488void PeerConnection::OnIceCandidatesRemoved(
3489 const std::vector<cricket::Candidate>& candidates) {
3490 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003491 if (IsClosed()) {
3492 return;
3493 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003494 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003495}
3496
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497void PeerConnection::ChangeSignalingState(
3498 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003499 RTC_DCHECK(signaling_thread()->IsCurrent());
3500 if (signaling_state_ == signaling_state) {
3501 return;
3502 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003503 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3504 << GetSignalingStateString(signaling_state_)
3505 << " New state: "
3506 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003507 signaling_state_ = signaling_state;
3508 if (signaling_state == kClosed) {
3509 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003510 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003511 if (ice_gathering_state_ != kIceGatheringComplete) {
3512 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003513 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003514 }
3515 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003516 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517}
3518
deadbeefeb459812015-12-15 19:24:43 -08003519void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3520 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003521 if (IsClosed()) {
3522 return;
3523 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003524 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003525 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003526}
3527
deadbeefeb459812015-12-15 19:24:43 -08003528void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3529 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003530 if (IsClosed()) {
3531 return;
3532 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003533 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003534 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003535}
3536
3537void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3538 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003539 if (IsClosed()) {
3540 return;
3541 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003542 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003543 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003544}
3545
3546void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3547 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003548 if (IsClosed()) {
3549 return;
3550 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003551 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003552 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003553}
3554
Henrik Boström31638672017-11-23 17:48:32 +01003555void PeerConnection::PostSetSessionDescriptionSuccess(
3556 SetSessionDescriptionObserver* observer) {
3557 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3558 signaling_thread()->Post(RTC_FROM_HERE, this,
3559 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3560}
3561
deadbeefab9b2d12015-10-14 11:33:11 -07003562void PeerConnection::PostSetSessionDescriptionFailure(
3563 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003564 RTCError&& error) {
3565 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003566 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003567 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003568 signaling_thread()->Post(RTC_FROM_HERE, this,
3569 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003570}
3571
3572void PeerConnection::PostCreateSessionDescriptionFailure(
3573 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003574 RTCError error) {
3575 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003576 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003577 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003578 signaling_thread()->Post(RTC_FROM_HERE, this,
3579 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003580}
3581
zhihuang1c378ed2017-08-17 14:10:50 -07003582void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003583 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003584 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003585 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003586
Steve Antondcc3c022017-12-22 16:02:54 -08003587 if (IsUnifiedPlan()) {
3588 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3589 } else {
3590 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3591 }
3592
Steve Antonfa2260d2017-12-28 16:38:23 -08003593 // Intentionally unset the data channel type for RTP data channel with the
3594 // second condition. Otherwise the RTP data channels would be successfully
3595 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3596 // when building with chromium. We want to leave RTP data channels broken, so
3597 // people won't try to use them.
3598 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3599 session_options->data_channel_type = data_channel_type();
3600 }
3601
Steve Antondcc3c022017-12-22 16:02:54 -08003602 // Apply ICE restart flag and renomination flag.
3603 for (auto& options : session_options->media_description_options) {
3604 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3605 options.transport_options.enable_ice_renomination =
3606 configuration_.enable_ice_renomination;
3607 }
3608
3609 session_options->rtcp_cname = rtcp_cname_;
3610 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003611 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003612}
3613
3614void PeerConnection::GetOptionsForPlanBOffer(
3615 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3616 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003617 // Figure out transceiver directional preferences.
3618 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3619 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3620
3621 // By default, generate sendrecv/recvonly m= sections.
3622 bool recv_audio = true;
3623 bool recv_video = true;
3624
3625 // By default, only offer a new m= section if we have media to send with it.
3626 bool offer_new_audio_description = send_audio;
3627 bool offer_new_video_description = send_video;
3628 bool offer_new_data_description = HasDataChannels();
3629
3630 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003631 if (offer_answer_options.offer_to_receive_audio !=
3632 RTCOfferAnswerOptions::kUndefined) {
3633 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003634 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003635 offer_new_audio_description ||
3636 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003637 }
Steve Antondcc3c022017-12-22 16:02:54 -08003638 if (offer_answer_options.offer_to_receive_video !=
3639 RTCOfferAnswerOptions::kUndefined) {
3640 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003641 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003642 offer_new_video_description ||
3643 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003644 }
3645
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003646 absl::optional<size_t> audio_index;
3647 absl::optional<size_t> video_index;
3648 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003649 // If a current description exists, generate m= sections in the same order,
3650 // using the first audio/video/data section that appears and rejecting
3651 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003652 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003653 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003654 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003655 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3656 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3657 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003658 }
3659
zhihuang1c378ed2017-08-17 14:10:50 -07003660 // Add audio/video/data m= sections to the end if needed.
3661 if (!audio_index && offer_new_audio_description) {
3662 session_options->media_description_options.push_back(
3663 cricket::MediaDescriptionOptions(
3664 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003665 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3666 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003667 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003668 }
zhihuang1c378ed2017-08-17 14:10:50 -07003669 if (!video_index && offer_new_video_description) {
3670 session_options->media_description_options.push_back(
3671 cricket::MediaDescriptionOptions(
3672 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003673 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3674 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003675 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003676 }
zhihuang1c378ed2017-08-17 14:10:50 -07003677 if (!data_index && offer_new_data_description) {
3678 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003679 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003680 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003681 }
3682
3683 cricket::MediaDescriptionOptions* audio_media_description_options =
3684 !audio_index ? nullptr
3685 : &session_options->media_description_options[*audio_index];
3686 cricket::MediaDescriptionOptions* video_media_description_options =
3687 !video_index ? nullptr
3688 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003689
Steve Anton4171afb2017-11-20 10:20:22 -08003690 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003691 video_media_description_options,
3692 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003693}
3694
3695// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3696// and return a reference to it.
3697// Generated MIDs should be no more than 3 bytes long to take up less space in
3698// the RTP packet.
3699static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3700 RTC_DCHECK(used_mids);
3701 // We're boring: just generate MIDs 0, 1, 2, ...
3702 size_t i = 0;
3703 std::set<std::string>::iterator it;
3704 bool inserted;
3705 do {
3706 std::string mid = rtc::ToString(i++);
3707 auto insert_result = used_mids->insert(mid);
3708 it = insert_result.first;
3709 inserted = insert_result.second;
3710 } while (!inserted);
3711 return *it;
3712}
3713
3714static cricket::MediaDescriptionOptions
3715GetMediaDescriptionOptionsForTransceiver(
3716 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3717 transceiver,
3718 const std::string& mid) {
3719 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003720 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003721 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003722 // This behavior is specified in JSEP. The gist is that:
3723 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3724 // sendrecv.
3725 // 2. If the MSID is included, then it must be included in any subsequent
3726 // offer/answer exactly the same until the RtpTransceiver is stopped.
3727 if (!transceiver->stopped() &&
3728 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3729 transceiver->internal()->has_ever_been_used_to_send())) {
3730 cricket::SenderOptions sender_options;
3731 sender_options.track_id = transceiver->sender()->id();
3732 sender_options.stream_ids = transceiver->sender()->stream_ids();
3733 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3734 // set in the RTP parameters when the transceiver was added.
3735 sender_options.num_sim_layers = 1;
3736 media_description_options.sender_options.push_back(sender_options);
3737 }
Steve Antondcc3c022017-12-22 16:02:54 -08003738 return media_description_options;
3739}
3740
3741void PeerConnection::GetOptionsForUnifiedPlanOffer(
3742 const RTCOfferAnswerOptions& offer_answer_options,
3743 cricket::MediaSessionOptions* session_options) {
3744 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3745 // Offers) and 5.2.2 (Subsequent Offers).
3746 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3747 const ContentInfos& local_contents =
3748 (local_description() ? local_description()->description()->contents()
3749 : ContentInfos());
3750 const ContentInfos& remote_contents =
3751 (remote_description() ? remote_description()->description()->contents()
3752 : ContentInfos());
3753 // The mline indices that can be recycled. New transceivers should reuse these
3754 // slots first.
3755 std::queue<size_t> recycleable_mline_indices;
3756 // Track the MIDs used in previous offer/answer exchanges and the current
3757 // offer so that new, unique MIDs are generated.
3758 std::set<std::string> used_mids = seen_mids_;
3759 // First, go through each media section that exists in either the local or
3760 // remote description and generate a media section in this offer for the
3761 // associated transceiver. If a media section can be recycled, generate a
3762 // default, rejected media section here that can be later overwritten.
3763 for (size_t i = 0;
3764 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3765 // Either |local_content| or |remote_content| is non-null.
3766 const ContentInfo* local_content =
3767 (i < local_contents.size() ? &local_contents[i] : nullptr);
3768 const ContentInfo* remote_content =
3769 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3770 bool had_been_rejected = (local_content && local_content->rejected) ||
3771 (remote_content && remote_content->rejected);
3772 const std::string& mid =
3773 (local_content ? local_content->name : remote_content->name);
3774 cricket::MediaType media_type =
3775 (local_content ? local_content->media_description()->type()
3776 : remote_content->media_description()->type());
3777 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3778 media_type == cricket::MEDIA_TYPE_VIDEO) {
3779 auto transceiver = GetAssociatedTransceiver(mid);
3780 RTC_CHECK(transceiver);
3781 // A media section is considered eligible for recycling if it is marked as
3782 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003783 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003784 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003785 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3786 RtpTransceiverDirection::kInactive,
3787 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003788 recycleable_mline_indices.push(i);
3789 } else {
3790 session_options->media_description_options.push_back(
3791 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3792 // CreateOffer shouldn't really cause any state changes in
3793 // PeerConnection, but we need a way to match new transceivers to new
3794 // media sections in SetLocalDescription and JSEP specifies this is done
3795 // by recording the index of the media section generated for the
3796 // transceiver in the offer.
3797 transceiver->internal()->set_mline_index(i);
3798 }
3799 } else {
3800 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003801 RTC_CHECK(GetDataMid());
3802 if (had_been_rejected || mid != *GetDataMid()) {
3803 session_options->media_description_options.push_back(
3804 GetMediaDescriptionOptionsForRejectedData(mid));
3805 } else {
3806 session_options->media_description_options.push_back(
3807 GetMediaDescriptionOptionsForActiveData(mid));
3808 }
Steve Antondcc3c022017-12-22 16:02:54 -08003809 }
3810 }
3811 // Next, look for transceivers that are newly added (that is, are not stopped
3812 // and not associated). Reuse media sections marked as recyclable first,
3813 // otherwise append to the end of the offer. New media sections should be
3814 // added in the order they were added to the PeerConnection.
3815 for (auto transceiver : transceivers_) {
3816 if (transceiver->mid() || transceiver->stopped()) {
3817 continue;
3818 }
3819 size_t mline_index;
3820 if (!recycleable_mline_indices.empty()) {
3821 mline_index = recycleable_mline_indices.front();
3822 recycleable_mline_indices.pop();
3823 session_options->media_description_options[mline_index] =
3824 GetMediaDescriptionOptionsForTransceiver(transceiver,
3825 AllocateMid(&used_mids));
3826 } else {
3827 mline_index = session_options->media_description_options.size();
3828 session_options->media_description_options.push_back(
3829 GetMediaDescriptionOptionsForTransceiver(transceiver,
3830 AllocateMid(&used_mids)));
3831 }
3832 // See comment above for why CreateOffer changes the transceiver's state.
3833 transceiver->internal()->set_mline_index(mline_index);
3834 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003835 // Lastly, add a m-section if we have local data channels and an m section
3836 // does not already exist.
3837 if (!GetDataMid() && HasDataChannels()) {
3838 session_options->media_description_options.push_back(
3839 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3840 }
Steve Antondcc3c022017-12-22 16:02:54 -08003841}
3842
3843void PeerConnection::GetOptionsForAnswer(
3844 const RTCOfferAnswerOptions& offer_answer_options,
3845 cricket::MediaSessionOptions* session_options) {
3846 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3847
3848 if (IsUnifiedPlan()) {
3849 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3850 } else {
3851 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3852 }
3853
Steve Antonfa2260d2017-12-28 16:38:23 -08003854 // Intentionally unset the data channel type for RTP data channel. Otherwise
3855 // the RTP data channels would be successfully negotiated by default and the
3856 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3857 // We want to leave RTP data channels broken, so people won't try to use them.
3858 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3859 session_options->data_channel_type = data_channel_type();
3860 }
3861
Steve Antondcc3c022017-12-22 16:02:54 -08003862 // Apply ICE renomination flag.
3863 for (auto& options : session_options->media_description_options) {
3864 options.transport_options.enable_ice_renomination =
3865 configuration_.enable_ice_renomination;
3866 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003867
3868 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003869 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003870 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003871}
3872
Steve Antondcc3c022017-12-22 16:02:54 -08003873void PeerConnection::GetOptionsForPlanBAnswer(
3874 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003875 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003876 // Figure out transceiver directional preferences.
3877 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3878 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3879
3880 // By default, generate sendrecv/recvonly m= sections. The direction is also
3881 // restricted by the direction in the offer.
3882 bool recv_audio = true;
3883 bool recv_video = true;
3884
3885 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003886 if (offer_answer_options.offer_to_receive_audio !=
3887 RTCOfferAnswerOptions::kUndefined) {
3888 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003889 }
Steve Antondcc3c022017-12-22 16:02:54 -08003890 if (offer_answer_options.offer_to_receive_video !=
3891 RTCOfferAnswerOptions::kUndefined) {
3892 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003893 }
3894
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003895 absl::optional<size_t> audio_index;
3896 absl::optional<size_t> video_index;
3897 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003898
3899 // Generate m= sections that match those in the offer.
3900 // Note that mediasession.cc will handle intersection our preferred
3901 // direction with the offered direction.
3902 GenerateMediaDescriptionOptions(
3903 remote_description(),
3904 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3905 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3906 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003907
3908 cricket::MediaDescriptionOptions* audio_media_description_options =
3909 !audio_index ? nullptr
3910 : &session_options->media_description_options[*audio_index];
3911 cricket::MediaDescriptionOptions* video_media_description_options =
3912 !video_index ? nullptr
3913 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003914
Steve Anton4171afb2017-11-20 10:20:22 -08003915 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003916 video_media_description_options,
3917 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003918}
zhihuangaf388472016-11-02 16:49:48 -07003919
Steve Antondcc3c022017-12-22 16:02:54 -08003920void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3921 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3922 cricket::MediaSessionOptions* session_options) {
3923 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3924 // Answers) and 5.3.2 (Subsequent Answers).
3925 RTC_DCHECK(remote_description());
3926 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3927 for (const ContentInfo& content :
3928 remote_description()->description()->contents()) {
3929 cricket::MediaType media_type = content.media_description()->type();
3930 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3931 media_type == cricket::MEDIA_TYPE_VIDEO) {
3932 auto transceiver = GetAssociatedTransceiver(content.name);
3933 RTC_CHECK(transceiver);
3934 session_options->media_description_options.push_back(
3935 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3936 } else {
3937 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003938 // Reject all data sections if data channels are disabled.
3939 // Reject a data section if it has already been rejected.
3940 // Reject all data sections except for the first one.
3941 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3942 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003943 session_options->media_description_options.push_back(
3944 GetMediaDescriptionOptionsForRejectedData(content.name));
3945 } else {
3946 session_options->media_description_options.push_back(
3947 GetMediaDescriptionOptionsForActiveData(content.name));
3948 }
Steve Antondcc3c022017-12-22 16:02:54 -08003949 }
3950 }
htaa2a49d92016-03-04 02:51:39 -08003951}
3952
zhihuang1c378ed2017-08-17 14:10:50 -07003953void PeerConnection::GenerateMediaDescriptionOptions(
3954 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003955 RtpTransceiverDirection audio_direction,
3956 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003957 absl::optional<size_t>* audio_index,
3958 absl::optional<size_t>* video_index,
3959 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003960 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003961 for (const cricket::ContentInfo& content :
3962 session_desc->description()->contents()) {
3963 if (IsAudioContent(&content)) {
3964 // If we already have an audio m= section, reject this extra one.
3965 if (*audio_index) {
3966 session_options->media_description_options.push_back(
3967 cricket::MediaDescriptionOptions(
3968 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003969 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003970 } else {
3971 session_options->media_description_options.push_back(
3972 cricket::MediaDescriptionOptions(
3973 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003974 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003975 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003976 }
3977 } else if (IsVideoContent(&content)) {
3978 // If we already have an video m= section, reject this extra one.
3979 if (*video_index) {
3980 session_options->media_description_options.push_back(
3981 cricket::MediaDescriptionOptions(
3982 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003983 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003984 } else {
3985 session_options->media_description_options.push_back(
3986 cricket::MediaDescriptionOptions(
3987 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003988 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003989 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003990 }
3991 } else {
3992 RTC_DCHECK(IsDataContent(&content));
3993 // If we already have an data m= section, reject this extra one.
3994 if (*data_index) {
3995 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003996 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003997 } else {
3998 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003999 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004000 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004001 }
4002 }
htaa2a49d92016-03-04 02:51:39 -08004003 }
deadbeefab9b2d12015-10-14 11:33:11 -07004004}
4005
Steve Antonfa2260d2017-12-28 16:38:23 -08004006cricket::MediaDescriptionOptions
4007PeerConnection::GetMediaDescriptionOptionsForActiveData(
4008 const std::string& mid) const {
4009 // Direction for data sections is meaningless, but legacy endpoints might
4010 // expect sendrecv.
4011 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4012 RtpTransceiverDirection::kSendRecv,
4013 /*stopped=*/false);
4014 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4015 return options;
4016}
4017
4018cricket::MediaDescriptionOptions
4019PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4020 const std::string& mid) const {
4021 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4022 RtpTransceiverDirection::kInactive,
4023 /*stopped=*/true);
4024 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4025 return options;
4026}
4027
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004028absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004029 switch (data_channel_type_) {
4030 case cricket::DCT_RTP:
4031 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004032 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004033 }
4034 return rtp_data_channel_->content_name();
4035 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004036 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004037 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004038 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004039 }
4040}
4041
Steve Anton4171afb2017-11-20 10:20:22 -08004042void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4043 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4044 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004045 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004046}
4047
Steve Anton4171afb2017-11-20 10:20:22 -08004048void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004049 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004050 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004051 cricket::MediaType media_type,
4052 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004053 RTC_DCHECK(!IsUnifiedPlan());
4054
Steve Anton4171afb2017-11-20 10:20:22 -08004055 std::vector<RtpSenderInfo>* current_senders =
4056 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004057
Steve Anton4171afb2017-11-20 10:20:22 -08004058 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004059 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004060 for (auto sender_it = current_senders->begin();
4061 sender_it != current_senders->end();
4062 /* incremented manually */) {
4063 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004064 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004065 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004066 std::string params_stream_id;
4067 if (params) {
4068 params_stream_id =
4069 (!params->first_stream_id().empty() ? params->first_stream_id()
4070 : kDefaultStreamId);
4071 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004072 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004073 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004074 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004075 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004076 sender_exists) {
4077 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004078 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004079 OnRemoteSenderRemoved(info, media_type);
4080 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004081 }
4082 }
4083
Steve Anton4171afb2017-11-20 10:20:22 -08004084 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004085 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004086 if (!params.has_ssrcs()) {
4087 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4088 // sender, this means it is coming from a Unified Plan endpoint,so we just
4089 // create a default.
4090 default_sender_needed = true;
4091 break;
4092 }
4093
Seth Hampson845e8782018-03-02 11:34:10 -08004094 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004095 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004096 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4097 // not supported in Plan B, we just take the first here and create the
4098 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004099 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004100 (!params.first_stream_id().empty() ? params.first_stream_id()
4101 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004102 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004103 uint32_t ssrc = params.first_ssrc();
4104
4105 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004106 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004107 if (!stream) {
4108 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004109 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004110 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004111 remote_streams_->AddStream(stream);
4112 new_streams->AddStream(stream);
4113 }
4114
Steve Anton4171afb2017-11-20 10:20:22 -08004115 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004116 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004117 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004118 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004119 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004120 }
4121 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004122
Steve Anton4171afb2017-11-20 10:20:22 -08004123 // Add default sender if necessary.
4124 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004125 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004126 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004127 if (!default_stream) {
4128 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004129 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004130 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004131 remote_streams_->AddStream(default_stream);
4132 new_streams->AddStream(default_stream);
4133 }
Steve Anton4171afb2017-11-20 10:20:22 -08004134 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4135 ? kDefaultAudioSenderId
4136 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004137 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004138 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004139 if (!default_sender_info) {
4140 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004141 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004142 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004143 }
4144 }
deadbeefab9b2d12015-10-14 11:33:11 -07004145}
4146
Steve Anton4171afb2017-11-20 10:20:22 -08004147void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4148 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004149 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4150 << " receiver for track_id=" << sender_info.sender_id
4151 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004152
Steve Anton3d954a62018-04-02 11:27:23 -07004153 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004154 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004155 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004156 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004157 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004158 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004159 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004160 }
4161}
4162
Steve Anton4171afb2017-11-20 10:20:22 -08004163void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4164 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004165 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4166 << " receiver for track_id=" << sender_info.sender_id
4167 << " and stream_id=" << sender_info.stream_id;
4168
Seth Hampson845e8782018-03-02 11:34:10 -08004169 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004170
Henrik Boström933d8b02017-10-10 10:05:16 -07004171 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004172 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004173 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4174 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004175 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004176 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004177 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004178 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004179 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004180 }
4181 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004182 // Stopping or destroying a VideoRtpReceiver will end the
4183 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004184 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004185 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004186 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004187 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004188 // There's no guarantee the track is still available, e.g. the track may
4189 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004190 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004191 }
4192 } else {
nisseede5da42017-01-12 05:15:36 -08004193 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004194 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004195 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004196 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004197 }
deadbeefab9b2d12015-10-14 11:33:11 -07004198}
4199
4200void PeerConnection::UpdateEndedRemoteMediaStreams() {
4201 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4202 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4203 MediaStreamInterface* stream = remote_streams_->at(i);
4204 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4205 streams_to_remove.push_back(stream);
4206 }
4207 }
4208
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004209 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004210 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004211 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004212 }
4213}
4214
Steve Anton4171afb2017-11-20 10:20:22 -08004215void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004216 const std::vector<cricket::StreamParams>& streams,
4217 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004218 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004219
Seth Hampson845e8782018-03-02 11:34:10 -08004220 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004221 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004222 for (auto sender_it = current_senders->begin();
4223 sender_it != current_senders->end();
4224 /* incremented manually */) {
4225 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004226 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004227 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4228 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004229 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004230 OnLocalSenderRemoved(info, media_type);
4231 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004232 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004233 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004234 }
4235 }
4236
Steve Anton4171afb2017-11-20 10:20:22 -08004237 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004238 for (const cricket::StreamParams& params : streams) {
4239 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004240 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004241 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004242 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004243 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004244 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004245 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004246 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004247 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004248 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004249 }
4250 }
4251}
4252
Steve Anton4171afb2017-11-20 10:20:22 -08004253void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4254 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004255 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004256 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004257 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004258 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4259 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004260 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004261 return;
4262 }
4263
deadbeeffac06552015-11-25 11:26:01 -08004264 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004265 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004266 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004267 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004268 }
deadbeeffac06552015-11-25 11:26:01 -08004269
Seth Hampson5b4f0752018-04-02 16:31:36 -07004270 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004271 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004272}
4273
Steve Anton4171afb2017-11-20 10:20:22 -08004274void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4275 cricket::MediaType media_type) {
4276 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004277 if (!sender) {
4278 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004279 // SessionDescriptions has been renegotiated.
4280 return;
4281 }
deadbeeffac06552015-11-25 11:26:01 -08004282
4283 // A sender has been removed from the SessionDescription but it's still
4284 // associated with the PeerConnection. This only occurs if the SDP doesn't
4285 // match with the calls to CreateSender, AddStream and RemoveStream.
4286 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004287 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004288 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004289 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004290 }
deadbeeffac06552015-11-25 11:26:01 -08004291
Steve Anton4171afb2017-11-20 10:20:22 -08004292 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004293}
4294
4295void PeerConnection::UpdateLocalRtpDataChannels(
4296 const cricket::StreamParamsVec& streams) {
4297 std::vector<std::string> existing_channels;
4298
4299 // Find new and active data channels.
4300 for (const cricket::StreamParams& params : streams) {
4301 // |it->sync_label| is actually the data channel label. The reason is that
4302 // we use the same naming of data channels as we do for
4303 // MediaStreams and Tracks.
4304 // For MediaStreams, the sync_label is the MediaStream label and the
4305 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004306 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004307 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004308 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004309 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004310 continue;
4311 }
4312 // Set the SSRC the data channel should use for sending.
4313 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4314 existing_channels.push_back(data_channel_it->first);
4315 }
4316
4317 UpdateClosingRtpDataChannels(existing_channels, true);
4318}
4319
4320void PeerConnection::UpdateRemoteRtpDataChannels(
4321 const cricket::StreamParamsVec& streams) {
4322 std::vector<std::string> existing_channels;
4323
4324 // Find new and active data channels.
4325 for (const cricket::StreamParams& params : streams) {
4326 // The data channel label is either the mslabel or the SSRC if the mslabel
4327 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004328 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004329 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004330 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004331 auto data_channel_it = rtp_data_channels_.find(label);
4332 if (data_channel_it == rtp_data_channels_.end()) {
4333 // This is a new data channel.
4334 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4335 } else {
4336 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4337 }
4338 existing_channels.push_back(label);
4339 }
4340
4341 UpdateClosingRtpDataChannels(existing_channels, false);
4342}
4343
4344void PeerConnection::UpdateClosingRtpDataChannels(
4345 const std::vector<std::string>& active_channels,
4346 bool is_local_update) {
4347 auto it = rtp_data_channels_.begin();
4348 while (it != rtp_data_channels_.end()) {
4349 DataChannel* data_channel = it->second;
4350 if (std::find(active_channels.begin(), active_channels.end(),
4351 data_channel->label()) != active_channels.end()) {
4352 ++it;
4353 continue;
4354 }
4355
4356 if (is_local_update) {
4357 data_channel->SetSendSsrc(0);
4358 } else {
4359 data_channel->RemotePeerRequestClose();
4360 }
4361
4362 if (data_channel->state() == DataChannel::kClosed) {
4363 rtp_data_channels_.erase(it);
4364 it = rtp_data_channels_.begin();
4365 } else {
4366 ++it;
4367 }
4368 }
4369}
4370
4371void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4372 uint32_t remote_ssrc) {
4373 rtc::scoped_refptr<DataChannel> channel(
4374 InternalCreateDataChannel(label, nullptr));
4375 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004376 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004377 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004378 return;
4379 }
4380 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004381 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4382 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004383 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004384}
4385
4386rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4387 const std::string& label,
4388 const InternalDataChannelInit* config) {
4389 if (IsClosed()) {
4390 return nullptr;
4391 }
Steve Anton75737c02017-11-06 10:37:17 -08004392 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004393 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004394 << "InternalCreateDataChannel: Data is not supported in this call.";
4395 return nullptr;
4396 }
4397 InternalDataChannelInit new_config =
4398 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004399 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004400 if (new_config.id < 0) {
4401 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004402 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004403 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004404 RTC_LOG(LS_ERROR)
4405 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004406 return nullptr;
4407 }
4408 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004409 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004410 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004411 return nullptr;
4412 }
4413 }
4414
Steve Anton75737c02017-11-06 10:37:17 -08004415 rtc::scoped_refptr<DataChannel> channel(
4416 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004417 if (!channel) {
4418 sid_allocator_.ReleaseSid(new_config.id);
4419 return nullptr;
4420 }
4421
4422 if (channel->data_channel_type() == cricket::DCT_RTP) {
4423 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004424 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4425 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004426 return nullptr;
4427 }
4428 rtp_data_channels_[channel->label()] = channel;
4429 } else {
4430 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4431 sctp_data_channels_.push_back(channel);
4432 channel->SignalClosed.connect(this,
4433 &PeerConnection::OnSctpDataChannelClosed);
4434 }
4435
Steve Anton2d8609c2018-01-23 16:38:46 -08004436 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004437 return channel;
4438}
4439
4440bool PeerConnection::HasDataChannels() const {
4441 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4442}
4443
4444void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4445 for (const auto& channel : sctp_data_channels_) {
4446 if (channel->id() < 0) {
4447 int sid;
4448 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004449 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004450 continue;
4451 }
4452 channel->SetSctpSid(sid);
4453 }
4454 }
4455}
4456
4457void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004458 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004459 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4460 ++it) {
4461 if (it->get() == channel) {
4462 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004463 // After the closing procedure is done, it's safe to use this ID for
4464 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004465 sid_allocator_.ReleaseSid(channel->id());
4466 }
deadbeefbd292462015-12-14 18:15:29 -08004467 // Since this method is triggered by a signal from the DataChannel,
4468 // we can't free it directly here; we need to free it asynchronously.
4469 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004470 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004471 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4472 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004473 return;
4474 }
4475 }
4476}
4477
deadbeefab9b2d12015-10-14 11:33:11 -07004478void PeerConnection::OnDataChannelDestroyed() {
4479 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4480 // DataChannel may callback to us and try to modify the list.
4481 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4482 temp_rtp_dcs.swap(rtp_data_channels_);
4483 for (const auto& kv : temp_rtp_dcs) {
4484 kv.second->OnTransportChannelDestroyed();
4485 }
4486
4487 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4488 temp_sctp_dcs.swap(sctp_data_channels_);
4489 for (const auto& channel : temp_sctp_dcs) {
4490 channel->OnTransportChannelDestroyed();
4491 }
4492}
4493
4494void PeerConnection::OnDataChannelOpenMessage(
4495 const std::string& label,
4496 const InternalDataChannelInit& config) {
4497 rtc::scoped_refptr<DataChannel> channel(
4498 InternalCreateDataChannel(label, &config));
4499 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004500 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004501 return;
4502 }
4503
deadbeefa601f5c2016-06-06 14:27:39 -07004504 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4505 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004506 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004507 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004508}
4509
Steve Anton4171afb2017-11-20 10:20:22 -08004510rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4511PeerConnection::GetAudioTransceiver() const {
4512 // This method only works with Plan B SDP, where there is a single
4513 // audio/video transceiver.
4514 RTC_DCHECK(!IsUnifiedPlan());
4515 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004516 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004517 return transceiver;
4518 }
4519 }
4520 RTC_NOTREACHED();
4521 return nullptr;
4522}
4523
4524rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4525PeerConnection::GetVideoTransceiver() const {
4526 // This method only works with Plan B SDP, where there is a single
4527 // audio/video transceiver.
4528 RTC_DCHECK(!IsUnifiedPlan());
4529 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004530 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004531 return transceiver;
4532 }
4533 }
4534 RTC_NOTREACHED();
4535 return nullptr;
4536}
4537
4538// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4539// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004540bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004541 switch (type) {
4542 case cricket::MEDIA_TYPE_AUDIO:
4543 return !GetAudioTransceiver()->internal()->senders().empty();
4544 case cricket::MEDIA_TYPE_VIDEO:
4545 return !GetVideoTransceiver()->internal()->senders().empty();
4546 case cricket::MEDIA_TYPE_DATA:
4547 return false;
4548 }
4549 RTC_NOTREACHED();
4550 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004551}
4552
Steve Anton4171afb2017-11-20 10:20:22 -08004553rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4554PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4555 for (auto transceiver : transceivers_) {
4556 for (auto sender : transceiver->internal()->senders()) {
4557 if (sender->track() == track) {
4558 return sender;
4559 }
4560 }
4561 }
4562 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004563}
4564
Steve Anton4171afb2017-11-20 10:20:22 -08004565rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4566PeerConnection::FindSenderById(const std::string& sender_id) const {
4567 for (auto transceiver : transceivers_) {
4568 for (auto sender : transceiver->internal()->senders()) {
4569 if (sender->id() == sender_id) {
4570 return sender;
4571 }
4572 }
4573 }
4574 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004575}
4576
Steve Anton4171afb2017-11-20 10:20:22 -08004577rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4578PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4579 for (auto transceiver : transceivers_) {
4580 for (auto receiver : transceiver->internal()->receivers()) {
4581 if (receiver->id() == receiver_id) {
4582 return receiver;
4583 }
4584 }
4585 }
4586 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004587}
4588
Steve Anton4171afb2017-11-20 10:20:22 -08004589std::vector<PeerConnection::RtpSenderInfo>*
4590PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4591 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4592 media_type == cricket::MEDIA_TYPE_VIDEO);
4593 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4594 ? &remote_audio_sender_infos_
4595 : &remote_video_sender_infos_;
4596}
4597
4598std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004599 cricket::MediaType media_type) {
4600 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4601 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004602 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4603 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004604}
4605
Steve Anton4171afb2017-11-20 10:20:22 -08004606const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4607 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004608 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004609 const std::string sender_id) const {
4610 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004611 if (sender_info.stream_id == stream_id &&
4612 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004613 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004614 }
4615 }
4616 return nullptr;
4617}
4618
4619DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4620 for (const auto& channel : sctp_data_channels_) {
4621 if (channel->id() == sid) {
4622 return channel;
4623 }
4624 }
4625 return nullptr;
4626}
4627
deadbeef91dd5672016-05-18 16:55:30 -07004628bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004629 const cricket::ServerAddresses& stun_servers,
4630 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004631 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004632 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004633 // To handle both internal and externally created port allocator, we will
4634 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004635 port_allocator_flags_ = port_allocator_->flags();
4636 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4637 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4638 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004639 // If the disable-IPv6 flag was specified, we'll not override it
4640 // by experiment.
4641 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004642 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004643 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4644 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004645 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004646 }
4647
zhihuangb09b3f92017-03-07 14:40:51 -08004648 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004649 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004650 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004651 }
4652
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004653 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004654 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004655 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004656 }
4657
honghaiz60347052016-05-31 18:29:12 -07004658 if (configuration.candidate_network_policy ==
4659 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004660 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004661 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004662 }
4663
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004664 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004665 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004666 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4667 }
4668
Qingsi Wanga2d60672018-04-11 16:57:45 -07004669 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004670 // No step delay is used while allocating ports.
4671 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4672 port_allocator_->set_candidate_filter(
4673 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004674 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004675
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004676 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004677 for (auto& turn_server : turn_servers_copy) {
4678 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004679 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004680 // Call this last since it may create pooled allocator sessions using the
4681 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004682 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004683 stun_servers, std::move(turn_servers_copy),
4684 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4685 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004686 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004687 return true;
4688}
4689
deadbeef91dd5672016-05-18 16:55:30 -07004690bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004691 const cricket::ServerAddresses& stun_servers,
4692 const std::vector<cricket::RelayServerConfig>& turn_servers,
4693 IceTransportsType type,
4694 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004695 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004696 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004697 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004698 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004699 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004700 // According to JSEP, after setLocalDescription, changing the candidate pool
4701 // size is not allowed, and changing the set of ICE servers will not result
4702 // in new candidates being gathered.
4703 if (local_description()) {
4704 port_allocator_->FreezeCandidatePool();
4705 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004706 // Add the custom tls turn servers if they exist.
4707 auto turn_servers_copy = turn_servers;
4708 for (auto& turn_server : turn_servers_copy) {
4709 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4710 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004711 // Call this last since it may create pooled allocator sessions using the
4712 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004713 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004714 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4715 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004716}
4717
Steve Antonba818672017-11-06 10:21:57 -08004718cricket::ChannelManager* PeerConnection::channel_manager() const {
4719 return factory_->channel_manager();
4720}
4721
Elad Alon99c3fe52017-10-13 16:29:40 +02004722bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004723 std::unique_ptr<RtcEventLogOutput> output,
4724 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004725 if (!event_log_) {
4726 return false;
4727 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004728 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004729}
4730
4731void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004732 if (event_log_) {
4733 event_log_->StopLogging();
4734 }
ivoc14d5dbe2016-07-04 07:06:55 -07004735}
nisseeaabdf62017-05-05 02:23:02 -07004736
Steve Anton75737c02017-11-06 10:37:17 -08004737cricket::BaseChannel* PeerConnection::GetChannel(
4738 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004739 for (auto transceiver : transceivers_) {
4740 cricket::BaseChannel* channel = transceiver->internal()->channel();
4741 if (channel && channel->content_name() == content_name) {
4742 return channel;
4743 }
Steve Anton75737c02017-11-06 10:37:17 -08004744 }
4745 if (rtp_data_channel() &&
4746 rtp_data_channel()->content_name() == content_name) {
4747 return rtp_data_channel();
4748 }
4749 return nullptr;
4750}
4751
4752bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4753 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004754 RTC_LOG(LS_INFO)
4755 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004756 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004757 return false;
4758 }
4759 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004760 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004761 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004762 return false;
4763 }
4764
Zhi Huange830e682018-03-30 10:48:35 -07004765 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4766 if (dtls_role) {
4767 *role = *dtls_role;
4768 return true;
4769 }
4770 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004771}
4772
4773bool PeerConnection::GetSslRole(const std::string& content_name,
4774 rtc::SSLRole* role) {
4775 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004776 RTC_LOG(LS_INFO)
4777 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004778 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004779 return false;
4780 }
4781
Zhi Huange830e682018-03-30 10:48:35 -07004782 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4783 if (dtls_role) {
4784 *role = *dtls_role;
4785 return true;
4786 }
4787 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004788}
4789
Steve Antonf8470812017-12-04 10:46:21 -08004790void PeerConnection::SetSessionError(SessionError error,
4791 const std::string& error_desc) {
4792 RTC_DCHECK_RUN_ON(signaling_thread());
4793 if (error != session_error_) {
4794 session_error_ = error;
4795 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004796 }
4797}
4798
Zhi Huange830e682018-03-30 10:48:35 -07004799RTCError PeerConnection::UpdateSessionState(
4800 SdpType type,
4801 cricket::ContentSource source,
4802 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004803 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004804
4805 // If there's already a pending error then no state transition should happen.
4806 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004807 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004808
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004809 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004810 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004811 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004812 }
4813
4814 // Update the signaling state according to the specified state machine (see
4815 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004816 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004817 ChangeSignalingState(source == cricket::CS_LOCAL
4818 ? PeerConnectionInterface::kHaveLocalOffer
4819 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004820 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004821 ChangeSignalingState(source == cricket::CS_LOCAL
4822 ? PeerConnectionInterface::kHaveLocalPrAnswer
4823 : PeerConnectionInterface::kHaveRemotePrAnswer);
4824 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004825 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004826 ChangeSignalingState(PeerConnectionInterface::kStable);
4827 }
4828
4829 // Update internal objects according to the session description's media
4830 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004831 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004832 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004833 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004834 }
4835
Steve Anton8a006912017-12-04 15:25:56 -08004836 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004837}
4838
Steve Anton8a006912017-12-04 15:25:56 -08004839RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004840 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004841 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004842 const SessionDescriptionInterface* sdesc =
4843 (source == cricket::CS_LOCAL ? local_description()
4844 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004845 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004846
4847 // Push down the new SDP media section for each audio/video transceiver.
4848 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004849 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004850 FindMediaSectionForTransceiver(transceiver, sdesc);
4851 cricket::BaseChannel* channel = transceiver->internal()->channel();
4852 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004853 continue;
4854 }
4855 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004856 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004857 if (!content_desc) {
4858 continue;
4859 }
4860 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004861 bool success = (source == cricket::CS_LOCAL)
4862 ? channel->SetLocalContent(content_desc, type, &error)
4863 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004864 if (!success) {
4865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4866 }
4867 }
4868
4869 // If using the RtpDataChannel, push down the new SDP section for it too.
4870 if (rtp_data_channel_) {
4871 const ContentInfo* data_content =
4872 cricket::GetFirstDataContent(sdesc->description());
4873 if (data_content && !data_content->rejected) {
4874 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004875 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004876 if (data_desc) {
4877 std::string error;
4878 bool success =
4879 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004880 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004881 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004882 if (!success) {
4883 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4884 std::move(error));
4885 }
Steve Anton75737c02017-11-06 10:37:17 -08004886 }
4887 }
4888 }
Steve Antoned10bd92017-12-05 10:52:59 -08004889
Steve Anton75737c02017-11-06 10:37:17 -08004890 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4891 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4892 if (sctp_transport_ && local_description() && remote_description() &&
4893 cricket::GetFirstDataContent(local_description()->description()) &&
4894 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004895 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004896 RTC_FROM_HERE,
4897 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004898 if (!success) {
4899 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4900 "Failed to push down SCTP parameters.");
4901 }
Steve Anton75737c02017-11-06 10:37:17 -08004902 }
Steve Antoned10bd92017-12-05 10:52:59 -08004903
Steve Anton8a006912017-12-04 15:25:56 -08004904 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004905}
4906
4907bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4908 RTC_DCHECK(network_thread()->IsCurrent());
4909 RTC_DCHECK(local_description());
4910 RTC_DCHECK(remote_description());
4911 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4912 // When we support "max-message-size", that would also be pushed down here.
4913 return sctp_transport_->Start(
4914 GetSctpPort(local_description()->description()),
4915 GetSctpPort(remote_description()->description()));
4916}
4917
Steve Anton8a006912017-12-04 15:25:56 -08004918RTCError PeerConnection::PushdownTransportDescription(
4919 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004920 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004921 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004922
Zhi Huange830e682018-03-30 10:48:35 -07004923 if (source == cricket::CS_LOCAL) {
4924 const SessionDescriptionInterface* sdesc = local_description();
4925 RTC_DCHECK(sdesc);
4926 return transport_controller_->SetLocalDescription(type,
4927 sdesc->description());
4928 } else {
4929 const SessionDescriptionInterface* sdesc = remote_description();
4930 RTC_DCHECK(sdesc);
4931 return transport_controller_->SetRemoteDescription(type,
4932 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004933 }
Steve Anton75737c02017-11-06 10:37:17 -08004934}
4935
4936bool PeerConnection::GetTransportDescription(
4937 const SessionDescription* description,
4938 const std::string& content_name,
4939 cricket::TransportDescription* tdesc) {
4940 if (!description || !tdesc) {
4941 return false;
4942 }
4943 const TransportInfo* transport_info =
4944 description->GetTransportInfoByName(content_name);
4945 if (!transport_info) {
4946 return false;
4947 }
4948 *tdesc = transport_info->description;
4949 return true;
4950}
4951
Steve Anton75737c02017-11-06 10:37:17 -08004952cricket::IceConfig PeerConnection::ParseIceConfig(
4953 const PeerConnectionInterface::RTCConfiguration& config) const {
4954 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004955 switch (config.continual_gathering_policy) {
4956 case PeerConnectionInterface::GATHER_ONCE:
4957 gathering_policy = cricket::GATHER_ONCE;
4958 break;
4959 case PeerConnectionInterface::GATHER_CONTINUALLY:
4960 gathering_policy = cricket::GATHER_CONTINUALLY;
4961 break;
4962 default:
4963 RTC_NOTREACHED();
4964 gathering_policy = cricket::GATHER_ONCE;
4965 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004966
Steve Anton75737c02017-11-06 10:37:17 -08004967 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004968 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4969 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004970 ice_config.prioritize_most_likely_candidate_pairs =
4971 config.prioritize_most_likely_ice_candidate_pairs;
4972 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004973 RTCConfigurationToIceConfigOptionalInt(
4974 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004975 ice_config.continual_gathering_policy = gathering_policy;
4976 ice_config.presume_writable_when_fully_relayed =
4977 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004978 ice_config.ice_check_interval_strong_connectivity =
4979 config.ice_check_interval_strong_connectivity;
4980 ice_config.ice_check_interval_weak_connectivity =
4981 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004982 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004983 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004984 ice_config.regather_all_networks_interval_range =
4985 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004986 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004987 return ice_config;
4988}
4989
Steve Anton75737c02017-11-06 10:37:17 -08004990bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4991 std::string* track_id) {
4992 if (!local_description()) {
4993 return false;
4994 }
4995 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4996 track_id);
4997}
4998
4999bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5000 std::string* track_id) {
5001 if (!remote_description()) {
5002 return false;
5003 }
5004 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5005 track_id);
5006}
5007
5008bool PeerConnection::SendData(const cricket::SendDataParams& params,
5009 const rtc::CopyOnWriteBuffer& payload,
5010 cricket::SendDataResult* result) {
5011 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005012 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005013 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005014 return false;
5015 }
5016 return rtp_data_channel_
5017 ? rtp_data_channel_->SendData(params, payload, result)
5018 : network_thread()->Invoke<bool>(
5019 RTC_FROM_HERE,
5020 Bind(&cricket::SctpTransportInternal::SendData,
5021 sctp_transport_.get(), params, payload, result));
5022}
5023
5024bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5025 if (!rtp_data_channel_ && !sctp_transport_) {
5026 // Don't log an error here, because DataChannels are expected to call
5027 // ConnectDataChannel in this state. It's the only way to initially tell
5028 // whether or not the underlying transport is ready.
5029 return false;
5030 }
5031 if (rtp_data_channel_) {
5032 rtp_data_channel_->SignalReadyToSendData.connect(
5033 webrtc_data_channel, &DataChannel::OnChannelReady);
5034 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5035 &DataChannel::OnDataReceived);
5036 } else {
5037 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5038 &DataChannel::OnChannelReady);
5039 SignalSctpDataReceived.connect(webrtc_data_channel,
5040 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005041 SignalSctpClosingProcedureStartedRemotely.connect(
5042 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5043 SignalSctpClosingProcedureComplete.connect(
5044 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005045 }
5046 return true;
5047}
5048
5049void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5050 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005051 RTC_LOG(LS_ERROR)
5052 << "DisconnectDataChannel called when rtp_data_channel_ and "
5053 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005054 return;
5055 }
5056 if (rtp_data_channel_) {
5057 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5058 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5059 } else {
5060 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5061 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005062 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5063 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005064 }
5065}
5066
5067void PeerConnection::AddSctpDataStream(int sid) {
5068 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005069 RTC_LOG(LS_ERROR)
5070 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005071 return;
5072 }
5073 network_thread()->Invoke<void>(
5074 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5075 sctp_transport_.get(), sid));
5076}
5077
5078void PeerConnection::RemoveSctpDataStream(int sid) {
5079 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005080 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005081 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005082 return;
5083 }
5084 network_thread()->Invoke<void>(
5085 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5086 sctp_transport_.get(), sid));
5087}
5088
5089bool PeerConnection::ReadyToSendData() const {
5090 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5091 sctp_ready_to_send_data_;
5092}
5093
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005094absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005095 if (sctp_mid_ && transport_controller_) {
5096 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5097 if (dtls_transport) {
5098 return dtls_transport->transport_name();
5099 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005100 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005101 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005102 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005103}
5104
Qingsi Wang72a43a12018-02-20 16:03:18 -08005105cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5106 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005107 network_thread()->Invoke<void>(
5108 RTC_FROM_HERE,
5109 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5110 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005111 return candidate_states_list;
5112}
5113
Steve Anton5dfde182018-02-06 10:34:40 -08005114std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5115 const {
5116 std::map<std::string, std::string> transport_names_by_mid;
5117 for (auto transceiver : transceivers_) {
5118 cricket::BaseChannel* channel = transceiver->internal()->channel();
5119 if (channel) {
5120 transport_names_by_mid[channel->content_name()] =
5121 channel->transport_name();
5122 }
Steve Anton75737c02017-11-06 10:37:17 -08005123 }
Steve Anton5dfde182018-02-06 10:34:40 -08005124 if (rtp_data_channel_) {
5125 transport_names_by_mid[rtp_data_channel_->content_name()] =
5126 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005127 }
5128 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005129 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005130 RTC_DCHECK(transport_name);
5131 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005132 }
Steve Anton5dfde182018-02-06 10:34:40 -08005133 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005134}
5135
Steve Anton5dfde182018-02-06 10:34:40 -08005136std::map<std::string, cricket::TransportStats>
5137PeerConnection::GetTransportStatsByNames(
5138 const std::set<std::string>& transport_names) {
5139 if (!network_thread()->IsCurrent()) {
5140 return network_thread()
5141 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5142 RTC_FROM_HERE,
5143 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005144 }
Steve Anton5dfde182018-02-06 10:34:40 -08005145 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5146 for (const std::string& transport_name : transport_names) {
5147 cricket::TransportStats transport_stats;
5148 bool success =
5149 transport_controller_->GetStats(transport_name, &transport_stats);
5150 if (success) {
5151 transport_stats_by_name[transport_name] = std::move(transport_stats);
5152 } else {
5153 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5154 << transport_name;
5155 }
5156 }
5157 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005158}
5159
5160bool PeerConnection::GetLocalCertificate(
5161 const std::string& transport_name,
5162 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005163 if (!certificate) {
5164 return false;
5165 }
5166 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5167 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005168}
5169
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005170std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005171 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005172 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005173}
5174
5175cricket::DataChannelType PeerConnection::data_channel_type() const {
5176 return data_channel_type_;
5177}
5178
5179bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5180 return pending_ice_restarts_.find(content_name) !=
5181 pending_ice_restarts_.end();
5182}
5183
Steve Anton75737c02017-11-06 10:37:17 -08005184bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5185 return transport_controller_->NeedsIceRestart(content_name);
5186}
5187
5188void PeerConnection::OnCertificateReady(
5189 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5190 transport_controller_->SetLocalCertificate(certificate);
5191}
5192
5193void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005194 SetSessionError(SessionError::kTransport,
5195 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005196}
5197
5198void PeerConnection::OnTransportControllerConnectionState(
5199 cricket::IceConnectionState state) {
5200 switch (state) {
5201 case cricket::kIceConnectionConnecting:
5202 // If the current state is Connected or Completed, then there were
5203 // writable channels but now there are not, so the next state must
5204 // be Disconnected.
5205 // kIceConnectionConnecting is currently used as the default,
5206 // un-connected state by the TransportController, so its only use is
5207 // detecting disconnections.
5208 if (ice_connection_state_ ==
5209 PeerConnectionInterface::kIceConnectionConnected ||
5210 ice_connection_state_ ==
5211 PeerConnectionInterface::kIceConnectionCompleted) {
5212 SetIceConnectionState(
5213 PeerConnectionInterface::kIceConnectionDisconnected);
5214 }
5215 break;
5216 case cricket::kIceConnectionFailed:
5217 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5218 break;
5219 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005220 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005221 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005222 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005223 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005224 break;
5225 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005226 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005227 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005228 if (ice_connection_state_ !=
5229 PeerConnectionInterface::kIceConnectionConnected) {
5230 // If jumping directly from "checking" to "connected",
5231 // signal "connected" first.
5232 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5233 }
5234 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005235 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005236 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005237 break;
5238 default:
5239 RTC_NOTREACHED();
5240 }
5241}
5242
5243void PeerConnection::OnTransportControllerCandidatesGathered(
5244 const std::string& transport_name,
5245 const cricket::Candidates& candidates) {
5246 RTC_DCHECK(signaling_thread()->IsCurrent());
5247 int sdp_mline_index;
5248 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005249 RTC_LOG(LS_ERROR)
5250 << "OnTransportControllerCandidatesGathered: content name "
5251 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005252 return;
5253 }
5254
5255 for (cricket::Candidates::const_iterator citer = candidates.begin();
5256 citer != candidates.end(); ++citer) {
5257 // Use transport_name as the candidate media id.
5258 std::unique_ptr<JsepIceCandidate> candidate(
5259 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5260 if (local_description()) {
5261 mutable_local_description()->AddCandidate(candidate.get());
5262 }
5263 OnIceCandidate(std::move(candidate));
5264 }
5265}
5266
5267void PeerConnection::OnTransportControllerCandidatesRemoved(
5268 const std::vector<cricket::Candidate>& candidates) {
5269 RTC_DCHECK(signaling_thread()->IsCurrent());
5270 // Sanity check.
5271 for (const cricket::Candidate& candidate : candidates) {
5272 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005273 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005274 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005275 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005276 return;
5277 }
5278 }
5279
5280 if (local_description()) {
5281 mutable_local_description()->RemoveCandidates(candidates);
5282 }
5283 OnIceCandidatesRemoved(candidates);
5284}
5285
5286void PeerConnection::OnTransportControllerDtlsHandshakeError(
5287 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005288 RTC_HISTOGRAM_ENUMERATION(
5289 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5290 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005291}
5292
Steve Antoned10bd92017-12-05 10:52:59 -08005293void PeerConnection::EnableSending() {
5294 for (auto transceiver : transceivers_) {
5295 cricket::BaseChannel* channel = transceiver->internal()->channel();
5296 if (channel && !channel->enabled()) {
5297 channel->Enable(true);
5298 }
Steve Anton75737c02017-11-06 10:37:17 -08005299 }
5300
Steve Anton4171afb2017-11-20 10:20:22 -08005301 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005302 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005303 }
Steve Anton75737c02017-11-06 10:37:17 -08005304}
5305
5306// Returns the media index for a local ice candidate given the content name.
5307bool PeerConnection::GetLocalCandidateMediaIndex(
5308 const std::string& content_name,
5309 int* sdp_mline_index) {
5310 if (!local_description() || !sdp_mline_index) {
5311 return false;
5312 }
5313
5314 bool content_found = false;
5315 const ContentInfos& contents = local_description()->description()->contents();
5316 for (size_t index = 0; index < contents.size(); ++index) {
5317 if (contents[index].name == content_name) {
5318 *sdp_mline_index = static_cast<int>(index);
5319 content_found = true;
5320 break;
5321 }
5322 }
5323 return content_found;
5324}
5325
5326bool PeerConnection::UseCandidatesInSessionDescription(
5327 const SessionDescriptionInterface* remote_desc) {
5328 if (!remote_desc) {
5329 return true;
5330 }
5331 bool ret = true;
5332
5333 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5334 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5335 for (size_t n = 0; n < candidates->count(); ++n) {
5336 const IceCandidateInterface* candidate = candidates->at(n);
5337 bool valid = false;
5338 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5339 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005340 RTC_LOG(LS_INFO)
5341 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005342 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005343 }
5344 continue;
5345 }
5346 ret = UseCandidate(candidate);
5347 if (!ret) {
5348 break;
5349 }
5350 }
5351 }
5352 return ret;
5353}
5354
5355bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5356 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5357 size_t remote_content_size =
5358 remote_description()->description()->contents().size();
5359 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005360 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005361 return false;
5362 }
5363
5364 cricket::ContentInfo content =
5365 remote_description()->description()->contents()[mediacontent_index];
5366 std::vector<cricket::Candidate> candidates;
5367 candidates.push_back(candidate->candidate());
5368 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005369 RTCError error =
5370 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005371 if (error.ok()) {
5372 // Candidates successfully submitted for checking.
5373 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5374 ice_connection_state_ ==
5375 PeerConnectionInterface::kIceConnectionDisconnected) {
5376 // If state is New, then the session has just gotten its first remote ICE
5377 // candidates, so go to Checking.
5378 // If state is Disconnected, the session is re-using old candidates or
5379 // receiving additional ones, so go to Checking.
5380 // If state is Connected, stay Connected.
5381 // TODO(bemasc): If state is Connected, and the new candidates are for a
5382 // newly added transport, then the state actually _should_ move to
5383 // checking. Add a way to distinguish that case.
5384 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5385 }
5386 // TODO(bemasc): If state is Completed, go back to Connected.
5387 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005388 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005389 }
5390 return true;
5391}
5392
5393void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005394 // Destroy video channel first since it may have a pointer to the
5395 // voice channel.
5396 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005397 if (!video_info || video_info->rejected) {
5398 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005399 }
5400
Steve Anton6fec8802017-12-04 10:37:29 -08005401 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5402 if (!audio_info || audio_info->rejected) {
5403 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005404 }
5405
5406 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5407 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005408 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005409 }
5410}
5411
Steve Antondcc3c022017-12-22 16:02:54 -08005412RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5413 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005414 const cricket::ContentGroup* bundle_group = nullptr;
5415 if (configuration_.bundle_policy ==
5416 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005417 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005418 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005419 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5420 "max-bundle configured but session description "
5421 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005422 }
5423 }
Steve Antondcc3c022017-12-22 16:02:54 -08005424 return std::move(bundle_group);
5425}
5426
5427RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005428 // Creating the media channels. Transports should already have been created
5429 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005430 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005431 if (voice && !voice->rejected &&
5432 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005433 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005434 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005435 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5436 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005437 }
5438 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5439 }
5440
Steve Antondcc3c022017-12-22 16:02:54 -08005441 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005442 if (video && !video->rejected &&
5443 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005444 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005445 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005446 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5447 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005448 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005449 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
5451
Steve Antondcc3c022017-12-22 16:02:54 -08005452 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005453 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5454 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005455 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005456 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5457 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005458 }
5459 }
5460
Steve Anton8a006912017-12-04 15:25:56 -08005461 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005462}
5463
Steve Anton4171afb2017-11-20 10:20:22 -08005464// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005465cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005466 const std::string& mid) {
5467 RtpTransportInternal* rtp_transport =
5468 transport_controller_->GetRtpTransport(mid);
5469 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005470 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005471 call_.get(), configuration_.media_config, rtp_transport,
5472 signaling_thread(), mid, SrtpRequired(),
5473 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005474 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005476 }
Steve Anton75737c02017-11-06 10:37:17 -08005477 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5478 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005479 voice_channel->SignalSentPacket.connect(this,
5480 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005481 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005482
Steve Antoneda6ccd2017-12-04 10:21:55 -08005483 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005484}
5485
Steve Anton4171afb2017-11-20 10:20:22 -08005486// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005487cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005488 const std::string& mid) {
5489 RtpTransportInternal* rtp_transport =
5490 transport_controller_->GetRtpTransport(mid);
5491 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005492 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005493 call_.get(), configuration_.media_config, rtp_transport,
5494 signaling_thread(), mid, SrtpRequired(),
5495 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005496 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005497 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005498 }
Steve Anton75737c02017-11-06 10:37:17 -08005499 video_channel->SignalDtlsSrtpSetupFailure.connect(
5500 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005501 video_channel->SignalSentPacket.connect(this,
5502 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005503 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005504
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005506}
5507
Zhi Huange830e682018-03-30 10:48:35 -07005508bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005509 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5510 if (sctp) {
5511 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005512 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005513 << "Trying to create SCTP transport, but didn't compile with "
5514 "SCTP support (HAVE_SCTP)";
5515 return false;
5516 }
5517 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005518 RTC_FROM_HERE,
5519 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005520 return false;
5521 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005522 for (const auto& channel : sctp_data_channels_) {
5523 channel->OnTransportChannelCreated();
5524 }
Steve Anton75737c02017-11-06 10:37:17 -08005525 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005526 RtpTransportInternal* rtp_transport =
5527 transport_controller_->GetRtpTransport(mid);
5528 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005529 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005530 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5531 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005532 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005533 return false;
5534 }
Steve Anton75737c02017-11-06 10:37:17 -08005535 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5536 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5537 rtp_data_channel_->SignalSentPacket.connect(
5538 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005539 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005540 }
5541
Steve Anton75737c02017-11-06 10:37:17 -08005542 return true;
5543}
5544
5545Call::Stats PeerConnection::GetCallStats() {
5546 if (!worker_thread()->IsCurrent()) {
5547 return worker_thread()->Invoke<Call::Stats>(
5548 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5549 }
5550 if (call_) {
5551 return call_->GetStats();
5552 } else {
5553 return Call::Stats();
5554 }
5555}
5556
Zhi Huange830e682018-03-30 10:48:35 -07005557bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005558 RTC_DCHECK(network_thread()->IsCurrent());
5559 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005560 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005561 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005562 RTC_DCHECK(dtls_transport);
5563 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005564 RTC_DCHECK(sctp_transport_);
5565 sctp_invoker_.reset(new rtc::AsyncInvoker());
5566 sctp_transport_->SignalReadyToSendData.connect(
5567 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5568 sctp_transport_->SignalDataReceived.connect(
5569 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005570 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5571 // another thread. Would be nice if there was a helper class similar to
5572 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5573 // code.
5574 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5575 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5576 sctp_transport_->SignalClosingProcedureComplete.connect(
5577 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005578 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005579 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005580 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005581}
5582
5583void PeerConnection::DestroySctpTransport_n() {
5584 RTC_DCHECK(network_thread()->IsCurrent());
5585 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005586 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005587 sctp_invoker_.reset(nullptr);
5588 sctp_ready_to_send_data_ = false;
5589}
5590
5591void PeerConnection::OnSctpTransportReadyToSendData_n() {
5592 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5593 RTC_DCHECK(network_thread()->IsCurrent());
5594 // Note: Cannot use rtc::Bind here because it will grab a reference to
5595 // PeerConnection and potentially cause PeerConnection to live longer than
5596 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5597 // be destroyed before PeerConnection is destroyed, and at that point all
5598 // pending tasks will be cleared.
5599 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5600 OnSctpTransportReadyToSendData_s(true);
5601 });
5602}
5603
5604void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5605 RTC_DCHECK(signaling_thread()->IsCurrent());
5606 sctp_ready_to_send_data_ = ready;
5607 SignalSctpReadyToSendData(ready);
5608}
5609
5610void PeerConnection::OnSctpTransportDataReceived_n(
5611 const cricket::ReceiveDataParams& params,
5612 const rtc::CopyOnWriteBuffer& payload) {
5613 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5614 RTC_DCHECK(network_thread()->IsCurrent());
5615 // Note: Cannot use rtc::Bind here because it will grab a reference to
5616 // PeerConnection and potentially cause PeerConnection to live longer than
5617 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5618 // be destroyed before PeerConnection is destroyed, and at that point all
5619 // pending tasks will be cleared.
5620 sctp_invoker_->AsyncInvoke<void>(
5621 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5622 OnSctpTransportDataReceived_s(params, payload);
5623 });
5624}
5625
5626void PeerConnection::OnSctpTransportDataReceived_s(
5627 const cricket::ReceiveDataParams& params,
5628 const rtc::CopyOnWriteBuffer& payload) {
5629 RTC_DCHECK(signaling_thread()->IsCurrent());
5630 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5631 // Received OPEN message; parse and signal that a new data channel should
5632 // be created.
5633 std::string label;
5634 InternalDataChannelInit config;
5635 config.id = params.ssrc;
5636 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005637 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5638 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005639 return;
5640 }
5641 config.open_handshake_role = InternalDataChannelInit::kAcker;
5642 OnDataChannelOpenMessage(label, config);
5643 } else {
5644 // Otherwise just forward the signal.
5645 SignalSctpDataReceived(params, payload);
5646 }
5647}
5648
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005649void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005650 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5651 RTC_DCHECK(network_thread()->IsCurrent());
5652 sctp_invoker_->AsyncInvoke<void>(
5653 RTC_FROM_HERE, signaling_thread(),
5654 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005655 &SignalSctpClosingProcedureStartedRemotely, sid));
5656}
5657
5658void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5659 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5660 RTC_DCHECK(network_thread()->IsCurrent());
5661 sctp_invoker_->AsyncInvoke<void>(
5662 RTC_FROM_HERE, signaling_thread(),
5663 rtc::Bind(&sigslot::signal1<int>::operator(),
5664 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005665}
5666
5667// Returns false if bundle is enabled and rtcp_mux is disabled.
5668bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5669 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5670 if (!bundle_enabled)
5671 return true;
5672
5673 const cricket::ContentGroup* bundle_group =
5674 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5675 RTC_DCHECK(bundle_group != NULL);
5676
5677 const cricket::ContentInfos& contents = desc->contents();
5678 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5679 citer != contents.end(); ++citer) {
5680 const cricket::ContentInfo* content = (&*citer);
5681 RTC_DCHECK(content != NULL);
5682 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005683 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005684 if (!HasRtcpMuxEnabled(content))
5685 return false;
5686 }
5687 }
5688 // RTCP-MUX is enabled in all the contents.
5689 return true;
5690}
5691
5692bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005693 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005694}
5695
Steve Anton8a006912017-12-04 15:25:56 -08005696RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005697 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005698 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005699 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005700 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702
5703 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
5706
Steve Anton3828c062017-12-06 10:34:51 -08005707 SdpType type = sdesc->GetType();
5708 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5709 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005710 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005711 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005712 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
5714
5715 // Verify crypto settings.
5716 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005717 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5718 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005719 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005720 if (!crypto_error.ok()) {
5721 return crypto_error;
5722 }
Steve Anton75737c02017-11-06 10:37:17 -08005723 }
5724
5725 // Verify ice-ufrag and ice-pwd.
5726 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5728 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005729 }
5730
5731 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5733 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005734 }
5735
5736 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5737 // m-lines that do not rtcp-mux enabled.
5738
5739 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005740 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005741 // With an answer we want to compare the new answer session description with
5742 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005743 const cricket::SessionDescription* offer_desc =
5744 (source == cricket::CS_LOCAL) ? remote_description()->description()
5745 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005746 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5747 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5748 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5750 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005753 // The re-offers should respect the order of m= sections in current
5754 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005755 // With a re-offer, either the current local or current remote descriptions
5756 // could be the most up to date, so we would like to check against both of
5757 // them if they exist. It could be the case that one of them has a 0 port
5758 // for a media section, but the other does not. This is important to check
5759 // against in the case that we are recycling an m= section.
5760 const cricket::SessionDescription* current_desc = nullptr;
5761 const cricket::SessionDescription* secondary_current_desc = nullptr;
5762 if (local_description()) {
5763 current_desc = local_description()->description();
5764 if (remote_description()) {
5765 secondary_current_desc = remote_description()->description();
5766 }
5767 } else if (remote_description()) {
5768 current_desc = remote_description()->description();
5769 }
Steve Anton75737c02017-11-06 10:37:17 -08005770 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005771 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5772 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5774 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 }
5777
Steve Antonba42e992018-04-09 14:10:01 -07005778 if (IsUnifiedPlan()) {
5779 // Ensure that each audio and video media section has at most one
5780 // "StreamParams". This will return an error if receiving a session
5781 // description from a "Plan B" endpoint which adds multiple tracks of the
5782 // same type. With Unified Plan, there can only be at most one track per
5783 // media section.
5784 for (const ContentInfo& content : sdesc->description()->contents()) {
5785 const MediaContentDescription& desc = *content.description;
5786 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5787 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5788 desc.streams().size() > 1u) {
5789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5790 "Media section has more than one track specified "
5791 "with a=ssrc lines which is not supported with "
5792 "Unified Plan.");
5793 }
5794 }
5795 }
5796
Steve Anton8a006912017-12-04 15:25:56 -08005797 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005798}
5799
Steve Anton3828c062017-12-06 10:34:51 -08005800bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005801 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005802 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005803 return (state == PeerConnectionInterface::kStable) ||
5804 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005805 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005806 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005807 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5808 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5809 }
5810}
5811
Steve Anton3828c062017-12-06 10:34:51 -08005812bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005813 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005814 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005815 return (state == PeerConnectionInterface::kStable) ||
5816 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005817 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005818 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005819 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5820 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5821 }
5822}
5823
Steve Antonf8470812017-12-04 10:46:21 -08005824const char* PeerConnection::SessionErrorToString(SessionError error) const {
5825 switch (error) {
5826 case SessionError::kNone:
5827 return "ERROR_NONE";
5828 case SessionError::kContent:
5829 return "ERROR_CONTENT";
5830 case SessionError::kTransport:
5831 return "ERROR_TRANSPORT";
5832 }
5833 RTC_NOTREACHED();
5834 return "";
5835}
5836
Steve Anton75737c02017-11-06 10:37:17 -08005837std::string PeerConnection::GetSessionErrorMsg() {
5838 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005839 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5840 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005841 return desc.str();
5842}
5843
Steve Anton8e20f172018-03-06 10:55:04 -08005844void PeerConnection::ReportSdpFormatReceived(
5845 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005846 int num_audio_mlines = 0;
5847 int num_video_mlines = 0;
5848 int num_audio_tracks = 0;
5849 int num_video_tracks = 0;
5850 for (const ContentInfo& content : remote_offer.description()->contents()) {
5851 cricket::MediaType media_type = content.media_description()->type();
5852 int num_tracks = std::max(
5853 1, static_cast<int>(content.media_description()->streams().size()));
5854 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5855 num_audio_mlines += 1;
5856 num_audio_tracks += num_tracks;
5857 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5858 num_video_mlines += 1;
5859 num_video_tracks += num_tracks;
5860 }
5861 }
5862 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5863 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5864 format = kSdpFormatReceivedComplexUnifiedPlan;
5865 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5866 format = kSdpFormatReceivedComplexPlanB;
5867 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5868 format = kSdpFormatReceivedSimple;
5869 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005870 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5871 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005872}
5873
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005874void PeerConnection::NoteUsageEvent(UsageEvent event) {
5875 RTC_DCHECK_RUN_ON(signaling_thread());
5876 usage_event_accumulator_ |= static_cast<int>(event);
5877}
5878
5879void PeerConnection::ReportUsagePattern() const {
5880 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005881 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5882 usage_event_accumulator_,
5883 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005884 const int bad_bits =
5885 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5886 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5887 const int good_bits =
5888 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5889 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5890 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5891 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5892 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005893 // If called after close(), we can't report, because observer may have
5894 // been deallocated, and therefore pointer is null. Write to log instead.
5895 if (observer_) {
5896 Observer()->OnInterestingUsage(usage_event_accumulator_);
5897 } else {
5898 RTC_LOG(LS_INFO) << "Interesting usage signature "
5899 << usage_event_accumulator_
5900 << " observed after observer shutdown";
5901 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005902 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005903}
5904
Steve Anton0ffaaa22018-02-23 10:31:30 -08005905void PeerConnection::ReportNegotiatedSdpSemantics(
5906 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005907 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005908 switch (answer.description()->msid_signaling()) {
5909 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005910 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005911 break;
5912 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005913 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005914 break;
5915 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005916 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005917 break;
5918 case cricket::kMsidSignalingMediaSection |
5919 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005920 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005921 break;
5922 default:
5923 RTC_NOTREACHED();
5924 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005925 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5926 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005927}
5928
Steve Anton75737c02017-11-06 10:37:17 -08005929// We need to check the local/remote description for the Transport instead of
5930// the session, because a new Transport added during renegotiation may have
5931// them unset while the session has them set from the previous negotiation.
5932// Not doing so may trigger the auto generation of transport description and
5933// mess up DTLS identity information, ICE credential, etc.
5934bool PeerConnection::ReadyToUseRemoteCandidate(
5935 const IceCandidateInterface* candidate,
5936 const SessionDescriptionInterface* remote_desc,
5937 bool* valid) {
5938 *valid = true;
5939
5940 const SessionDescriptionInterface* current_remote_desc =
5941 remote_desc ? remote_desc : remote_description();
5942
5943 if (!current_remote_desc) {
5944 return false;
5945 }
5946
5947 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5948 size_t remote_content_size =
5949 current_remote_desc->description()->contents().size();
5950 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005951 RTC_LOG(LS_ERROR)
5952 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5953 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005954
5955 *valid = false;
5956 return false;
5957 }
5958
5959 cricket::ContentInfo content =
5960 current_remote_desc->description()->contents()[mediacontent_index];
5961
5962 const std::string transport_name = GetTransportName(content.name);
5963 if (transport_name.empty()) {
5964 return false;
5965 }
Zhi Huange830e682018-03-30 10:48:35 -07005966 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005967}
5968
5969bool PeerConnection::SrtpRequired() const {
5970 return dtls_enabled_ ||
5971 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5972}
5973
5974void PeerConnection::OnTransportControllerGatheringState(
5975 cricket::IceGatheringState state) {
5976 RTC_DCHECK(signaling_thread()->IsCurrent());
5977 if (state == cricket::kIceGatheringGathering) {
5978 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5979 } else if (state == cricket::kIceGatheringComplete) {
5980 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5981 }
5982}
5983
5984void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005985 std::map<std::string, std::set<cricket::MediaType>>
5986 media_types_by_transport_name;
5987 for (auto transceiver : transceivers_) {
5988 if (transceiver->internal()->channel()) {
5989 const std::string& transport_name =
5990 transceiver->internal()->channel()->transport_name();
5991 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005992 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005993 }
Steve Anton75737c02017-11-06 10:37:17 -08005994 }
5995 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005996 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5997 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005998 }
Zhi Huange830e682018-03-30 10:48:35 -07005999
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006000 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006001 if (transport_name) {
6002 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006003 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006004 }
Zhi Huange830e682018-03-30 10:48:35 -07006005
Steve Antonc7b964c2018-02-01 14:39:45 -08006006 for (const auto& entry : media_types_by_transport_name) {
6007 const std::string& transport_name = entry.first;
6008 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006009 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006010 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006011 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006012 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
6014 }
6015}
6016// Walk through the ConnectionInfos to gather best connection usage
6017// for IPv4 and IPv6.
6018void PeerConnection::ReportBestConnectionState(
6019 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006020 for (const cricket::TransportChannelStats& channel_stats :
6021 stats.channel_stats) {
6022 for (const cricket::ConnectionInfo& connection_info :
6023 channel_stats.connection_infos) {
6024 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006025 continue;
6026 }
6027
Steve Antonc7b964c2018-02-01 14:39:45 -08006028 const cricket::Candidate& local = connection_info.local_candidate;
6029 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006030
6031 // Increment the counter for IceCandidatePairType.
6032 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6033 (local.type() == RELAY_PORT_TYPE &&
6034 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006035 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6036 GetIceCandidatePairCounter(local, remote),
6037 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006038 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006039 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6040 GetIceCandidatePairCounter(local, remote),
6041 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006042 } else {
6043 RTC_CHECK(0);
6044 }
Steve Anton75737c02017-11-06 10:37:17 -08006045
6046 // Increment the counter for IP type.
6047 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006048 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6049 kBestConnections_IPv4,
6050 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006051 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006052 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6053 kBestConnections_IPv6,
6054 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006055 } else {
6056 RTC_CHECK(0);
6057 }
6058
6059 return;
6060 }
6061 }
6062}
6063
6064void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006065 const cricket::TransportStats& stats,
6066 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006067 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6068 return;
6069 }
6070
6071 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6072 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6073 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6074 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6075 return;
6076 }
6077
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006078 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6079 for (cricket::MediaType media_type : media_types) {
6080 switch (media_type) {
6081 case cricket::MEDIA_TYPE_AUDIO:
6082 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6083 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6084 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6085 break;
6086 case cricket::MEDIA_TYPE_VIDEO:
6087 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6088 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6089 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6090 break;
6091 case cricket::MEDIA_TYPE_DATA:
6092 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6093 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6094 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6095 break;
6096 default:
6097 RTC_NOTREACHED();
6098 continue;
6099 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006100 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006101 }
6102
6103 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6104 for (cricket::MediaType media_type : media_types) {
6105 switch (media_type) {
6106 case cricket::MEDIA_TYPE_AUDIO:
6107 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6108 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6109 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6110 break;
6111 case cricket::MEDIA_TYPE_VIDEO:
6112 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6113 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6114 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6115 break;
6116 case cricket::MEDIA_TYPE_DATA:
6117 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6118 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6119 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6120 break;
6121 default:
6122 RTC_NOTREACHED();
6123 continue;
6124 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006125 }
Steve Anton75737c02017-11-06 10:37:17 -08006126 }
6127}
6128
6129void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6130 RTC_DCHECK(worker_thread()->IsCurrent());
6131 RTC_DCHECK(call_);
6132 call_->OnSentPacket(sent_packet);
6133}
6134
6135const std::string PeerConnection::GetTransportName(
6136 const std::string& content_name) {
6137 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006138 if (channel) {
6139 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006140 }
Steve Anton6fec8802017-12-04 10:37:29 -08006141 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006142 RTC_DCHECK(sctp_mid_);
6143 if (content_name == *sctp_mid_) {
6144 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006145 }
6146 }
6147 // Return an empty string if failed to retrieve the transport name.
6148 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006149}
6150
Steve Anton6fec8802017-12-04 10:37:29 -08006151void PeerConnection::DestroyTransceiverChannel(
6152 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6153 transceiver) {
6154 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006155
Steve Anton6fec8802017-12-04 10:37:29 -08006156 cricket::BaseChannel* channel = transceiver->internal()->channel();
6157 if (channel) {
6158 transceiver->internal()->SetChannel(nullptr);
6159 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006160 }
6161}
6162
6163void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006164 if (rtp_data_channel_) {
6165 OnDataChannelDestroyed();
6166 DestroyBaseChannel(rtp_data_channel_);
6167 rtp_data_channel_ = nullptr;
6168 }
6169
6170 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6171 // grab a reference to this PeerConnection. If this is called from the
6172 // PeerConnection destructor, the RefCountedObject vtable will have already
6173 // been destroyed (since it is a subclass of PeerConnection) and using
6174 // rtc::Bind will cause "Pure virtual function called" error to appear.
6175
6176 if (sctp_transport_) {
6177 OnDataChannelDestroyed();
6178 network_thread()->Invoke<void>(RTC_FROM_HERE,
6179 [this] { DestroySctpTransport_n(); });
6180 }
6181}
6182
6183void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6184 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006185 switch (channel->media_type()) {
6186 case cricket::MEDIA_TYPE_AUDIO:
6187 channel_manager()->DestroyVoiceChannel(
6188 static_cast<cricket::VoiceChannel*>(channel));
6189 break;
6190 case cricket::MEDIA_TYPE_VIDEO:
6191 channel_manager()->DestroyVideoChannel(
6192 static_cast<cricket::VideoChannel*>(channel));
6193 break;
6194 case cricket::MEDIA_TYPE_DATA:
6195 channel_manager()->DestroyRtpDataChannel(
6196 static_cast<cricket::RtpDataChannel*>(channel));
6197 break;
6198 default:
6199 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6200 break;
6201 }
Zhi Huange830e682018-03-30 10:48:35 -07006202}
Steve Anton6fec8802017-12-04 10:37:29 -08006203
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006204bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006205 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006206 RtpTransportInternal* rtp_transport,
6207 cricket::DtlsTransportInternal* dtls_transport) {
6208 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006209 auto base_channel = GetChannel(mid);
6210 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006211 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006212 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006213 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006214 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006215 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006216 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006217}
6218
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006219PeerConnectionObserver* PeerConnection::Observer() const {
6220 // In earlier production code, the pointer was not cleared on close,
6221 // which might have led to undefined behavior if the observer was not
6222 // deallocated, or strange crashes if it was.
6223 // We use CHECK in order to catch such behavior if it exists.
6224 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6225 RTC_CHECK(observer_);
6226 return observer_;
6227}
6228
Harald Alvestrand89061872018-01-02 14:08:34 +01006229void PeerConnection::ClearStatsCache() {
6230 if (stats_collector_) {
6231 stats_collector_->ClearCachedStatsReport();
6232 }
6233}
6234
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006235void PeerConnection::RequestUsagePatternReportForTesting() {
6236 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6237 nullptr);
6238}
6239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006240} // namespace webrtc