blob: ea5d9228ef1c40bb864815ed6bed5b6c084ebf5d [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 Wang1a2cc0a2018-07-10 15:17:12 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800109 MSG_FREE_DATACHANNELS,
Harald Alvestrand19793842018-06-25 12:03:50 +0200110 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111};
112
Harald Alvestrand19793842018-06-25 12:03:50 +0200113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200118 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100121 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000122};
123
deadbeefab9b2d12015-10-14 11:33:11 -0700124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100130 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700131};
132
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200136 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000139};
140
deadbeefab9b2d12015-10-14 11:33:11 -0700141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
176 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700177 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700178 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
179 if (audio_media_description_options) {
180 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 } else {
184 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
185 if (video_media_description_options) {
186 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700187 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700188 }
189 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700190 }
zhihuang1c378ed2017-08-17 14:10:50 -0700191}
olka3c747662017-08-17 06:50:32 -0700192
zhihuang1c378ed2017-08-17 14:10:50 -0700193// Add options to |session_options| from |rtp_data_channels|.
194void AddRtpDataChannelOptions(
195 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
196 rtp_data_channels,
197 cricket::MediaDescriptionOptions* data_media_description_options) {
198 if (!data_media_description_options) {
199 return;
200 }
deadbeefab9b2d12015-10-14 11:33:11 -0700201 // Check for data channels.
202 for (const auto& kv : rtp_data_channels) {
203 const DataChannel* channel = kv.second;
204 if (channel->state() == DataChannel::kConnecting ||
205 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700206 // Legacy RTP data channels are signaled with the track/stream ID set to
207 // the data channel's label.
208 data_media_description_options->AddRtpDataChannel(channel->label(),
209 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700210 }
211 }
212}
213
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700214uint32_t ConvertIceTransportTypeToCandidateFilter(
215 PeerConnectionInterface::IceTransportsType type) {
216 switch (type) {
217 case PeerConnectionInterface::kNone:
218 return cricket::CF_NONE;
219 case PeerConnectionInterface::kRelay:
220 return cricket::CF_RELAY;
221 case PeerConnectionInterface::kNoHost:
222 return (cricket::CF_ALL & ~cricket::CF_HOST);
223 case PeerConnectionInterface::kAll:
224 return cricket::CF_ALL;
225 default:
nissec80e7412017-01-11 05:56:46 -0800226 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700227 }
228 return cricket::CF_NONE;
229}
230
deadbeef293e9262017-01-11 12:28:30 -0800231// Helper to set an error and return from a method.
232bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
233 if (error) {
234 error->set_type(type);
235 }
236 return type == webrtc::RTCErrorType::NONE;
237}
238
Steve Anton038834f2017-07-14 15:59:59 -0700239bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
240 if (error_out) {
241 *error_out = std::move(error);
242 }
243 return error.ok();
244}
245
Steve Antonba818672017-11-06 10:21:57 -0800246std::string GetSignalingStateString(
247 PeerConnectionInterface::SignalingState state) {
248 switch (state) {
249 case PeerConnectionInterface::kStable:
250 return "kStable";
251 case PeerConnectionInterface::kHaveLocalOffer:
252 return "kHaveLocalOffer";
253 case PeerConnectionInterface::kHaveLocalPrAnswer:
254 return "kHavePrAnswer";
255 case PeerConnectionInterface::kHaveRemoteOffer:
256 return "kHaveRemoteOffer";
257 case PeerConnectionInterface::kHaveRemotePrAnswer:
258 return "kHaveRemotePrAnswer";
259 case PeerConnectionInterface::kClosed:
260 return "kClosed";
261 }
262 RTC_NOTREACHED();
263 return "";
264}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700265
Steve Anton75737c02017-11-06 10:37:17 -0800266IceCandidatePairType GetIceCandidatePairCounter(
267 const cricket::Candidate& local,
268 const cricket::Candidate& remote) {
269 const auto& l = local.type();
270 const auto& r = remote.type();
271 const auto& host = LOCAL_PORT_TYPE;
272 const auto& srflx = STUN_PORT_TYPE;
273 const auto& relay = RELAY_PORT_TYPE;
274 const auto& prflx = PRFLX_PORT_TYPE;
275 if (l == host && r == host) {
276 bool local_private = IPIsPrivate(local.address().ipaddr());
277 bool remote_private = IPIsPrivate(remote.address().ipaddr());
278 if (local_private) {
279 if (remote_private) {
280 return kIceCandidatePairHostPrivateHostPrivate;
281 } else {
282 return kIceCandidatePairHostPrivateHostPublic;
283 }
284 } else {
285 if (remote_private) {
286 return kIceCandidatePairHostPublicHostPrivate;
287 } else {
288 return kIceCandidatePairHostPublicHostPublic;
289 }
290 }
291 }
292 if (l == host && r == srflx)
293 return kIceCandidatePairHostSrflx;
294 if (l == host && r == relay)
295 return kIceCandidatePairHostRelay;
296 if (l == host && r == prflx)
297 return kIceCandidatePairHostPrflx;
298 if (l == srflx && r == host)
299 return kIceCandidatePairSrflxHost;
300 if (l == srflx && r == srflx)
301 return kIceCandidatePairSrflxSrflx;
302 if (l == srflx && r == relay)
303 return kIceCandidatePairSrflxRelay;
304 if (l == srflx && r == prflx)
305 return kIceCandidatePairSrflxPrflx;
306 if (l == relay && r == host)
307 return kIceCandidatePairRelayHost;
308 if (l == relay && r == srflx)
309 return kIceCandidatePairRelaySrflx;
310 if (l == relay && r == relay)
311 return kIceCandidatePairRelayRelay;
312 if (l == relay && r == prflx)
313 return kIceCandidatePairRelayPrflx;
314 if (l == prflx && r == host)
315 return kIceCandidatePairPrflxHost;
316 if (l == prflx && r == srflx)
317 return kIceCandidatePairPrflxSrflx;
318 if (l == prflx && r == relay)
319 return kIceCandidatePairPrflxRelay;
320 return kIceCandidatePairMax;
321}
322
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800323// Logic to decide if an m= section can be recycled. This means that the new
324// m= section is not rejected, but the old local or remote m= section is
325// rejected. |old_content_one| and |old_content_two| refer to the m= section
326// of the old remote and old local descriptions in no particular order.
327// We need to check both the old local and remote because either
328// could be the most current from the latest negotation.
329bool IsMediaSectionBeingRecycled(SdpType type,
330 const ContentInfo& content,
331 const ContentInfo* old_content_one,
332 const ContentInfo* old_content_two) {
333 return type == SdpType::kOffer && !content.rejected &&
334 ((old_content_one && old_content_one->rejected) ||
335 (old_content_two && old_content_two->rejected));
336}
337
Steve Anton75737c02017-11-06 10:37:17 -0800338// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800339// |current_desc|. The number of m= sections in |new_desc| should be no
340// less than |current_desc|. In the case of checking an answer's
341// |new_desc|, the |current_desc| is the last offer that was set as the
342// local or remote. In the case of checking an offer's |new_desc| we
343// check against the local and remote descriptions stored from the last
344// negotiation, because either of these could be the most up to date for
345// possible rejected m sections. These are the |current_desc| and
346// |secondary_current_desc|.
347bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
348 const SessionDescription* secondary_current_desc,
349 const SessionDescription& new_desc,
350 const SdpType type) {
351 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800352 return false;
353 }
354
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800355 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
356 const cricket::ContentInfo* secondary_content_info = nullptr;
357 if (secondary_current_desc &&
358 i < secondary_current_desc->contents().size()) {
359 secondary_content_info = &secondary_current_desc->contents()[i];
360 }
361 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
362 &current_desc.contents()[i],
363 secondary_content_info)) {
364 // For new offer descriptions, if the media section can be recycled, it's
365 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800366 continue;
367 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800369 return false;
370 }
371 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 new_desc.contents()[i].media_description();
373 const MediaContentDescription* current_desc_mdesc =
374 current_desc.contents()[i].media_description();
375 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800376 return false;
377 }
378 }
379 return true;
380}
381
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800382bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
383 const SessionDescription& desc2) {
384 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800385}
386
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -0700387void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
388 cricket::MediaType media_type) {
389 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
390 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100391 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
392 KeyExchangeProtocolMedia>
393 proto_media_counter_map = {
394 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
395 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
396 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
397 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
399 kEnumCounterKeyProtocolMediaTypeDtlsData},
400 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
401 kEnumCounterKeyProtocolMediaTypeSdesAudio},
402 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
403 kEnumCounterKeyProtocolMediaTypeSdesVideo},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
405 kEnumCounterKeyProtocolMediaTypeSdesData}};
406
407 auto it = proto_media_counter_map.find({protocol_type, media_type});
408 if (it != proto_media_counter_map.end()) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -0700409 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
410 it->second, kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100411 }
412}
413
Steve Anton75737c02017-11-06 10:37:17 -0800414// Checks that each non-rejected content has SDES crypto keys or a DTLS
415// fingerprint, unless it's in a BUNDLE group, in which case only the
416// BUNDLE-tag section (first media section/description in the BUNDLE group)
417// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
418// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
419// by Channel's |srtp_required| check.
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -0700420RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800421 const cricket::ContentGroup* bundle =
422 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800423 for (const cricket::ContentInfo& content_info : desc->contents()) {
424 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800425 continue;
426 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100427 // Note what media is used with each crypto protocol, for all sections.
428 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
429 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -0700430 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800431 const std::string& mid = content_info.name;
432 if (bundle && bundle->HasContentName(mid) &&
433 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800434 // This isn't the first media section in the BUNDLE group, so it's not
435 // required to have crypto attributes, since only the crypto attributes
436 // from the first section actually get used.
437 continue;
438 }
439
440 // If the content isn't rejected or bundled into another m= section, crypto
441 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800442 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800443 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800444 if (!media || !tinfo) {
445 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800447 }
448 if (dtls_enabled) {
449 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_WARNING)
451 << "Session description must have DTLS fingerprint if "
452 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800453 return RTCError(RTCErrorType::INVALID_PARAMETER,
454 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800455 }
456 } else {
457 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800459 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800461 }
462 }
463 }
Steve Anton8a006912017-12-04 15:25:56 -0800464 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800465}
466
467// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
468// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
469// media section/description in the BUNDLE group) needs a ufrag and pwd.
470bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
471 const cricket::ContentGroup* bundle =
472 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800473 for (const cricket::ContentInfo& content_info : desc->contents()) {
474 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800475 continue;
476 }
Steve Anton8a006912017-12-04 15:25:56 -0800477 const std::string& mid = content_info.name;
478 if (bundle && bundle->HasContentName(mid) &&
479 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 // This isn't the first media section in the BUNDLE group, so it's not
481 // required to have ufrag/password, since only the ufrag/password from
482 // the first section actually get used.
483 continue;
484 }
485
486 // If the content isn't rejected or bundled into another m= section,
487 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800488 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800489 if (!tinfo) {
490 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100491 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800492 return false;
493 }
494 if (tinfo->description.ice_ufrag.empty() ||
495 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800497 return false;
498 }
499 }
500 return true;
501}
502
503bool GetTrackIdBySsrc(const SessionDescription* session_description,
504 uint32_t ssrc,
505 std::string* track_id) {
506 RTC_DCHECK(track_id != NULL);
507
Steve Antonb1c1de12017-12-21 15:14:30 -0800508 const cricket::AudioContentDescription* audio_desc =
509 cricket::GetFirstAudioContentDescription(session_description);
510 if (audio_desc) {
511 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800512 if (found) {
513 *track_id = found->id;
514 return true;
515 }
516 }
517
Steve Antonb1c1de12017-12-21 15:14:30 -0800518 const cricket::VideoContentDescription* video_desc =
519 cricket::GetFirstVideoContentDescription(session_description);
520 if (video_desc) {
521 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800522 if (found) {
523 *track_id = found->id;
524 return true;
525 }
526 }
527 return false;
528}
529
530// Get the SCTP port out of a SessionDescription.
531// Return -1 if not found.
532int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800533 const cricket::DataContentDescription* data_desc =
534 GetFirstDataContentDescription(session_description);
535 RTC_DCHECK(data_desc);
536 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800537 return -1;
538 }
Steve Anton75737c02017-11-06 10:37:17 -0800539 std::string value;
540 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
541 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800542 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 if (!codec.Matches(match_pattern)) {
544 continue;
545 }
546 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
547 return rtc::FromString<int>(value);
548 }
549 }
550 return -1;
551}
552
Steve Anton75737c02017-11-06 10:37:17 -0800553// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
554bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
555 const SessionDescriptionInterface* new_desc,
556 const std::string& content_name) {
557 if (!old_desc) {
558 return false;
559 }
560 const SessionDescription* new_sd = new_desc->description();
561 const SessionDescription* old_sd = old_desc->description();
562 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
563 if (!cinfo || cinfo->rejected) {
564 return false;
565 }
566 // If the content isn't rejected, check if ufrag and password has changed.
567 const cricket::TransportDescription* new_transport_desc =
568 new_sd->GetTransportDescriptionByName(content_name);
569 const cricket::TransportDescription* old_transport_desc =
570 old_sd->GetTransportDescriptionByName(content_name);
571 if (!new_transport_desc || !old_transport_desc) {
572 // No transport description exists. This is not an ICE restart.
573 return false;
574 }
575 if (cricket::IceCredentialsChanged(
576 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
577 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100578 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
579 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800580 return true;
581 }
582 return false;
583}
584
Steve Anton80dd7b52018-02-16 17:08:42 -0800585// Generates a string error message for SetLocalDescription/SetRemoteDescription
586// from an RTCError.
587std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
588 SdpType type,
589 const RTCError& error) {
590 std::ostringstream oss;
591 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
592 << " " << SdpTypeToString(type) << " sdp: " << error.message();
593 return oss.str();
594}
595
Seth Hampson5b4f0752018-04-02 16:31:36 -0700596std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
597 std::string output = "streams=[";
598 const char* separator = "";
599 for (const auto& stream_id : stream_ids) {
600 output.append(separator).append(stream_id);
601 separator = ", ";
602 }
603 output.append("]");
604 return output;
605}
606
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200607absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700608 int rtc_configuration_parameter) {
609 if (rtc_configuration_parameter ==
610 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200611 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700612 }
613 return rtc_configuration_parameter;
614}
615
Steve Anton75737c02017-11-06 10:37:17 -0800616} // namespace
617
Henrik Boström31638672017-11-23 17:48:32 +0100618// Upon completion, posts a task to execute the callback of the
619// SetSessionDescriptionObserver asynchronously on the same thread. At this
620// point, the state of the peer connection might no longer reflect the effects
621// of the SetRemoteDescription operation, as the peer connection could have been
622// modified during the post.
623// TODO(hbos): Remove this class once we remove the version of
624// PeerConnectionInterface::SetRemoteDescription() that takes a
625// SetSessionDescriptionObserver as an argument.
626class PeerConnection::SetRemoteDescriptionObserverAdapter
627 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
628 public:
629 SetRemoteDescriptionObserverAdapter(
630 rtc::scoped_refptr<PeerConnection> pc,
631 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
632 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
633
634 // SetRemoteDescriptionObserverInterface implementation.
635 void OnSetRemoteDescriptionComplete(RTCError error) override {
636 if (error.ok())
637 pc_->PostSetSessionDescriptionSuccess(wrapper_);
638 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100639 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100640 }
641
642 private:
643 rtc::scoped_refptr<PeerConnection> pc_;
644 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
645};
646
deadbeef293e9262017-01-11 12:28:30 -0800647bool PeerConnectionInterface::RTCConfiguration::operator==(
648 const PeerConnectionInterface::RTCConfiguration& o) const {
649 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700650 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800651 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000652 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700653 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800654 BundlePolicy bundle_policy;
655 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700656 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
657 int ice_candidate_pool_size;
658 bool disable_ipv6;
659 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700660 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100661 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700662 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200663 absl::optional<int> screencast_min_bitrate;
664 absl::optional<bool> combined_audio_video_bwe;
665 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800666 TcpCandidatePolicy tcp_candidate_policy;
667 CandidateNetworkPolicy candidate_network_policy;
668 int audio_jitter_buffer_max_packets;
669 bool audio_jitter_buffer_fast_accelerate;
670 int ice_connection_receiving_timeout;
671 int ice_backup_candidate_pair_ping_interval;
672 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800673 bool prioritize_most_likely_ice_candidate_pairs;
674 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800675 bool prune_turn_ports;
676 bool presume_writable_when_fully_relayed;
677 bool enable_ice_renomination;
678 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200679 absl::optional<int> ice_check_interval_strong_connectivity;
680 absl::optional<int> ice_check_interval_weak_connectivity;
681 absl::optional<int> ice_check_min_interval;
682 absl::optional<int> ice_unwritable_timeout;
683 absl::optional<int> ice_unwritable_min_checks;
684 absl::optional<int> stun_candidate_keepalive_interval;
685 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200686 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800687 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200688 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700689 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800690 };
691 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
692 "Did you add something to RTCConfiguration and forget to "
693 "update operator==?");
694 return type == o.type && servers == o.servers &&
695 bundle_policy == o.bundle_policy &&
696 rtcp_mux_policy == o.rtcp_mux_policy &&
697 tcp_candidate_policy == o.tcp_candidate_policy &&
698 candidate_network_policy == o.candidate_network_policy &&
699 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
700 audio_jitter_buffer_fast_accelerate ==
701 o.audio_jitter_buffer_fast_accelerate &&
702 ice_connection_receiving_timeout ==
703 o.ice_connection_receiving_timeout &&
704 ice_backup_candidate_pair_ping_interval ==
705 o.ice_backup_candidate_pair_ping_interval &&
706 continual_gathering_policy == o.continual_gathering_policy &&
707 certificates == o.certificates &&
708 prioritize_most_likely_ice_candidate_pairs ==
709 o.prioritize_most_likely_ice_candidate_pairs &&
710 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800711 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700712 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100713 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800714 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800715 screencast_min_bitrate == o.screencast_min_bitrate &&
716 combined_audio_video_bwe == o.combined_audio_video_bwe &&
717 enable_dtls_srtp == o.enable_dtls_srtp &&
718 ice_candidate_pool_size == o.ice_candidate_pool_size &&
719 prune_turn_ports == o.prune_turn_ports &&
720 presume_writable_when_fully_relayed ==
721 o.presume_writable_when_fully_relayed &&
722 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800723 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800724 ice_check_interval_strong_connectivity ==
725 o.ice_check_interval_strong_connectivity &&
726 ice_check_interval_weak_connectivity ==
727 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700728 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700729 ice_unwritable_timeout == o.ice_unwritable_timeout &&
730 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800731 stun_candidate_keepalive_interval ==
732 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800734 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800735 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 network_preference == o.network_preference &&
737 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800738}
739
740bool PeerConnectionInterface::RTCConfiguration::operator!=(
741 const PeerConnectionInterface::RTCConfiguration& o) const {
742 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800743}
744
zhihuang8f65cdf2016-05-06 18:40:30 -0700745// Generate a RTCP CNAME when a PeerConnection is created.
746std::string GenerateRtcpCname() {
747 std::string cname;
748 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100749 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800750 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700751 }
752 return cname;
753}
754
zhihuang1c378ed2017-08-17 14:10:50 -0700755bool ValidateOfferAnswerOptions(
756 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
757 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
758 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700759}
760
zhihuang1c378ed2017-08-17 14:10:50 -0700761// From |rtc_options|, fill parts of |session_options| shared by all generated
762// m= sections (in other words, nothing that involves a map/array).
763void ExtractSharedMediaSessionOptions(
764 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
765 cricket::MediaSessionOptions* session_options) {
766 session_options->vad_enabled = rtc_options.voice_activity_detection;
767 session_options->bundle_enabled = rtc_options.use_rtp_mux;
768}
zhihuanga77e6bb2017-08-14 18:17:48 -0700769
zhihuang1c378ed2017-08-17 14:10:50 -0700770bool ConvertConstraintsToOfferAnswerOptions(
771 const MediaConstraintsInterface* constraints,
772 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700773 if (!constraints) {
774 return true;
775 }
zhihuang1c378ed2017-08-17 14:10:50 -0700776
777 bool value = false;
778 size_t mandatory_constraints_satisfied = 0;
779
780 if (FindConstraint(constraints,
781 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
782 &mandatory_constraints_satisfied)) {
783 offer_answer_options->offer_to_receive_audio =
784 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
785 kOfferToReceiveMediaTrue
786 : 0;
787 }
788
789 if (FindConstraint(constraints,
790 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
791 &mandatory_constraints_satisfied)) {
792 offer_answer_options->offer_to_receive_video =
793 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
794 kOfferToReceiveMediaTrue
795 : 0;
796 }
797 if (FindConstraint(constraints,
798 MediaConstraintsInterface::kVoiceActivityDetection, &value,
799 &mandatory_constraints_satisfied)) {
800 offer_answer_options->voice_activity_detection = value;
801 }
802 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
803 &mandatory_constraints_satisfied)) {
804 offer_answer_options->use_rtp_mux = value;
805 }
806 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
807 &value, &mandatory_constraints_satisfied)) {
808 offer_answer_options->ice_restart = value;
809 }
810
deadbeefab9b2d12015-10-14 11:33:11 -0700811 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
812}
813
zhihuang38ede132017-06-15 12:52:32 -0700814PeerConnection::PeerConnection(PeerConnectionFactory* factory,
815 std::unique_ptr<RtcEventLog> event_log,
816 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700818 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700819 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700820 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700821 remote_streams_(StreamCollection::Create()),
822 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823
824PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100825 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800826 RTC_DCHECK_RUN_ON(signaling_thread());
827
Steve Anton8af21862017-12-15 11:20:13 -0800828 // Need to stop transceivers before destroying the stats collector because
829 // AudioRtpSender has a reference to the StatsCollector it will update when
830 // stopping.
831 for (auto transceiver : transceivers_) {
832 transceiver->Stop();
833 }
Steve Anton4171afb2017-11-20 10:20:22 -0800834
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700835 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800836 if (stats_collector_) {
837 stats_collector_->WaitForPendingRequest();
838 stats_collector_ = nullptr;
839 }
Steve Anton75737c02017-11-06 10:37:17 -0800840
Steve Anton8af21862017-12-15 11:20:13 -0800841 // Don't destroy BaseChannels until after stats has been cleaned up so that
842 // the last stats request can still read from the channels.
843 DestroyAllChannels();
844
Mirko Bonadei675513b2017-11-09 11:09:25 +0100845 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800846
847 webrtc_session_desc_factory_.reset();
848 sctp_invoker_.reset();
849 sctp_factory_.reset();
850 transport_controller_.reset();
851
deadbeef91dd5672016-05-18 16:55:30 -0700852 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700853 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700854 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700855 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700856 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700857 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800858 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700859 event_log_.reset();
860 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861}
862
Steve Anton8af21862017-12-15 11:20:13 -0800863void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800864 // Destroy video channels first since they may have a pointer to a voice
865 // channel.
866 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800867 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800868 DestroyTransceiverChannel(transceiver);
869 }
870 }
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800872 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 DestroyDataChannel();
877}
878
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000879bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000880 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700881 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100882 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700883
884 RTCError config_error = ValidateConfiguration(configuration);
885 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700887 return false;
888 }
889
Benjamin Wrightcab58882018-05-02 15:12:47 -0700890 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_ERROR)
892 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100893 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800894 return false;
895 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200896
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800898 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100900 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800901 return false;
902 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700903
Benjamin Wrightcab58882018-05-02 15:12:47 -0700904 observer_ = dependencies.observer;
905 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700906 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800907
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200908 cricket::ServerAddresses stun_servers;
909 std::vector<cricket::RelayServerConfig> turn_servers;
910
911 RTCErrorType parse_error =
912 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
913 if (parse_error != RTCErrorType::NONE) {
914 return false;
915 }
916
deadbeef91dd5672016-05-18 16:55:30 -0700917 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700918 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700919 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200920 RTC_FROM_HERE,
921 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
922 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923 return false;
924 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200925 // If initialization was successful, note if STUN or TURN servers
926 // were supplied.
927 if (!stun_servers.empty()) {
928 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
929 }
930 if (!turn_servers.empty()) {
931 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
932 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -0700934 // Send information about IPv4/IPv6 status.
935 PeerConnectionAddressFamilyCounter address_family;
936 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
937 address_family = kPeerConnection_IPv6;
938 } else {
939 address_family = kPeerConnection_IPv4;
940 }
941 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
942 kPeerConnectionAddressFamilyCounter_Max);
943
Zhi Huange830e682018-03-30 10:48:35 -0700944 const PeerConnectionFactoryInterface::Options& options = factory_->options();
945
Steve Anton75737c02017-11-06 10:37:17 -0800946 // RFC 3264: The numeric value of the session id and version in the
947 // o line MUST be representable with a "64 bit signed integer".
948 // Due to this constraint session id |session_id_| is max limited to
949 // LLONG_MAX.
950 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700951 JsepTransportController::Config config;
952 config.redetermine_role_on_ice_restart =
953 configuration.redetermine_role_on_ice_restart;
954 config.ssl_max_version = factory_->options().ssl_max_version;
955 config.disable_encryption = options.disable_encryption;
956 config.bundle_policy = configuration.bundle_policy;
957 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
958 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700959 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700960 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700961#if defined(ENABLE_EXTERNAL_AUTH)
962 config.enable_external_auth = true;
963#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700964 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700965 transport_controller_.reset(new JsepTransportController(
966 signaling_thread(), network_thread(), port_allocator_.get(), config));
967 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800968 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700969 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800970 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700971 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800972 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700973 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800974 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
975 transport_controller_->SignalDtlsHandshakeError.connect(
976 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
977
978 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700979
deadbeefab9b2d12015-10-14 11:33:11 -0700980 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700981 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982
Steve Antonba818672017-11-06 10:21:57 -0800983 configuration_ = configuration;
984
Steve Anton75737c02017-11-06 10:37:17 -0800985 // Obtain a certificate from RTCConfiguration if any were provided (optional).
986 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
987 if (!configuration.certificates.empty()) {
988 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
989 // just picking the first one. The decision should be made based on the DTLS
990 // handshake. The DTLS negotiations need to know about all certificates.
991 certificate = configuration.certificates[0];
992 }
993
Steve Antond25da372017-11-06 14:50:29 -0800994 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800995
996 if (options.disable_encryption) {
997 dtls_enabled_ = false;
998 } else {
999 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001000 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001001 // |configuration| can override the default |dtls_enabled_| value.
1002 if (configuration.enable_dtls_srtp) {
1003 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1004 }
1005 }
1006
1007 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1008 // It takes precendence over the disable_sctp_data_channels
1009 // PeerConnectionFactoryInterface::Options.
1010 if (configuration.enable_rtp_data_channel) {
1011 data_channel_type_ = cricket::DCT_RTP;
1012 } else {
1013 // DTLS has to be enabled to use SCTP.
1014 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1015 data_channel_type_ = cricket::DCT_SCTP;
1016 }
1017 }
1018
1019 video_options_.screencast_min_bitrate_kbps =
1020 configuration.screencast_min_bitrate;
1021 audio_options_.combined_audio_video_bwe =
1022 configuration.combined_audio_video_bwe;
1023
1024 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001025 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001026
1027 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001028 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001029
1030 // Whether the certificate generator/certificate is null or not determines
1031 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1032 // the right instructions by clearing the variables if needed.
1033 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001034 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001035 certificate = nullptr;
1036 } else if (certificate) {
1037 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001038 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001039 }
1040
1041 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1042 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001043 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001044 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1045 this, &PeerConnection::OnCertificateReady);
1046
1047 if (options.disable_encryption) {
1048 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1049 }
1050
1051 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1052 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053
Steve Anton4171afb2017-11-20 10:20:22 -08001054 // Add default audio/video transceivers for Plan B SDP.
1055 if (!IsUnifiedPlan()) {
1056 transceivers_.push_back(
1057 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1058 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1059 transceivers_.push_back(
1060 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1061 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1062 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001063 int delay_ms =
1064 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1065 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1066 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067 return true;
1068}
1069
Steve Anton038834f2017-07-14 15:59:59 -07001070RTCError PeerConnection::ValidateConfiguration(
1071 const RTCConfiguration& config) const {
1072 if (config.ice_regather_interval_range &&
1073 config.continual_gathering_policy == GATHER_ONCE) {
1074 return RTCError(RTCErrorType::INVALID_PARAMETER,
1075 "ice_regather_interval_range specified but continual "
1076 "gathering policy is GATHER_ONCE");
1077 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001078 auto result =
1079 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1080 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001081}
1082
Yves Gerey665174f2018-06-19 15:03:05 +02001083rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001084 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1085 "Plan SdpSemantics. Please use GetSenders "
1086 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001087 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088}
1089
Yves Gerey665174f2018-06-19 15:03:05 +02001090rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001091 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1092 "Plan SdpSemantics. Please use GetReceivers "
1093 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001094 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095}
1096
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001097bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001098 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1099 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001100 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 if (IsClosed()) {
1102 return false;
1103 }
deadbeefab9b2d12015-10-14 11:33:11 -07001104 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 return false;
1106 }
deadbeefab9b2d12015-10-14 11:33:11 -07001107
1108 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001109 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1110 observer->SignalAudioTrackAdded.connect(this,
1111 &PeerConnection::OnAudioTrackAdded);
1112 observer->SignalAudioTrackRemoved.connect(
1113 this, &PeerConnection::OnAudioTrackRemoved);
1114 observer->SignalVideoTrackAdded.connect(this,
1115 &PeerConnection::OnVideoTrackAdded);
1116 observer->SignalVideoTrackRemoved.connect(
1117 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001118 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001119
deadbeefab9b2d12015-10-14 11:33:11 -07001120 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001121 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001122 }
1123 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001124 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001125 }
1126
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001127 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 observer_->OnRenegotiationNeeded();
1129 return true;
1130}
1131
1132void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001133 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1134 "Plan SdpSemantics. Please use RemoveTrack "
1135 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001136 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001137 if (!IsClosed()) {
1138 for (const auto& track : local_stream->GetAudioTracks()) {
1139 RemoveAudioTrack(track.get(), local_stream);
1140 }
1141 for (const auto& track : local_stream->GetVideoTracks()) {
1142 RemoveVideoTrack(track.get(), local_stream);
1143 }
deadbeefab9b2d12015-10-14 11:33:11 -07001144 }
deadbeefab9b2d12015-10-14 11:33:11 -07001145 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001146 stream_observers_.erase(
1147 std::remove_if(
1148 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001149 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001150 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001151 }),
1152 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001153
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 if (IsClosed()) {
1155 return;
1156 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001157 observer_->OnRenegotiationNeeded();
1158}
1159
deadbeefe1f9d832016-01-14 15:35:42 -08001160rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1161 MediaStreamTrackInterface* track,
1162 std::vector<MediaStreamInterface*> streams) {
1163 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001164 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001165 for (auto* stream : streams) {
1166 if (!stream) {
1167 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1168 return nullptr;
1169 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001170 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001171 }
Seth Hampson845e8782018-03-02 11:34:10 -08001172 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001173 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001174 return nullptr;
1175 }
Steve Antonf9381f02017-12-14 10:23:57 -08001176 return sender_or_error.MoveValue();
1177}
1178
Steve Anton2d6c76a2018-01-05 17:10:52 -08001179RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001180 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001181 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001182 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001183 if (!track) {
1184 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1185 }
1186 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1187 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1189 "Track has invalid kind: " + track->kind());
1190 }
Steve Antonf9381f02017-12-14 10:23:57 -08001191 if (IsClosed()) {
1192 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1193 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
Steve Anton4171afb2017-11-20 10:20:22 -08001195 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001196 LOG_AND_RETURN_ERROR(
1197 RTCErrorType::INVALID_PARAMETER,
1198 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001199 }
Steve Antonf9381f02017-12-14 10:23:57 -08001200 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001201 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1202 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001203 if (sender_or_error.ok()) {
1204 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001205 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001206 }
1207 return sender_or_error;
1208}
deadbeefe1f9d832016-01-14 15:35:42 -08001209
Steve Antonf9381f02017-12-14 10:23:57 -08001210RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1211PeerConnection::AddTrackPlanB(
1212 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001213 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001214 if (stream_ids.size() > 1u) {
1215 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1216 "AddTrack with more than one stream is not "
1217 "supported with Plan B semantics.");
1218 }
1219 std::vector<std::string> adjusted_stream_ids = stream_ids;
1220 if (adjusted_stream_ids.empty()) {
1221 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1222 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001223 cricket::MediaType media_type =
1224 (track->kind() == MediaStreamTrackInterface::kAudioKind
1225 ? cricket::MEDIA_TYPE_AUDIO
1226 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001227 auto new_sender =
1228 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001229 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001230 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001231 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001232 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001233 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001234 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001235 if (sender_info) {
1236 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001237 }
Steve Antonf9381f02017-12-14 10:23:57 -08001238 } else {
1239 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001240 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001241 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001242 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001243 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001244 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001245 if (sender_info) {
1246 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001247 }
deadbeefe1f9d832016-01-14 15:35:42 -08001248 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001249 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001250}
deadbeefe1f9d832016-01-14 15:35:42 -08001251
Steve Antonf9381f02017-12-14 10:23:57 -08001252RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1253PeerConnection::AddTrackUnifiedPlan(
1254 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001255 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001256 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1257 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001258 RTC_LOG(LS_INFO) << "Reusing an existing "
1259 << cricket::MediaTypeToString(transceiver->media_type())
1260 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001261 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001262 transceiver->internal()->set_direction(
1263 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001264 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001265 transceiver->internal()->set_direction(
1266 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001267 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001268 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001269 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001270 } else {
1271 cricket::MediaType media_type =
1272 (track->kind() == MediaStreamTrackInterface::kAudioKind
1273 ? cricket::MEDIA_TYPE_AUDIO
1274 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001275 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1276 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001277 std::string sender_id = track->id();
1278 // Avoid creating a sender with an existing ID by generating a random ID.
1279 // This can happen if this is the second time AddTrack has created a sender
1280 // for this track.
1281 if (FindSenderById(sender_id)) {
1282 sender_id = rtc::CreateRandomUuid();
1283 }
1284 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001285 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1286 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001287 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001288 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001289 }
Steve Antonf9381f02017-12-14 10:23:57 -08001290 return transceiver->sender();
1291}
1292
1293rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1294PeerConnection::FindFirstTransceiverForAddedTrack(
1295 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1296 RTC_DCHECK(track);
1297 for (auto transceiver : transceivers_) {
1298 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001299 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001300 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001301 !transceiver->internal()->has_ever_been_used_to_send() &&
1302 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001303 return transceiver;
1304 }
1305 }
1306 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001307}
1308
1309bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1310 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001311 return RemoveTrackInternal(sender).ok();
1312}
1313
1314RTCError PeerConnection::RemoveTrackInternal(
1315 rtc::scoped_refptr<RtpSenderInterface> sender) {
1316 if (!sender) {
1317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1318 }
deadbeefe1f9d832016-01-14 15:35:42 -08001319 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001320 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1321 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001322 }
Steve Antonf9381f02017-12-14 10:23:57 -08001323 if (IsUnifiedPlan()) {
1324 auto transceiver = FindTransceiverBySender(sender);
1325 if (!transceiver || !sender->track()) {
1326 return RTCError::OK();
1327 }
1328 sender->SetTrack(nullptr);
1329 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001330 transceiver->internal()->set_direction(
1331 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001332 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001333 transceiver->internal()->set_direction(
1334 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001335 }
Steve Anton4171afb2017-11-20 10:20:22 -08001336 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001337 bool removed;
1338 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1339 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1340 } else {
1341 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1342 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1343 }
1344 if (!removed) {
1345 LOG_AND_RETURN_ERROR(
1346 RTCErrorType::INVALID_PARAMETER,
1347 "Couldn't find sender " + sender->id() + " to remove.");
1348 }
Steve Anton4171afb2017-11-20 10:20:22 -08001349 }
deadbeefe1f9d832016-01-14 15:35:42 -08001350 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001351 return RTCError::OK();
1352}
1353
1354rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1355PeerConnection::FindTransceiverBySender(
1356 rtc::scoped_refptr<RtpSenderInterface> sender) {
1357 for (auto transceiver : transceivers_) {
1358 if (transceiver->sender() == sender) {
1359 return transceiver;
1360 }
1361 }
1362 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001363}
1364
Steve Anton9158ef62017-11-27 13:01:52 -08001365RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1366PeerConnection::AddTransceiver(
1367 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1368 return AddTransceiver(track, RtpTransceiverInit());
1369}
1370
1371RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1372PeerConnection::AddTransceiver(
1373 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1374 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001375 RTC_CHECK(IsUnifiedPlan())
1376 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001377 if (!track) {
1378 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1379 }
1380 cricket::MediaType media_type;
1381 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1382 media_type = cricket::MEDIA_TYPE_AUDIO;
1383 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1384 media_type = cricket::MEDIA_TYPE_VIDEO;
1385 } else {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1387 "Track kind is not audio or video");
1388 }
1389 return AddTransceiver(media_type, track, init);
1390}
1391
1392RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1393PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1394 return AddTransceiver(media_type, RtpTransceiverInit());
1395}
1396
1397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(cricket::MediaType media_type,
1399 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001400 RTC_CHECK(IsUnifiedPlan())
1401 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001402 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1403 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1404 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1405 "media type is not audio or video");
1406 }
1407 return AddTransceiver(media_type, nullptr, init);
1408}
1409
1410RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1411PeerConnection::AddTransceiver(
1412 cricket::MediaType media_type,
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001414 const RtpTransceiverInit& init,
1415 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001416 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1417 media_type == cricket::MEDIA_TYPE_VIDEO));
1418 if (track) {
1419 RTC_DCHECK_EQ(media_type,
1420 (track->kind() == MediaStreamTrackInterface::kAudioKind
1421 ? cricket::MEDIA_TYPE_AUDIO
1422 : cricket::MEDIA_TYPE_VIDEO));
1423 }
1424
1425 // TODO(bugs.webrtc.org/7600): Verify init.
1426
Steve Anton3d954a62018-04-02 11:27:23 -07001427 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1428 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001429 // Set the sender ID equal to the track ID if the track is specified unless
1430 // that sender ID is already in use.
1431 std::string sender_id =
1432 (track && !FindSenderById(track->id()) ? track->id()
1433 : rtc::CreateRandomUuid());
1434 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001435 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1436 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1437 transceiver->internal()->set_direction(init.direction);
1438
Steve Anton22da89f2018-01-25 13:58:07 -08001439 if (fire_callback) {
1440 observer_->OnRenegotiationNeeded();
1441 }
Steve Antonf9381f02017-12-14 10:23:57 -08001442
1443 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1444}
1445
Steve Anton02ee47c2018-01-10 16:26:06 -08001446rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1447PeerConnection::CreateSender(
1448 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001449 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001450 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001451 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001452 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001453 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1454 RTC_DCHECK(!track ||
1455 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1456 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1457 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001458 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001459 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001460 } else {
1461 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1462 RTC_DCHECK(!track ||
1463 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1464 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001465 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001466 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001467 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001468 bool set_track_succeeded = sender->SetTrack(track);
1469 RTC_DCHECK(set_track_succeeded);
1470 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001471 return sender;
1472}
1473
1474rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1475PeerConnection::CreateReceiver(cricket::MediaType media_type,
1476 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001477 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1478 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001479 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001480 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001481 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001482 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001483 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001484 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001485 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001486 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1487 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001488 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001489 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001490 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001491 return receiver;
1492}
1493
1494rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1495PeerConnection::CreateAndAddTransceiver(
1496 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1497 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1498 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001499 // Ensure that the new sender does not have an ID that is already in use by
1500 // another sender.
1501 // Allow receiver IDs to conflict since those come from remote SDP (which
1502 // could be invalid, but should not cause a crash).
1503 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1505 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001506 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001507 transceiver->internal()->SignalNegotiationNeeded.connect(
1508 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001509 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001510}
1511
Steve Anton52d86772018-02-20 15:48:12 -08001512void PeerConnection::OnNegotiationNeeded() {
1513 RTC_DCHECK_RUN_ON(signaling_thread());
1514 RTC_DCHECK(!IsClosed());
1515 observer_->OnRenegotiationNeeded();
1516}
1517
deadbeeffac06552015-11-25 11:26:01 -08001518rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001519 const std::string& kind,
1520 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001521 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1522 "Plan SdpSemantics. Please use AddTransceiver "
1523 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001524 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001525 if (IsClosed()) {
1526 return nullptr;
1527 }
Steve Anton4171afb2017-11-20 10:20:22 -08001528
Seth Hampson5b4f0752018-04-02 16:31:36 -07001529 // Internally we need to have one stream with Plan B semantics, so we
1530 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001531 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001532 if (stream_id.empty()) {
1533 stream_ids.push_back(rtc::CreateRandomUuid());
1534 RTC_LOG(LS_INFO)
1535 << "No stream_id specified for sender. Generated stream ID: "
1536 << stream_ids[0];
1537 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001538 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 }
1540
Steve Anton4171afb2017-11-20 10:20:22 -08001541 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001542 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001543 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001544 auto* audio_sender = new AudioRtpSender(
1545 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001546 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001547 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001548 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001549 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001550 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001551 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001552 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001553 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001554 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001555 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001556 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001557 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001558 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001559 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001560 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001561 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001562
deadbeefe1f9d832016-01-14 15:35:42 -08001563 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001564}
1565
deadbeef70ab1a12015-09-28 16:53:55 -07001566std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1567 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001568 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001569 for (auto sender : GetSendersInternal()) {
1570 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001571 }
1572 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001573}
1574
Steve Anton4171afb2017-11-20 10:20:22 -08001575std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1576PeerConnection::GetSendersInternal() const {
1577 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1578 all_senders;
1579 for (auto transceiver : transceivers_) {
1580 auto senders = transceiver->internal()->senders();
1581 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1582 }
1583 return all_senders;
1584}
1585
deadbeef70ab1a12015-09-28 16:53:55 -07001586std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1587PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001588 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001589 for (const auto& receiver : GetReceiversInternal()) {
1590 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001591 }
1592 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001593}
1594
Steve Anton4171afb2017-11-20 10:20:22 -08001595std::vector<
1596 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1597PeerConnection::GetReceiversInternal() const {
1598 std::vector<
1599 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1600 all_receivers;
1601 for (auto transceiver : transceivers_) {
1602 auto receivers = transceiver->internal()->receivers();
1603 all_receivers.insert(all_receivers.end(), receivers.begin(),
1604 receivers.end());
1605 }
1606 return all_receivers;
1607}
1608
Steve Anton9158ef62017-11-27 13:01:52 -08001609std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1610PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001611 RTC_CHECK(IsUnifiedPlan())
1612 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001613 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1614 for (auto transceiver : transceivers_) {
1615 all_transceivers.push_back(transceiver);
1616 }
1617 return all_transceivers;
1618}
1619
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001621 MediaStreamTrackInterface* track,
1622 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001623 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001624 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001625 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001626 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001627 return false;
1628 }
1629
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001630 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001631 // The StatsCollector is used to tell if a track is valid because it may
1632 // remember tracks that the PeerConnection previously removed.
1633 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001634 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1635 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001636 return false;
1637 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001638 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001639 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 return true;
1641}
1642
hbos74e1a4f2016-09-15 23:33:01 -07001643void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001644 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001645 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001646 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001647 stats_collector_->GetStatsReport(callback);
1648}
1649
Henrik Boström1df1bf82018-03-20 13:24:20 +01001650void PeerConnection::GetStats(
1651 rtc::scoped_refptr<RtpSenderInterface> selector,
1652 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1653 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1654 RTC_DCHECK(callback);
1655 RTC_DCHECK(stats_collector_);
1656 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1657 if (selector) {
1658 for (const auto& proxy_transceiver : transceivers_) {
1659 for (const auto& proxy_sender :
1660 proxy_transceiver->internal()->senders()) {
1661 if (proxy_sender == selector) {
1662 internal_sender = proxy_sender->internal();
1663 break;
1664 }
1665 }
1666 if (internal_sender)
1667 break;
1668 }
1669 }
1670 // If there is no |internal_sender| then |selector| is either null or does not
1671 // belong to the PeerConnection (in Plan B, senders can be removed from the
1672 // PeerConnection). This means that "all the stats objects representing the
1673 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1674 // produces an empty stats report.
1675 stats_collector_->GetStatsReport(internal_sender, callback);
1676}
1677
1678void PeerConnection::GetStats(
1679 rtc::scoped_refptr<RtpReceiverInterface> selector,
1680 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1681 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1682 RTC_DCHECK(callback);
1683 RTC_DCHECK(stats_collector_);
1684 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1685 if (selector) {
1686 for (const auto& proxy_transceiver : transceivers_) {
1687 for (const auto& proxy_receiver :
1688 proxy_transceiver->internal()->receivers()) {
1689 if (proxy_receiver == selector) {
1690 internal_receiver = proxy_receiver->internal();
1691 break;
1692 }
1693 }
1694 if (internal_receiver)
1695 break;
1696 }
1697 }
1698 // If there is no |internal_receiver| then |selector| is either null or does
1699 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1700 // the PeerConnection). This means that "all the stats objects representing
1701 // the selector" is an empty set. Invoking GetStatsReport() with a null
1702 // selector produces an empty stats report.
1703 stats_collector_->GetStatsReport(internal_receiver, callback);
1704}
1705
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1707 return signaling_state_;
1708}
1709
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001710PeerConnectionInterface::IceConnectionState
1711PeerConnection::ice_connection_state() {
1712 return ice_connection_state_;
1713}
1714
1715PeerConnectionInterface::IceGatheringState
1716PeerConnection::ice_gathering_state() {
1717 return ice_gathering_state_;
1718}
1719
Yves Gerey665174f2018-06-19 15:03:05 +02001720rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 const std::string& label,
1722 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001723 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001724
deadbeefab9b2d12015-10-14 11:33:11 -07001725 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001726
kwibergd1fe2812016-04-27 06:47:29 -07001727 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001728 if (config) {
1729 internal_config.reset(new InternalDataChannelInit(*config));
1730 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001731 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001732 InternalCreateDataChannel(label, internal_config.get()));
1733 if (!channel.get()) {
1734 return nullptr;
1735 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001736
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001737 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1738 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001739 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001740 observer_->OnRenegotiationNeeded();
1741 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001742 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743 return DataChannelProxy::Create(signaling_thread(), channel.get());
1744}
1745
1746void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1747 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001748 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001749
zhihuang1c378ed2017-08-17 14:10:50 -07001750 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1751 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1752 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1753 // compares the mandatory fields parsed with the mandatory fields added in the
1754 // |constraints| and some downstream applications might create offers with
1755 // mandatory fields which would not be parsed in the helper method. For
1756 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1757 // |constraints| as a mandatory field but it is not parsed.
1758 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001759
zhihuang1c378ed2017-08-17 14:10:50 -07001760 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001761}
1762
1763void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1764 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001765 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001766
nisse7ce109a2017-01-31 00:57:56 -08001767 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001769 return;
1770 }
deadbeefab9b2d12015-10-14 11:33:11 -07001771
Steve Anton8d3444d2017-10-20 15:30:51 -07001772 if (IsClosed()) {
1773 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001774 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001775 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001776 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001777 return;
1778 }
1779
zhihuang1c378ed2017-08-17 14:10:50 -07001780 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001781 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001783 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001784 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001785 return;
1786 }
1787
Steve Anton22da89f2018-01-25 13:58:07 -08001788 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1789 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1790 if (IsUnifiedPlan()) {
1791 RTCError error = HandleLegacyOfferOptions(options);
1792 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001793 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001794 return;
1795 }
1796 }
1797
zhihuang1c378ed2017-08-17 14:10:50 -07001798 cricket::MediaSessionOptions session_options;
1799 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001800 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801}
1802
Steve Anton22da89f2018-01-25 13:58:07 -08001803RTCError PeerConnection::HandleLegacyOfferOptions(
1804 const RTCOfferAnswerOptions& options) {
1805 RTC_DCHECK(IsUnifiedPlan());
1806
1807 if (options.offer_to_receive_audio == 0) {
1808 RemoveRecvDirectionFromReceivingTransceiversOfType(
1809 cricket::MEDIA_TYPE_AUDIO);
1810 } else if (options.offer_to_receive_audio == 1) {
1811 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1812 } else if (options.offer_to_receive_audio > 1) {
1813 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1814 "offer_to_receive_audio > 1 is not supported.");
1815 }
1816
1817 if (options.offer_to_receive_video == 0) {
1818 RemoveRecvDirectionFromReceivingTransceiversOfType(
1819 cricket::MEDIA_TYPE_VIDEO);
1820 } else if (options.offer_to_receive_video == 1) {
1821 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1822 } else if (options.offer_to_receive_video > 1) {
1823 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1824 "offer_to_receive_video > 1 is not supported.");
1825 }
1826
1827 return RTCError::OK();
1828}
1829
1830void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1831 cricket::MediaType media_type) {
1832 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001833 RtpTransceiverDirection new_direction =
1834 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1835 if (new_direction != transceiver->direction()) {
1836 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1837 << " transceiver (MID="
1838 << transceiver->mid().value_or("<not set>") << ") from "
1839 << RtpTransceiverDirectionToString(
1840 transceiver->direction())
1841 << " to "
1842 << RtpTransceiverDirectionToString(new_direction)
1843 << " since CreateOffer specified offer_to_receive=0";
1844 transceiver->internal()->set_direction(new_direction);
1845 }
Steve Anton22da89f2018-01-25 13:58:07 -08001846 }
1847}
1848
1849void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1850 cricket::MediaType media_type) {
1851 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001852 RTC_LOG(LS_INFO)
1853 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1854 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001855 RtpTransceiverInit init;
1856 init.direction = RtpTransceiverDirection::kRecvOnly;
1857 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1858 }
1859}
1860
1861std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1862PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1863 std::vector<
1864 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1865 receiving_transceivers;
1866 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001867 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001868 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1869 receiving_transceivers.push_back(transceiver);
1870 }
1871 }
1872 return receiving_transceivers;
1873}
1874
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875void PeerConnection::CreateAnswer(
1876 CreateSessionDescriptionObserver* observer,
1877 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001878 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001879
nisse7ce109a2017-01-31 00:57:56 -08001880 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882 return;
1883 }
deadbeefab9b2d12015-10-14 11:33:11 -07001884
zhihuang1c378ed2017-08-17 14:10:50 -07001885 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1886 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1887 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001888 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001890 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001891 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001892 return;
1893 }
1894
Steve Anton8d3444d2017-10-20 15:30:51 -07001895 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001896}
1897
1898void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1899 const RTCOfferAnswerOptions& options) {
1900 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001901 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001902 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001903 return;
1904 }
1905
Steve Antondffead82018-02-06 10:31:29 -08001906 if (!(signaling_state_ == kHaveRemoteOffer ||
1907 signaling_state_ == kHaveLocalPrAnswer)) {
1908 std::string error =
1909 "PeerConnection cannot create an answer in a state other than "
1910 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001911 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001912 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001913 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001914 return;
1915 }
1916
Steve Antondffead82018-02-06 10:31:29 -08001917 // The remote description should be set if we're in the right state.
1918 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001919
Steve Anton22da89f2018-01-25 13:58:07 -08001920 if (IsUnifiedPlan()) {
1921 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1922 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1923 "supported with Unified Plan semantics. Use the "
1924 "RtpTransceiver API instead.";
1925 }
1926 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1927 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1928 "supported with Unified Plan semantics. Use the "
1929 "RtpTransceiver API instead.";
1930 }
1931 }
1932
htaa2a49d92016-03-04 02:51:39 -08001933 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001934 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001935
Steve Antond25da372017-11-06 14:50:29 -08001936 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937}
1938
1939void PeerConnection::SetLocalDescription(
1940 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001941 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001942 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001943
Steve Anton80dd7b52018-02-16 17:08:42 -08001944 // The SetLocalDescription contract is that we take ownership of the session
1945 // description regardless of the outcome, so wrap it in a unique_ptr right
1946 // away. Ideally, SetLocalDescription's signature will be changed to take the
1947 // description as a unique_ptr argument to formalize this agreement.
1948 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1949
nisse7ce109a2017-01-31 00:57:56 -08001950 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001951 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 return;
1953 }
Steve Anton8a006912017-12-04 15:25:56 -08001954
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001956 PostSetSessionDescriptionFailure(
1957 observer,
1958 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001959 return;
1960 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001961
Steve Anton80dd7b52018-02-16 17:08:42 -08001962 // If a session error has occurred the PeerConnection is in a possibly
1963 // inconsistent state so fail right away.
1964 if (session_error() != SessionError::kNone) {
1965 std::string error_message = GetSessionErrorMsg();
1966 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001967 PostSetSessionDescriptionFailure(
1968 observer,
1969 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 return;
1971 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001972
Steve Anton80dd7b52018-02-16 17:08:42 -08001973 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1974 if (!error.ok()) {
1975 std::string error_message = GetSetDescriptionErrorMessage(
1976 cricket::CS_LOCAL, desc->GetType(), error);
1977 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001978 PostSetSessionDescriptionFailure(
1979 observer,
1980 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001981 return;
1982 }
1983
1984 // Grab the description type before moving ownership to ApplyLocalDescription,
1985 // which may destroy it before returning.
1986 const SdpType type = desc->GetType();
1987
1988 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001989 // |desc| may be destroyed at this point.
1990
1991 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001992 // If ApplyLocalDescription fails, the PeerConnection could be in an
1993 // inconsistent state, so act conservatively here and set the session error
1994 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1995 SetSessionError(SessionError::kContent, error.message());
1996 std::string error_message =
1997 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1998 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001999 PostSetSessionDescriptionFailure(
2000 observer,
2001 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002002 return;
2003 }
Steve Anton8a006912017-12-04 15:25:56 -08002004 RTC_DCHECK(local_description());
2005
2006 PostSetSessionDescriptionSuccess(observer);
2007
Steve Anton8a006912017-12-04 15:25:56 -08002008 // MaybeStartGathering needs to be called after posting
2009 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2010 // before signaling that SetLocalDescription completed.
2011 transport_controller_->MaybeStartGathering();
2012
Steve Antona3a92c22017-12-07 10:27:41 -08002013 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002014 // TODO(deadbeef): We already had to hop to the network thread for
2015 // MaybeStartGathering...
2016 network_thread()->Invoke<void>(
2017 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2018 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002019 // Make UMA notes about what was agreed to.
2020 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002021 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002022 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002023}
2024
2025RTCError PeerConnection::ApplyLocalDescription(
2026 std::unique_ptr<SessionDescriptionInterface> desc) {
2027 RTC_DCHECK_RUN_ON(signaling_thread());
2028 RTC_DCHECK(desc);
2029
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 // Update stats here so that we have the most recent stats for tracks and
2031 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002032 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002033
Steve Antondcc3c022017-12-22 16:02:54 -08002034 // Take a reference to the old local description since it's used below to
2035 // compare against the new local description. When setting the new local
2036 // description, grab ownership of the replaced session description in case it
2037 // is the same as |old_local_description|, to keep it alive for the duration
2038 // of the method.
2039 const SessionDescriptionInterface* old_local_description =
2040 local_description();
2041 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002042 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002043 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002044 replaced_local_description = pending_local_description_
2045 ? std::move(pending_local_description_)
2046 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002047 current_local_description_ = std::move(desc);
2048 pending_local_description_ = nullptr;
2049 current_remote_description_ = std::move(pending_remote_description_);
2050 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002051 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002052 pending_local_description_ = std::move(desc);
2053 }
2054 // The session description to apply now must be accessed by
2055 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002056 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002057
Zhi Huange830e682018-03-30 10:48:35 -07002058 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2059 if (!error.ok()) {
2060 return error;
2061 }
2062
Steve Antondcc3c022017-12-22 16:02:54 -08002063 if (IsUnifiedPlan()) {
2064 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002065 cricket::CS_LOCAL, *local_description(), old_local_description,
2066 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002067 if (!error.ok()) {
2068 return error;
2069 }
Steve Antondcc3c022017-12-22 16:02:54 -08002070 for (auto transceiver : transceivers_) {
2071 const ContentInfo* content =
2072 FindMediaSectionForTransceiver(transceiver, local_description());
2073 if (!content) {
2074 continue;
2075 }
2076 const MediaContentDescription* media_desc = content->media_description();
2077 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2078 transceiver->internal()->set_current_direction(media_desc->direction());
2079 }
2080 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002081 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2082 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002083 transceiver->Stop();
2084 }
2085 }
2086 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002087 // Media channels will be created only when offer is set. These may use new
2088 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002089 if (type == SdpType::kOffer) {
2090 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2091 // description is applied. Restore back to old description.
2092 RTCError error = CreateChannels(*local_description()->description());
2093 if (!error.ok()) {
2094 return error;
2095 }
2096 }
Steve Antondcc3c022017-12-22 16:02:54 -08002097 // Remove unused channels if MediaContentDescription is rejected.
2098 RemoveUnusedChannels(local_description()->description());
2099 }
Steve Anton8a006912017-12-04 15:25:56 -08002100
Zhi Huange830e682018-03-30 10:48:35 -07002101 error = UpdateSessionState(type, cricket::CS_LOCAL,
2102 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002103 if (!error.ok()) {
2104 return error;
2105 }
Steve Antondcc3c022017-12-22 16:02:54 -08002106
Steve Anton8a006912017-12-04 15:25:56 -08002107 if (remote_description()) {
2108 // Now that we have a local description, we can push down remote candidates.
2109 UseCandidatesInSessionDescription(remote_description());
2110 }
2111
2112 pending_ice_restarts_.clear();
2113 if (session_error() != SessionError::kNone) {
2114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2115 }
2116
deadbeefab9b2d12015-10-14 11:33:11 -07002117 // If setting the description decided our SSL role, allocate any necessary
2118 // SCTP sids.
2119 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002120 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002121 AllocateSctpSids(role);
2122 }
2123
Steve Antond3679212018-01-17 17:41:02 -08002124 if (IsUnifiedPlan()) {
2125 for (auto transceiver : transceivers_) {
2126 const ContentInfo* content =
2127 FindMediaSectionForTransceiver(transceiver, local_description());
2128 if (!content) {
2129 continue;
2130 }
Steve Anton74255ff2018-01-24 18:32:57 -08002131 const auto& streams = content->media_description()->streams();
2132 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002133 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002134 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002135 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002136 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002137 } else {
2138 // 0 is a special value meaning "this sender has no associated send
2139 // stream". Need to call this so the sender won't attempt to configure
2140 // a no longer existing stream and run into DCHECKs in the lower
2141 // layers.
2142 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002143 }
2144 }
2145 } else {
2146 // Plan B semantics.
2147
Steve Antondcc3c022017-12-22 16:02:54 -08002148 // Update state and SSRC of local MediaStreams and DataChannels based on the
2149 // local session description.
2150 const cricket::ContentInfo* audio_content =
2151 GetFirstAudioContent(local_description()->description());
2152 if (audio_content) {
2153 if (audio_content->rejected) {
2154 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2155 } else {
2156 const cricket::AudioContentDescription* audio_desc =
2157 audio_content->media_description()->as_audio();
2158 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2159 }
deadbeeffaac4972015-11-12 15:33:07 -08002160 }
deadbeefab9b2d12015-10-14 11:33:11 -07002161
Steve Antondcc3c022017-12-22 16:02:54 -08002162 const cricket::ContentInfo* video_content =
2163 GetFirstVideoContent(local_description()->description());
2164 if (video_content) {
2165 if (video_content->rejected) {
2166 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2167 } else {
2168 const cricket::VideoContentDescription* video_desc =
2169 video_content->media_description()->as_video();
2170 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2171 }
deadbeeffaac4972015-11-12 15:33:07 -08002172 }
deadbeefab9b2d12015-10-14 11:33:11 -07002173 }
2174
2175 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002176 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002177 if (data_content) {
2178 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002179 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002180 if (rtc::starts_with(data_desc->protocol().data(),
2181 cricket::kMediaProtocolRtpPrefix)) {
2182 UpdateLocalRtpDataChannels(data_desc->streams());
2183 }
2184 }
2185
Steve Anton8a006912017-12-04 15:25:56 -08002186 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187}
2188
2189void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002190 SetSessionDescriptionObserver* observer,
2191 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002192 SetRemoteDescription(
2193 std::unique_ptr<SessionDescriptionInterface>(desc),
2194 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2195 new SetRemoteDescriptionObserverAdapter(this, observer)));
2196}
2197
2198void PeerConnection::SetRemoteDescription(
2199 std::unique_ptr<SessionDescriptionInterface> desc,
2200 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002201 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002202
nisse7ce109a2017-01-31 00:57:56 -08002203 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002204 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 return;
2206 }
Steve Anton8a006912017-12-04 15:25:56 -08002207
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002209 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002210 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 return;
2212 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002213
Steve Anton80dd7b52018-02-16 17:08:42 -08002214 // If a session error has occurred the PeerConnection is in a possibly
2215 // inconsistent state so fail right away.
2216 if (session_error() != SessionError::kNone) {
2217 std::string error_message = GetSessionErrorMsg();
2218 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2219 observer->OnSetRemoteDescriptionComplete(
2220 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2221 return;
2222 }
Steve Anton71439a62018-02-15 11:53:06 -08002223
Steve Antonba42e992018-04-09 14:10:01 -07002224 if (desc->GetType() == SdpType::kOffer) {
2225 // Report to UMA the format of the received offer.
2226 ReportSdpFormatReceived(*desc);
2227 }
2228
Steve Anton80dd7b52018-02-16 17:08:42 -08002229 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002230 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002231 std::string error_message = GetSetDescriptionErrorMessage(
2232 cricket::CS_REMOTE, desc->GetType(), error);
2233 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002234 observer->OnSetRemoteDescriptionComplete(
2235 RTCError(error.type(), std::move(error_message)));
2236 return;
2237 }
Steve Anton71439a62018-02-15 11:53:06 -08002238
Steve Anton80dd7b52018-02-16 17:08:42 -08002239 // Grab the description type before moving ownership to
2240 // ApplyRemoteDescription, which may destroy it before returning.
2241 const SdpType type = desc->GetType();
2242
2243 error = ApplyRemoteDescription(std::move(desc));
2244 // |desc| may be destroyed at this point.
2245
2246 if (!error.ok()) {
2247 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2248 // inconsistent state, so act conservatively here and set the session error
2249 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2250 SetSessionError(SessionError::kContent, error.message());
2251 std::string error_message =
2252 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2253 RTC_LOG(LS_ERROR) << error_message;
2254 observer->OnSetRemoteDescriptionComplete(
2255 RTCError(error.type(), std::move(error_message)));
2256 return;
2257 }
2258 RTC_DCHECK(remote_description());
2259
2260 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002261 // TODO(deadbeef): We already had to hop to the network thread for
2262 // MaybeStartGathering...
2263 network_thread()->Invoke<void>(
2264 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2265 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002266 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002267 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002268 }
2269
2270 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002271 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002272}
2273
2274RTCError PeerConnection::ApplyRemoteDescription(
2275 std::unique_ptr<SessionDescriptionInterface> desc) {
2276 RTC_DCHECK_RUN_ON(signaling_thread());
2277 RTC_DCHECK(desc);
2278
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279 // Update stats here so that we have the most recent stats for tracks and
2280 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002281 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002282
Steve Antondcc3c022017-12-22 16:02:54 -08002283 // Take a reference to the old remote description since it's used below to
2284 // compare against the new remote description. When setting the new remote
2285 // description, grab ownership of the replaced session description in case it
2286 // is the same as |old_remote_description|, to keep it alive for the duration
2287 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002288 const SessionDescriptionInterface* old_remote_description =
2289 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002290 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002291 SdpType type = desc->GetType();
2292 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002293 replaced_remote_description = pending_remote_description_
2294 ? std::move(pending_remote_description_)
2295 : std::move(current_remote_description_);
2296 current_remote_description_ = std::move(desc);
2297 pending_remote_description_ = nullptr;
2298 current_local_description_ = std::move(pending_local_description_);
2299 } else {
2300 replaced_remote_description = std::move(pending_remote_description_);
2301 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302 }
Steve Anton8a006912017-12-04 15:25:56 -08002303 // The session description to apply now must be accessed by
2304 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002305 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306
Zhi Huange830e682018-03-30 10:48:35 -07002307 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2308 if (!error.ok()) {
2309 return error;
2310 }
Steve Anton8a006912017-12-04 15:25:56 -08002311 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002312 if (IsUnifiedPlan()) {
2313 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002314 cricket::CS_REMOTE, *remote_description(), local_description(),
2315 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002316 if (!error.ok()) {
2317 return error;
2318 }
Steve Antondcc3c022017-12-22 16:02:54 -08002319 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002320 // Media channels will be created only when offer is set. These may use new
2321 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002322 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002323 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // description is applied. Restore back to old description.
2325 RTCError error = CreateChannels(*remote_description()->description());
2326 if (!error.ok()) {
2327 return error;
2328 }
2329 }
Steve Antondcc3c022017-12-22 16:02:54 -08002330 // Remove unused channels if MediaContentDescription is rejected.
2331 RemoveUnusedChannels(remote_description()->description());
2332 }
Steve Anton8a006912017-12-04 15:25:56 -08002333
Zhi Huange830e682018-03-30 10:48:35 -07002334 // NOTE: Candidates allocation will be initiated only when
2335 // SetLocalDescription is called.
2336 error = UpdateSessionState(type, cricket::CS_REMOTE,
2337 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002338 if (!error.ok()) {
2339 return error;
2340 }
2341
2342 if (local_description() &&
2343 !UseCandidatesInSessionDescription(remote_description())) {
2344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2345 }
2346
2347 if (old_remote_description) {
2348 for (const cricket::ContentInfo& content :
2349 old_remote_description->description()->contents()) {
2350 // Check if this new SessionDescription contains new ICE ufrag and
2351 // password that indicates the remote peer requests an ICE restart.
2352 // TODO(deadbeef): When we start storing both the current and pending
2353 // remote description, this should reset pending_ice_restarts and compare
2354 // against the current description.
2355 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2356 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002357 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002358 pending_ice_restarts_.insert(content.name);
2359 }
2360 } else {
2361 // We retain all received candidates only if ICE is not restarted.
2362 // When ICE is restarted, all previous candidates belong to an old
2363 // generation and should not be kept.
2364 // TODO(deadbeef): This goes against the W3C spec which says the remote
2365 // description should only contain candidates from the last set remote
2366 // description plus any candidates added since then. We should remove
2367 // this once we're sure it won't break anything.
2368 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2369 old_remote_description, content.name, mutable_remote_description());
2370 }
2371 }
2372 }
2373
2374 if (session_error() != SessionError::kNone) {
2375 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2376 }
2377
2378 // Set the the ICE connection state to connecting since the connection may
2379 // become writable with peer reflexive candidates before any remote candidate
2380 // is signaled.
2381 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2382 // is to have a new signal the indicates a change in checking state from the
2383 // transport and expose a new checking() member from transport that can be
2384 // read to determine the current checking state. The existing SignalConnecting
2385 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002386 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002387 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002388 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2389 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2390 }
2391
deadbeefab9b2d12015-10-14 11:33:11 -07002392 // If setting the description decided our SSL role, allocate any necessary
2393 // SCTP sids.
2394 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002395 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002396 AllocateSctpSids(role);
2397 }
2398
Steve Antondcc3c022017-12-22 16:02:54 -08002399 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002400 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002401 now_receiving_transceivers;
2402 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2403 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002404 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002405 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002406 for (auto transceiver : transceivers_) {
2407 const ContentInfo* content =
2408 FindMediaSectionForTransceiver(transceiver, remote_description());
2409 if (!content) {
2410 continue;
2411 }
2412 const MediaContentDescription* media_desc = content->media_description();
2413 RtpTransceiverDirection local_direction =
2414 RtpTransceiverDirectionReversed(media_desc->direction());
2415 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2416 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2417 // transceiver's current direction is neither sendrecv nor recvonly,
2418 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002419 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002420 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002421 // The remote description has signaled the stream IDs.
2422 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002423 }
Steve Antondcc3c022017-12-22 16:02:54 -08002424 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2425 (!transceiver->current_direction() ||
2426 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002427 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002428 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002429 << content->name << " (added to "
2430 << GetStreamIdsString(stream_ids) << ").";
2431
2432 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2433 for (const std::string& stream_id : stream_ids) {
2434 rtc::scoped_refptr<MediaStreamInterface> stream =
2435 remote_streams_->find(stream_id);
2436 if (!stream) {
2437 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2438 MediaStream::Create(stream_id));
2439 remote_streams_->AddStream(stream);
2440 added_streams.push_back(stream);
2441 }
2442 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002443 }
Steve Anton3172c032018-05-03 15:30:18 -07002444 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002445 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002446 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
2448 // If direction is sendonly or inactive, and transceiver's current
2449 // direction is neither sendonly nor inactive, process the removal of a
2450 // remote track for the media description.
2451 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002452 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002453 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002454 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2455 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002456 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2457 transceiver->internal()->receiver_internal()->streams();
2458 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002459 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002460 no_longer_receiving_transceivers.push_back(transceiver);
2461 // Remove any streams that no longer have tracks.
2462 for (auto stream : media_streams) {
2463 if (stream->GetAudioTracks().empty() &&
2464 stream->GetVideoTracks().empty()) {
2465 remote_streams_->RemoveStream(stream);
2466 removed_streams.push_back(stream);
2467 }
2468 }
Steve Antondcc3c022017-12-22 16:02:54 -08002469 }
2470 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2471 transceiver->internal()->set_current_direction(local_direction);
2472 }
2473 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002474 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2475 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002476 transceiver->Stop();
2477 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002478 if (!content->rejected &&
2479 RtpTransceiverDirectionHasRecv(local_direction)) {
2480 // Set ssrc to 0 in the case of an unsignalled ssrc.
2481 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002482 if (!media_desc->streams().empty() &&
2483 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002484 ssrc = media_desc->streams()[0].first_ssrc();
2485 }
2486 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002487 }
Steve Antondcc3c022017-12-22 16:02:54 -08002488 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002489 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002490 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002491 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002492 observer_->OnTrack(transceiver);
2493 observer_->OnAddTrack(transceiver->receiver(),
2494 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002495 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002496 for (auto stream : added_streams) {
2497 observer_->OnAddStream(stream);
2498 }
Steve Anton3172c032018-05-03 15:30:18 -07002499 for (auto transceiver : no_longer_receiving_transceivers) {
2500 observer_->OnRemoveTrack(transceiver->receiver());
2501 }
2502 for (auto stream : removed_streams) {
2503 observer_->OnRemoveStream(stream);
2504 }
Steve Antondcc3c022017-12-22 16:02:54 -08002505 }
2506
Henrik Boströmfdb92012017-11-09 19:55:44 +01002507 const cricket::ContentInfo* audio_content =
2508 GetFirstAudioContent(remote_description()->description());
2509 const cricket::ContentInfo* video_content =
2510 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002511 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002512 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002513 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002514 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002515 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002516 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002517
2518 // Check if the descriptions include streams, just in case the peer supports
2519 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002520 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002521 (audio_desc && !audio_desc->streams().empty()) ||
2522 (video_desc && !video_desc->streams().empty())) {
2523 remote_peer_supports_msid_ = true;
2524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
2526 // We wait to signal new streams until we finish processing the description,
2527 // since only at that point will new streams have all their tracks.
2528 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2529
Steve Antondcc3c022017-12-22 16:02:54 -08002530 if (!IsUnifiedPlan()) {
2531 // TODO(steveanton): When removing RTP senders/receivers in response to a
2532 // rejected media section, there is some cleanup logic that expects the
2533 // voice/ video channel to still be set. But in this method the voice/video
2534 // channel would have been destroyed by the SetRemoteDescription caller
2535 // above so the cleanup that relies on them fails to run. The RemoveSenders
2536 // calls should be moved to right before the DestroyChannel calls to fix
2537 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002538
Steve Antondcc3c022017-12-22 16:02:54 -08002539 // Find all audio rtp streams and create corresponding remote AudioTracks
2540 // and MediaStreams.
2541 if (audio_content) {
2542 if (audio_content->rejected) {
2543 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2544 } else {
2545 bool default_audio_track_needed =
2546 !remote_peer_supports_msid_ &&
2547 RtpTransceiverDirectionHasSend(audio_desc->direction());
2548 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2549 default_audio_track_needed, audio_desc->type(),
2550 new_streams);
2551 }
deadbeeffaac4972015-11-12 15:33:07 -08002552 }
deadbeefab9b2d12015-10-14 11:33:11 -07002553
Steve Antondcc3c022017-12-22 16:02:54 -08002554 // Find all video rtp streams and create corresponding remote VideoTracks
2555 // and MediaStreams.
2556 if (video_content) {
2557 if (video_content->rejected) {
2558 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2559 } else {
2560 bool default_video_track_needed =
2561 !remote_peer_supports_msid_ &&
2562 RtpTransceiverDirectionHasSend(video_desc->direction());
2563 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2564 default_video_track_needed, video_desc->type(),
2565 new_streams);
2566 }
deadbeeffaac4972015-11-12 15:33:07 -08002567 }
deadbeefab9b2d12015-10-14 11:33:11 -07002568
Steve Antondcc3c022017-12-22 16:02:54 -08002569 // Update the DataChannels with the information from the remote peer.
2570 if (data_desc) {
2571 if (rtc::starts_with(data_desc->protocol().data(),
2572 cricket::kMediaProtocolRtpPrefix)) {
2573 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2574 }
deadbeefab9b2d12015-10-14 11:33:11 -07002575 }
deadbeefab9b2d12015-10-14 11:33:11 -07002576
Steve Antondcc3c022017-12-22 16:02:54 -08002577 // Iterate new_streams and notify the observer about new MediaStreams.
2578 for (size_t i = 0; i < new_streams->count(); ++i) {
2579 MediaStreamInterface* new_stream = new_streams->at(i);
2580 stats_->AddStream(new_stream);
2581 observer_->OnAddStream(
2582 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2583 }
deadbeefab9b2d12015-10-14 11:33:11 -07002584
Steve Antondcc3c022017-12-22 16:02:54 -08002585 UpdateEndedRemoteMediaStreams();
2586 }
deadbeefab9b2d12015-10-14 11:33:11 -07002587
Steve Anton8a006912017-12-04 15:25:56 -08002588 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002589}
2590
Steve Antondcc3c022017-12-22 16:02:54 -08002591RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2592 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002593 const SessionDescriptionInterface& new_session,
2594 const SessionDescriptionInterface* old_local_description,
2595 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002596 RTC_DCHECK(IsUnifiedPlan());
2597
Steve Anton7464fca2018-01-19 11:10:37 -08002598 const cricket::ContentGroup* bundle_group = nullptr;
2599 if (new_session.GetType() == SdpType::kOffer) {
2600 auto bundle_group_or_error =
2601 GetEarlyBundleGroup(*new_session.description());
2602 if (!bundle_group_or_error.ok()) {
2603 return bundle_group_or_error.MoveError();
2604 }
2605 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002606 }
Steve Antondcc3c022017-12-22 16:02:54 -08002607
Steve Antondcc3c022017-12-22 16:02:54 -08002608 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002609 for (size_t i = 0; i < new_contents.size(); ++i) {
2610 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002611 cricket::MediaType media_type = new_content.media_description()->type();
2612 seen_mids_.insert(new_content.name);
2613 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2614 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002615 const cricket::ContentInfo* old_local_content = nullptr;
2616 if (old_local_description &&
2617 i < old_local_description->description()->contents().size()) {
2618 old_local_content =
2619 &old_local_description->description()->contents()[i];
2620 }
2621 const cricket::ContentInfo* old_remote_content = nullptr;
2622 if (old_remote_description &&
2623 i < old_remote_description->description()->contents().size()) {
2624 old_remote_content =
2625 &old_remote_description->description()->contents()[i];
2626 }
Steve Antondcc3c022017-12-22 16:02:54 -08002627 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002628 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2629 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002630 if (!transceiver_or_error.ok()) {
2631 return transceiver_or_error.MoveError();
2632 }
2633 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002634 RTCError error =
2635 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2636 if (!error.ok()) {
2637 return error;
2638 }
2639 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002640 if (GetDataMid() && new_content.name != *GetDataMid()) {
2641 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002642 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2643 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002644 continue;
2645 }
2646 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2647 if (!error.ok()) {
2648 return error;
2649 }
Steve Antondcc3c022017-12-22 16:02:54 -08002650 } else {
2651 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2652 "Unknown section type.");
2653 }
2654 }
2655
2656 return RTCError::OK();
2657}
2658
2659RTCError PeerConnection::UpdateTransceiverChannel(
2660 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2661 transceiver,
2662 const cricket::ContentInfo& content,
2663 const cricket::ContentGroup* bundle_group) {
2664 RTC_DCHECK(IsUnifiedPlan());
2665 RTC_DCHECK(transceiver);
2666 cricket::BaseChannel* channel = transceiver->internal()->channel();
2667 if (content.rejected) {
2668 if (channel) {
2669 transceiver->internal()->SetChannel(nullptr);
2670 DestroyBaseChannel(channel);
2671 }
2672 } else {
2673 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002674 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002675 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002676 } else {
Steve Anton69470252018-02-09 11:43:08 -08002677 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002678 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002679 }
2680 if (!channel) {
2681 LOG_AND_RETURN_ERROR(
2682 RTCErrorType::INTERNAL_ERROR,
2683 "Failed to create channel for mid=" + content.name);
2684 }
2685 transceiver->internal()->SetChannel(channel);
2686 }
2687 }
2688 return RTCError::OK();
2689}
2690
Steve Antonfa2260d2017-12-28 16:38:23 -08002691RTCError PeerConnection::UpdateDataChannel(
2692 cricket::ContentSource source,
2693 const cricket::ContentInfo& content,
2694 const cricket::ContentGroup* bundle_group) {
2695 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002696 // If data channels are disabled, ignore this media section. CreateAnswer
2697 // will take care of rejecting it.
2698 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002699 }
2700 if (content.rejected) {
2701 DestroyDataChannel();
2702 } else {
2703 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002704 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002705 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2706 "Failed to create data channel.");
2707 }
2708 }
2709 if (source == cricket::CS_REMOTE) {
2710 const MediaContentDescription* data_desc = content.media_description();
2711 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2712 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2713 }
2714 }
2715 }
2716 return RTCError::OK();
2717}
2718
Steve Antondcc3c022017-12-22 16:02:54 -08002719RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2720PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002721 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002722 size_t mline_index,
2723 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002724 const ContentInfo* old_local_content,
2725 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002726 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002727 // If this is an offer then the m= section might be recycled. If the m=
2728 // section is being recycled (defined as: rejected in the current local or
2729 // remote description and not rejected in new description), dissociate the
2730 // currently associated RtpTransceiver by setting its mid property to null,
2731 // and discard the mapping between the transceiver and its m= section index.
2732 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2733 old_remote_content)) {
2734 // We want to dissociate the transceiver that has the rejected mid.
2735 const std::string& old_mid =
2736 (old_local_content && old_local_content->rejected)
2737 ? old_local_content->name
2738 : old_remote_content->name;
2739 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002740 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002741 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2742 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002743 old_transceiver->internal()->set_mid(absl::nullopt);
2744 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002745 }
2746 }
2747 const MediaContentDescription* media_desc = content.media_description();
2748 auto transceiver = GetAssociatedTransceiver(content.name);
2749 if (source == cricket::CS_LOCAL) {
2750 // Find the RtpTransceiver that corresponds to this m= section, using the
2751 // mapping between transceivers and m= section indices established when
2752 // creating the offer.
2753 if (!transceiver) {
2754 transceiver = GetTransceiverByMLineIndex(mline_index);
2755 }
2756 if (!transceiver) {
2757 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2758 "Unknown transceiver");
2759 }
2760 } else {
2761 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2762 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2763 // of the same type...
2764 if (!transceiver &&
2765 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2766 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2767 }
2768 // If no RtpTransceiver was found in the previous step, create one with a
2769 // recvonly direction.
2770 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002771 RTC_LOG(LS_INFO) << "Adding "
2772 << cricket::MediaTypeToString(media_desc->type())
2773 << " transceiver for MID=" << content.name
2774 << " at i=" << mline_index
2775 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002776 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002777 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002778 std::string receiver_id;
2779 if (!media_desc->streams().empty()) {
2780 receiver_id = media_desc->streams()[0].id;
2781 } else {
2782 receiver_id = rtc::CreateRandomUuid();
2783 }
2784 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002785 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002786 transceiver->internal()->set_direction(
2787 RtpTransceiverDirection::kRecvOnly);
2788 }
2789 }
2790 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002791 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002792 LOG_AND_RETURN_ERROR(
2793 RTCErrorType::INVALID_PARAMETER,
2794 "Transceiver type does not match media description type.");
2795 }
2796 // Associate the found or created RtpTransceiver with the m= section by
2797 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2798 // section, and establish a mapping between the transceiver and the index of
2799 // the m= section.
2800 transceiver->internal()->set_mid(content.name);
2801 transceiver->internal()->set_mline_index(mline_index);
2802 return std::move(transceiver);
2803}
2804
2805rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2806PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2807 RTC_DCHECK(IsUnifiedPlan());
2808 for (auto transceiver : transceivers_) {
2809 if (transceiver->mid() == mid) {
2810 return transceiver;
2811 }
2812 }
2813 return nullptr;
2814}
2815
2816rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2817PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2818 RTC_DCHECK(IsUnifiedPlan());
2819 for (auto transceiver : transceivers_) {
2820 if (transceiver->internal()->mline_index() == mline_index) {
2821 return transceiver;
2822 }
2823 }
2824 return nullptr;
2825}
2826
2827rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2828PeerConnection::FindAvailableTransceiverToReceive(
2829 cricket::MediaType media_type) const {
2830 RTC_DCHECK(IsUnifiedPlan());
2831 // From JSEP section 5.10 (Applying a Remote Description):
2832 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2833 // the same type that were added to the PeerConnection by addTrack and are not
2834 // associated with any m= section and are not stopped, find the first such
2835 // RtpTransceiver.
2836 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002837 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002838 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2839 !transceiver->stopped()) {
2840 return transceiver;
2841 }
2842 }
2843 return nullptr;
2844}
2845
Steve Antoned10bd92017-12-05 10:52:59 -08002846const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2847 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2848 transceiver,
2849 const SessionDescriptionInterface* sdesc) const {
2850 RTC_DCHECK(transceiver);
2851 RTC_DCHECK(sdesc);
2852 if (IsUnifiedPlan()) {
2853 if (!transceiver->internal()->mid()) {
2854 // This transceiver is not associated with a media section yet.
2855 return nullptr;
2856 }
2857 return sdesc->description()->GetContentByName(
2858 *transceiver->internal()->mid());
2859 } else {
2860 // Plan B only allows at most one audio and one video section, so use the
2861 // first media section of that type.
2862 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002863 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002864 }
2865}
2866
deadbeef46c73892016-11-16 19:42:04 -08002867PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2868 return configuration_;
2869}
2870
deadbeef293e9262017-01-11 12:28:30 -08002871bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2872 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002873 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002874 if (IsClosed()) {
2875 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2876 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2877 }
2878
Qingsi Wanga2d60672018-04-11 16:57:45 -07002879 // According to JSEP, after setLocalDescription, changing the candidate pool
2880 // size is not allowed, and changing the set of ICE servers will not result
2881 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002882 if (local_description() && configuration.ice_candidate_pool_size !=
2883 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002884 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2885 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002886 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002887 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002888
deadbeef293e9262017-01-11 12:28:30 -08002889 // The simplest (and most future-compatible) way to tell if the config was
2890 // modified in an invalid way is to copy each property we do support
2891 // modifying, then use operator==. There are far more properties we don't
2892 // support modifying than those we do, and more could be added.
2893 RTCConfiguration modified_config = configuration_;
2894 modified_config.servers = configuration.servers;
2895 modified_config.type = configuration.type;
2896 modified_config.ice_candidate_pool_size =
2897 configuration.ice_candidate_pool_size;
2898 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002899 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002900 modified_config.ice_check_interval_strong_connectivity =
2901 configuration.ice_check_interval_strong_connectivity;
2902 modified_config.ice_check_interval_weak_connectivity =
2903 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002904 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2905 modified_config.ice_unwritable_min_checks =
2906 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002907 modified_config.stun_candidate_keepalive_interval =
2908 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002909 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002910 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002911 modified_config.active_reset_srtp_params =
2912 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002913 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002914 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002915 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2916 }
2917
Steve Anton038834f2017-07-14 15:59:59 -07002918 // Validate the modified configuration.
2919 RTCError validate_error = ValidateConfiguration(modified_config);
2920 if (!validate_error.ok()) {
2921 return SafeSetError(std::move(validate_error), error);
2922 }
2923
deadbeef293e9262017-01-11 12:28:30 -08002924 // Note that this isn't possible through chromium, since it's an unsigned
2925 // short in WebIDL.
2926 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002927 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002928 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2929 }
2930
2931 // Parse ICE servers before hopping to network thread.
2932 cricket::ServerAddresses stun_servers;
2933 std::vector<cricket::RelayServerConfig> turn_servers;
2934 RTCErrorType parse_error =
2935 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2936 if (parse_error != RTCErrorType::NONE) {
2937 return SafeSetError(parse_error, error);
2938 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002939 // Note if STUN or TURN servers were supplied.
2940 if (!stun_servers.empty()) {
2941 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2942 }
2943 if (!turn_servers.empty()) {
2944 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2945 }
deadbeef293e9262017-01-11 12:28:30 -08002946
2947 // In theory this shouldn't fail.
2948 if (!network_thread()->Invoke<bool>(
2949 RTC_FROM_HERE,
2950 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2951 stun_servers, turn_servers, modified_config.type,
2952 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002953 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002954 modified_config.turn_customizer,
2955 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002956 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002957 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2958 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002959
deadbeefd1a38b52016-12-10 13:15:33 -08002960 // As described in JSEP, calling setConfiguration with new ICE servers or
2961 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2962 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002963 if (modified_config.servers != configuration_.servers ||
2964 modified_config.type != configuration_.type ||
2965 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002966 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002967 }
skvladd1f5fda2017-02-03 16:54:05 -08002968
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002969 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002970
Zhi Huangb57e1692018-06-12 11:41:11 -07002971 if (configuration_.active_reset_srtp_params !=
2972 modified_config.active_reset_srtp_params) {
2973 transport_controller_->SetActiveResetSrtpParams(
2974 modified_config.active_reset_srtp_params);
2975 }
2976
deadbeef293e9262017-01-11 12:28:30 -08002977 configuration_ = modified_config;
2978 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002979}
2980
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981bool PeerConnection::AddIceCandidate(
2982 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002983 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002984 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002985 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002986 return false;
2987 }
Steve Antond25da372017-11-06 14:50:29 -08002988
2989 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002990 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002991 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002992 return false;
2993 }
2994
2995 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002996 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002997 return false;
2998 }
2999
3000 bool valid = false;
3001 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3002 if (!valid) {
3003 return false;
3004 }
3005
3006 // Add this candidate to the remote session description.
3007 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003008 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08003009 return false;
3010 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003011 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08003012
3013 if (ready) {
3014 return UseCandidate(ice_candidate);
3015 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003016 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08003017 return true;
3018 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019}
3020
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003021bool PeerConnection::RemoveIceCandidates(
3022 const std::vector<cricket::Candidate>& candidates) {
3023 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003024 if (IsClosed()) {
3025 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3026 return false;
3027 }
3028
Steve Antond25da372017-11-06 14:50:29 -08003029 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003030 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3031 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003032 return false;
3033 }
3034
3035 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003036 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003037 return false;
3038 }
3039
3040 size_t number_removed =
3041 mutable_remote_description()->RemoveCandidates(candidates);
3042 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003043 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003044 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003045 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003046 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003047 }
3048
3049 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003050 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3051 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003052 RTC_LOG(LS_ERROR)
3053 << "RemoveIceCandidates: Error when removing remote candidates: "
3054 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003055 }
3056 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003057}
3058
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003059void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003060 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003061 network_thread()->Invoke<void>(
3062 RTC_FROM_HERE,
3063 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
Qingsi Wanga2d60672018-04-11 16:57:45 -07003064}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003065
Qingsi Wanga2d60672018-04-11 16:57:45 -07003066void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3067 RTC_DCHECK(network_thread()->IsCurrent());
3068 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003069 if (transport_controller_) {
3070 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003071 }
3072
3073 for (auto transceiver : transceivers_) {
3074 auto* channel = transceiver->internal()->channel();
3075 if (channel) {
3076 channel->SetMetricsObserver(uma_observer_);
3077 }
3078 }
3079
deadbeef293e9262017-01-11 12:28:30 -08003080 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003081 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003082 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003083}
3084
Niels Möller0c4f7be2018-05-07 14:01:37 +02003085RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003086 if (!worker_thread()->IsCurrent()) {
3087 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003088 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003089 }
3090
Niels Möller0c4f7be2018-05-07 14:01:37 +02003091 const bool has_min = bitrate.min_bitrate_bps.has_value();
3092 const bool has_start = bitrate.start_bitrate_bps.has_value();
3093 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003094 if (has_min && *bitrate.min_bitrate_bps < 0) {
3095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3096 "min_bitrate_bps <= 0");
3097 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003098 if (has_start) {
3099 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003101 "start_bitrate_bps < min_bitrate_bps");
3102 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3104 "curent_bitrate_bps < 0");
3105 }
3106 }
3107 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003108 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003110 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003111 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3112 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3113 "max_bitrate_bps < min_bitrate_bps");
3114 } else if (*bitrate.max_bitrate_bps < 0) {
3115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3116 "max_bitrate_bps < 0");
3117 }
3118 }
3119
zstein4b979802017-06-02 14:37:37 -07003120 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003121 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003122
3123 return RTCError::OK();
3124}
3125
Alex Narest78609d52017-10-20 10:37:47 +02003126void PeerConnection::SetBitrateAllocationStrategy(
3127 std::unique_ptr<rtc::BitrateAllocationStrategy>
3128 bitrate_allocation_strategy) {
3129 rtc::Thread* worker_thread = factory_->worker_thread();
3130 if (!worker_thread->IsCurrent()) {
3131 rtc::BitrateAllocationStrategy* strategy_raw =
3132 bitrate_allocation_strategy.release();
3133 auto functor = [this, strategy_raw]() {
3134 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003135 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003136 };
3137 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3138 return;
3139 }
3140 RTC_DCHECK(call_.get());
3141 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3142}
3143
henrika5f6bf242017-11-01 11:06:56 +01003144void PeerConnection::SetAudioPlayout(bool playout) {
3145 if (!worker_thread()->IsCurrent()) {
3146 worker_thread()->Invoke<void>(
3147 RTC_FROM_HERE,
3148 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3149 return;
3150 }
3151 auto audio_state =
3152 factory_->channel_manager()->media_engine()->GetAudioState();
3153 audio_state->SetPlayout(playout);
3154}
3155
3156void PeerConnection::SetAudioRecording(bool recording) {
3157 if (!worker_thread()->IsCurrent()) {
3158 worker_thread()->Invoke<void>(
3159 RTC_FROM_HERE,
3160 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3161 return;
3162 }
3163 auto audio_state =
3164 factory_->channel_manager()->media_engine()->GetAudioState();
3165 audio_state->SetRecording(recording);
3166}
3167
Steve Anton8c0f7a72017-10-03 10:03:10 -07003168std::unique_ptr<rtc::SSLCertificate>
3169PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003170 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3171 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003172 return nullptr;
3173 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003174 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003175}
3176
Zhi Huang70b820f2018-01-27 14:16:15 -08003177std::unique_ptr<rtc::SSLCertChain>
3178PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003179 auto audio_transceiver = GetFirstAudioTransceiver();
3180 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003181 return nullptr;
3182 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003183 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003184 audio_transceiver->internal()->channel()->transport_name());
3185}
3186
3187rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3188PeerConnection::GetFirstAudioTransceiver() const {
3189 for (auto transceiver : transceivers_) {
3190 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3191 return transceiver;
3192 }
3193 }
3194 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003195}
3196
ivoc14d5dbe2016-07-04 07:06:55 -07003197bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3198 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003199 // TODO(eladalon): It would be better to not allow negative values into PC.
3200 const size_t max_size = (max_size_bytes < 0)
3201 ? RtcEventLog::kUnlimitedOutput
3202 : rtc::saturated_cast<size_t>(max_size_bytes);
3203 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003204 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003205 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003206}
3207
Bjorn Tereliusde939432017-11-20 17:38:14 +01003208bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3209 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003210 // TODO(eladalon): In C++14, this can be done with a lambda.
3211 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003212 bool operator()() {
3213 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3214 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003215 PeerConnection* const pc;
3216 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003217 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003218 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003219 return worker_thread()->Invoke<bool>(
3220 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003221}
3222
3223void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003224 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003225 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3226}
3227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003229 return pending_local_description_ ? pending_local_description_.get()
3230 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003231}
3232
3233const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003234 return pending_remote_description_ ? pending_remote_description_.get()
3235 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003236}
3237
deadbeeffe4a8a42016-12-20 17:56:17 -08003238const SessionDescriptionInterface* PeerConnection::current_local_description()
3239 const {
Steve Anton75737c02017-11-06 10:37:17 -08003240 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003241}
3242
3243const SessionDescriptionInterface* PeerConnection::current_remote_description()
3244 const {
Steve Anton75737c02017-11-06 10:37:17 -08003245 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003246}
3247
3248const SessionDescriptionInterface* PeerConnection::pending_local_description()
3249 const {
Steve Anton75737c02017-11-06 10:37:17 -08003250 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003251}
3252
3253const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3254 const {
Steve Anton75737c02017-11-06 10:37:17 -08003255 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003256}
3257
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003258void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003259 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 // Update stats here so that we have the most recent stats for tracks and
3261 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003262 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263
Steve Anton75737c02017-11-06 10:37:17 -08003264 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003265 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003266
Steve Anton8af21862017-12-15 11:20:13 -08003267 for (auto transceiver : transceivers_) {
3268 transceiver->Stop();
3269 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003270
3271 // Ensure that all asynchronous stats requests are completed before destroying
3272 // the transport controller below.
3273 if (stats_collector_) {
3274 stats_collector_->WaitForPendingRequest();
3275 }
3276
3277 // Don't destroy BaseChannels until after stats has been cleaned up so that
3278 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003279 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003280
Qingsi Wang93a84392018-01-30 17:13:09 -08003281 // The event log is used in the transport controller, which must be outlived
3282 // by the former. CreateOffer by the peer connection is implemented
3283 // asynchronously and if the peer connection is closed without resetting the
3284 // WebRTC session description factory, the session description factory would
3285 // call the transport controller.
3286 webrtc_session_desc_factory_.reset();
3287 transport_controller_.reset();
3288
deadbeef42a42632017-03-10 15:18:00 -08003289 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003290 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3291 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003292
Steve Anton978b8762017-09-29 12:15:02 -07003293 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003294 call_.reset();
3295 // The event log must outlive call (and any other object that uses it).
3296 event_log_.reset();
3297 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003298 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299}
3300
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003301void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3304 SetSessionDescriptionMsg* param =
3305 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3306 param->observer->OnSuccess();
3307 delete param;
3308 break;
3309 }
3310 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3311 SetSessionDescriptionMsg* param =
3312 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003313 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 delete param;
3315 break;
3316 }
deadbeefab9b2d12015-10-14 11:33:11 -07003317 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3318 CreateSessionDescriptionMsg* param =
3319 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003320 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003321 delete param;
3322 break;
3323 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 case MSG_GETSTATS: {
3325 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003326 StatsReports reports;
3327 stats_->GetStats(param->track, &reports);
3328 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329 delete param;
3330 break;
3331 }
deadbeefbd292462015-12-14 18:15:29 -08003332 case MSG_FREE_DATACHANNELS: {
3333 sctp_data_channels_to_free_.clear();
3334 break;
3335 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003336 case MSG_REPORT_USAGE_PATTERN: {
3337 ReportUsagePattern();
3338 break;
3339 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003341 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342 break;
3343 }
3344}
3345
Steve Antonafb0bb72018-02-20 11:35:37 -08003346cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3347 RTC_DCHECK(!IsUnifiedPlan());
3348 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3349 GetAudioTransceiver()->internal()->channel());
3350 if (voice_channel) {
3351 return voice_channel->media_channel();
3352 } else {
3353 return nullptr;
3354 }
3355}
3356
3357cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3358 RTC_DCHECK(!IsUnifiedPlan());
3359 auto* video_channel = static_cast<cricket::VideoChannel*>(
3360 GetVideoTransceiver()->internal()->channel());
3361 if (video_channel) {
3362 return video_channel->media_channel();
3363 } else {
3364 return nullptr;
3365 }
3366}
3367
Steve Anton4171afb2017-11-20 10:20:22 -08003368void PeerConnection::CreateAudioReceiver(
3369 MediaStreamInterface* stream,
3370 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003371 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3372 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003373 auto* audio_receiver = new AudioRtpReceiver(
3374 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003375 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003376 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3377 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3378 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003379 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003380 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003381 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003382}
3383
Steve Anton4171afb2017-11-20 10:20:22 -08003384void PeerConnection::CreateVideoReceiver(
3385 MediaStreamInterface* stream,
3386 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003387 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3388 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003389 auto* video_receiver = new VideoRtpReceiver(
3390 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003391 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003392 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3393 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3394 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003395 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003396 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003397 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398}
3399
deadbeef70ab1a12015-09-28 16:53:55 -07003400// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3401// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003402rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003403 const RtpSenderInfo& remote_sender_info) {
3404 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3405 if (!receiver) {
3406 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3407 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003408 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003409 }
Steve Anton4171afb2017-11-20 10:20:22 -08003410 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3411 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3412 } else {
3413 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3414 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003415 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416}
3417
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003418void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3419 MediaStreamInterface* stream) {
3420 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003421 RTC_DCHECK(track);
3422 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003423 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003424 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003425 // We already have a sender for this track, so just change the stream_id
3426 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003427 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003428 return;
3429 }
3430
3431 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003432 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3433 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003434 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003435 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003436 // If the sender has already been configured in SDP, we call SetSsrc,
3437 // which will connect the sender to the underlying transport. This can
3438 // occur if a local session description that contains the ID of the sender
3439 // is set before AddStream is called. It can also occur if the local
3440 // session description is not changed and RemoveStream is called, and
3441 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003442 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003443 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003444 if (sender_info) {
3445 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003446 }
3447}
3448
3449// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3450// indefinitely, when we have unified plan SDP.
3451void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3452 MediaStreamInterface* stream) {
3453 RTC_DCHECK(!IsClosed());
3454 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003455 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003456 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3457 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003458 return;
3459 }
Steve Anton4171afb2017-11-20 10:20:22 -08003460 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003461}
3462
3463void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3464 MediaStreamInterface* stream) {
3465 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003466 RTC_DCHECK(track);
3467 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003469 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003470 // We already have a sender for this track, so just change the stream_id
3471 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003472 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003473 return;
3474 }
3475
3476 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003477 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3478 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003479 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003480 GetVideoTransceiver()->internal()->AddSender(new_sender);
3481 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003482 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003483 if (sender_info) {
3484 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003485 }
3486}
3487
3488void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3489 MediaStreamInterface* stream) {
3490 RTC_DCHECK(!IsClosed());
3491 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003492 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003493 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3494 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003495 return;
3496 }
Steve Anton4171afb2017-11-20 10:20:22 -08003497 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003498}
3499
Steve Antonba818672017-11-06 10:21:57 -08003500void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003501 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003502 if (ice_connection_state_ == new_state) {
3503 return;
3504 }
3505
deadbeefcbecd352015-09-23 11:50:27 -07003506 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003507 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003508 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003509 return;
3510 }
Steve Antonba818672017-11-06 10:21:57 -08003511
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3513 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003514 RTC_DCHECK(ice_connection_state_ !=
3515 PeerConnectionInterface::kIceConnectionClosed);
3516
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003518 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519}
3520
3521void PeerConnection::OnIceGatheringChange(
3522 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003523 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524 if (IsClosed()) {
3525 return;
3526 }
3527 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003528 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529}
3530
jbauch81bf7b02017-03-25 08:31:12 -07003531void PeerConnection::OnIceCandidate(
3532 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003533 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003534 if (IsClosed()) {
3535 return;
3536 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003537 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003538 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539}
3540
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003541void PeerConnection::OnIceCandidatesRemoved(
3542 const std::vector<cricket::Candidate>& candidates) {
3543 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003544 if (IsClosed()) {
3545 return;
3546 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003547 observer_->OnIceCandidatesRemoved(candidates);
3548}
3549
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003550void PeerConnection::ChangeSignalingState(
3551 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003552 RTC_DCHECK(signaling_thread()->IsCurrent());
3553 if (signaling_state_ == signaling_state) {
3554 return;
3555 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003556 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3557 << GetSignalingStateString(signaling_state_)
3558 << " New state: "
3559 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003560 signaling_state_ = signaling_state;
3561 if (signaling_state == kClosed) {
3562 ice_connection_state_ = kIceConnectionClosed;
3563 observer_->OnIceConnectionChange(ice_connection_state_);
3564 if (ice_gathering_state_ != kIceGatheringComplete) {
3565 ice_gathering_state_ = kIceGatheringComplete;
3566 observer_->OnIceGatheringChange(ice_gathering_state_);
3567 }
3568 }
3569 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003570}
3571
deadbeefeb459812015-12-15 19:24:43 -08003572void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3573 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003574 if (IsClosed()) {
3575 return;
3576 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003577 AddAudioTrack(track, stream);
3578 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003579}
3580
deadbeefeb459812015-12-15 19:24:43 -08003581void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3582 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003583 if (IsClosed()) {
3584 return;
3585 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 RemoveAudioTrack(track, stream);
3587 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003588}
3589
3590void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3591 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003592 if (IsClosed()) {
3593 return;
3594 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003595 AddVideoTrack(track, stream);
3596 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003597}
3598
3599void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3600 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003601 if (IsClosed()) {
3602 return;
3603 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003604 RemoveVideoTrack(track, stream);
3605 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003606}
3607
Henrik Boström31638672017-11-23 17:48:32 +01003608void PeerConnection::PostSetSessionDescriptionSuccess(
3609 SetSessionDescriptionObserver* observer) {
3610 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3611 signaling_thread()->Post(RTC_FROM_HERE, this,
3612 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3613}
3614
deadbeefab9b2d12015-10-14 11:33:11 -07003615void PeerConnection::PostSetSessionDescriptionFailure(
3616 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003617 RTCError&& error) {
3618 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003619 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003620 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003621 signaling_thread()->Post(RTC_FROM_HERE, this,
3622 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003623}
3624
3625void PeerConnection::PostCreateSessionDescriptionFailure(
3626 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003627 RTCError error) {
3628 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003629 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003630 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003631 signaling_thread()->Post(RTC_FROM_HERE, this,
3632 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003633}
3634
zhihuang1c378ed2017-08-17 14:10:50 -07003635void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003636 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003637 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003638 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003639
Steve Antondcc3c022017-12-22 16:02:54 -08003640 if (IsUnifiedPlan()) {
3641 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3642 } else {
3643 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3644 }
3645
Steve Antonfa2260d2017-12-28 16:38:23 -08003646 // Intentionally unset the data channel type for RTP data channel with the
3647 // second condition. Otherwise the RTP data channels would be successfully
3648 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3649 // when building with chromium. We want to leave RTP data channels broken, so
3650 // people won't try to use them.
3651 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3652 session_options->data_channel_type = data_channel_type();
3653 }
3654
Steve Antondcc3c022017-12-22 16:02:54 -08003655 // Apply ICE restart flag and renomination flag.
3656 for (auto& options : session_options->media_description_options) {
3657 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3658 options.transport_options.enable_ice_renomination =
3659 configuration_.enable_ice_renomination;
3660 }
3661
3662 session_options->rtcp_cname = rtcp_cname_;
3663 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003664 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003665}
3666
3667void PeerConnection::GetOptionsForPlanBOffer(
3668 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3669 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003670 // Figure out transceiver directional preferences.
3671 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3672 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3673
3674 // By default, generate sendrecv/recvonly m= sections.
3675 bool recv_audio = true;
3676 bool recv_video = true;
3677
3678 // By default, only offer a new m= section if we have media to send with it.
3679 bool offer_new_audio_description = send_audio;
3680 bool offer_new_video_description = send_video;
3681 bool offer_new_data_description = HasDataChannels();
3682
3683 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003684 if (offer_answer_options.offer_to_receive_audio !=
3685 RTCOfferAnswerOptions::kUndefined) {
3686 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003687 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003688 offer_new_audio_description ||
3689 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003690 }
Steve Antondcc3c022017-12-22 16:02:54 -08003691 if (offer_answer_options.offer_to_receive_video !=
3692 RTCOfferAnswerOptions::kUndefined) {
3693 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003694 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003695 offer_new_video_description ||
3696 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003697 }
3698
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003699 absl::optional<size_t> audio_index;
3700 absl::optional<size_t> video_index;
3701 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003702 // If a current description exists, generate m= sections in the same order,
3703 // using the first audio/video/data section that appears and rejecting
3704 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003705 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003706 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003707 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003708 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3709 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3710 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003711 }
3712
zhihuang1c378ed2017-08-17 14:10:50 -07003713 // Add audio/video/data m= sections to the end if needed.
3714 if (!audio_index && offer_new_audio_description) {
3715 session_options->media_description_options.push_back(
3716 cricket::MediaDescriptionOptions(
3717 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003718 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3719 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003720 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003721 }
zhihuang1c378ed2017-08-17 14:10:50 -07003722 if (!video_index && offer_new_video_description) {
3723 session_options->media_description_options.push_back(
3724 cricket::MediaDescriptionOptions(
3725 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003726 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3727 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003728 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003729 }
zhihuang1c378ed2017-08-17 14:10:50 -07003730 if (!data_index && offer_new_data_description) {
3731 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003732 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003733 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003734 }
3735
3736 cricket::MediaDescriptionOptions* audio_media_description_options =
3737 !audio_index ? nullptr
3738 : &session_options->media_description_options[*audio_index];
3739 cricket::MediaDescriptionOptions* video_media_description_options =
3740 !video_index ? nullptr
3741 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003742
Steve Anton4171afb2017-11-20 10:20:22 -08003743 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003744 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003745}
3746
3747// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3748// and return a reference to it.
3749// Generated MIDs should be no more than 3 bytes long to take up less space in
3750// the RTP packet.
3751static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3752 RTC_DCHECK(used_mids);
3753 // We're boring: just generate MIDs 0, 1, 2, ...
3754 size_t i = 0;
3755 std::set<std::string>::iterator it;
3756 bool inserted;
3757 do {
3758 std::string mid = rtc::ToString(i++);
3759 auto insert_result = used_mids->insert(mid);
3760 it = insert_result.first;
3761 inserted = insert_result.second;
3762 } while (!inserted);
3763 return *it;
3764}
3765
3766static cricket::MediaDescriptionOptions
3767GetMediaDescriptionOptionsForTransceiver(
3768 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3769 transceiver,
3770 const std::string& mid) {
3771 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003772 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003773 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003774 // This behavior is specified in JSEP. The gist is that:
3775 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3776 // sendrecv.
3777 // 2. If the MSID is included, then it must be included in any subsequent
3778 // offer/answer exactly the same until the RtpTransceiver is stopped.
3779 if (!transceiver->stopped() &&
3780 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3781 transceiver->internal()->has_ever_been_used_to_send())) {
3782 cricket::SenderOptions sender_options;
3783 sender_options.track_id = transceiver->sender()->id();
3784 sender_options.stream_ids = transceiver->sender()->stream_ids();
3785 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3786 // set in the RTP parameters when the transceiver was added.
3787 sender_options.num_sim_layers = 1;
3788 media_description_options.sender_options.push_back(sender_options);
3789 }
Steve Antondcc3c022017-12-22 16:02:54 -08003790 return media_description_options;
3791}
3792
3793void PeerConnection::GetOptionsForUnifiedPlanOffer(
3794 const RTCOfferAnswerOptions& offer_answer_options,
3795 cricket::MediaSessionOptions* session_options) {
3796 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3797 // Offers) and 5.2.2 (Subsequent Offers).
3798 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3799 const ContentInfos& local_contents =
3800 (local_description() ? local_description()->description()->contents()
3801 : ContentInfos());
3802 const ContentInfos& remote_contents =
3803 (remote_description() ? remote_description()->description()->contents()
3804 : ContentInfos());
3805 // The mline indices that can be recycled. New transceivers should reuse these
3806 // slots first.
3807 std::queue<size_t> recycleable_mline_indices;
3808 // Track the MIDs used in previous offer/answer exchanges and the current
3809 // offer so that new, unique MIDs are generated.
3810 std::set<std::string> used_mids = seen_mids_;
3811 // First, go through each media section that exists in either the local or
3812 // remote description and generate a media section in this offer for the
3813 // associated transceiver. If a media section can be recycled, generate a
3814 // default, rejected media section here that can be later overwritten.
3815 for (size_t i = 0;
3816 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3817 // Either |local_content| or |remote_content| is non-null.
3818 const ContentInfo* local_content =
3819 (i < local_contents.size() ? &local_contents[i] : nullptr);
3820 const ContentInfo* remote_content =
3821 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3822 bool had_been_rejected = (local_content && local_content->rejected) ||
3823 (remote_content && remote_content->rejected);
3824 const std::string& mid =
3825 (local_content ? local_content->name : remote_content->name);
3826 cricket::MediaType media_type =
3827 (local_content ? local_content->media_description()->type()
3828 : remote_content->media_description()->type());
3829 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3830 media_type == cricket::MEDIA_TYPE_VIDEO) {
3831 auto transceiver = GetAssociatedTransceiver(mid);
3832 RTC_CHECK(transceiver);
3833 // A media section is considered eligible for recycling if it is marked as
3834 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003835 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003836 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003837 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3838 RtpTransceiverDirection::kInactive,
3839 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003840 recycleable_mline_indices.push(i);
3841 } else {
3842 session_options->media_description_options.push_back(
3843 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3844 // CreateOffer shouldn't really cause any state changes in
3845 // PeerConnection, but we need a way to match new transceivers to new
3846 // media sections in SetLocalDescription and JSEP specifies this is done
3847 // by recording the index of the media section generated for the
3848 // transceiver in the offer.
3849 transceiver->internal()->set_mline_index(i);
3850 }
3851 } else {
3852 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003853 RTC_CHECK(GetDataMid());
3854 if (had_been_rejected || mid != *GetDataMid()) {
3855 session_options->media_description_options.push_back(
3856 GetMediaDescriptionOptionsForRejectedData(mid));
3857 } else {
3858 session_options->media_description_options.push_back(
3859 GetMediaDescriptionOptionsForActiveData(mid));
3860 }
Steve Antondcc3c022017-12-22 16:02:54 -08003861 }
3862 }
3863 // Next, look for transceivers that are newly added (that is, are not stopped
3864 // and not associated). Reuse media sections marked as recyclable first,
3865 // otherwise append to the end of the offer. New media sections should be
3866 // added in the order they were added to the PeerConnection.
3867 for (auto transceiver : transceivers_) {
3868 if (transceiver->mid() || transceiver->stopped()) {
3869 continue;
3870 }
3871 size_t mline_index;
3872 if (!recycleable_mline_indices.empty()) {
3873 mline_index = recycleable_mline_indices.front();
3874 recycleable_mline_indices.pop();
3875 session_options->media_description_options[mline_index] =
3876 GetMediaDescriptionOptionsForTransceiver(transceiver,
3877 AllocateMid(&used_mids));
3878 } else {
3879 mline_index = session_options->media_description_options.size();
3880 session_options->media_description_options.push_back(
3881 GetMediaDescriptionOptionsForTransceiver(transceiver,
3882 AllocateMid(&used_mids)));
3883 }
3884 // See comment above for why CreateOffer changes the transceiver's state.
3885 transceiver->internal()->set_mline_index(mline_index);
3886 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003887 // Lastly, add a m-section if we have local data channels and an m section
3888 // does not already exist.
3889 if (!GetDataMid() && HasDataChannels()) {
3890 session_options->media_description_options.push_back(
3891 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3892 }
Steve Antondcc3c022017-12-22 16:02:54 -08003893}
3894
3895void PeerConnection::GetOptionsForAnswer(
3896 const RTCOfferAnswerOptions& offer_answer_options,
3897 cricket::MediaSessionOptions* session_options) {
3898 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3899
3900 if (IsUnifiedPlan()) {
3901 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3902 } else {
3903 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3904 }
3905
Steve Antonfa2260d2017-12-28 16:38:23 -08003906 // Intentionally unset the data channel type for RTP data channel. Otherwise
3907 // the RTP data channels would be successfully negotiated by default and the
3908 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3909 // We want to leave RTP data channels broken, so people won't try to use them.
3910 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3911 session_options->data_channel_type = data_channel_type();
3912 }
3913
Steve Antondcc3c022017-12-22 16:02:54 -08003914 // Apply ICE renomination flag.
3915 for (auto& options : session_options->media_description_options) {
3916 options.transport_options.enable_ice_renomination =
3917 configuration_.enable_ice_renomination;
3918 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003919
3920 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003921 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003922 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003923}
3924
Steve Antondcc3c022017-12-22 16:02:54 -08003925void PeerConnection::GetOptionsForPlanBAnswer(
3926 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003927 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003928 // Figure out transceiver directional preferences.
3929 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3930 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3931
3932 // By default, generate sendrecv/recvonly m= sections. The direction is also
3933 // restricted by the direction in the offer.
3934 bool recv_audio = true;
3935 bool recv_video = true;
3936
3937 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003938 if (offer_answer_options.offer_to_receive_audio !=
3939 RTCOfferAnswerOptions::kUndefined) {
3940 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003941 }
Steve Antondcc3c022017-12-22 16:02:54 -08003942 if (offer_answer_options.offer_to_receive_video !=
3943 RTCOfferAnswerOptions::kUndefined) {
3944 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003945 }
3946
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003947 absl::optional<size_t> audio_index;
3948 absl::optional<size_t> video_index;
3949 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003950
3951 // Generate m= sections that match those in the offer.
3952 // Note that mediasession.cc will handle intersection our preferred
3953 // direction with the offered direction.
3954 GenerateMediaDescriptionOptions(
3955 remote_description(),
3956 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3957 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3958 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003959
3960 cricket::MediaDescriptionOptions* audio_media_description_options =
3961 !audio_index ? nullptr
3962 : &session_options->media_description_options[*audio_index];
3963 cricket::MediaDescriptionOptions* video_media_description_options =
3964 !video_index ? nullptr
3965 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003966
Steve Anton4171afb2017-11-20 10:20:22 -08003967 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003968 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003969}
zhihuangaf388472016-11-02 16:49:48 -07003970
Steve Antondcc3c022017-12-22 16:02:54 -08003971void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3972 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3973 cricket::MediaSessionOptions* session_options) {
3974 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3975 // Answers) and 5.3.2 (Subsequent Answers).
3976 RTC_DCHECK(remote_description());
3977 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3978 for (const ContentInfo& content :
3979 remote_description()->description()->contents()) {
3980 cricket::MediaType media_type = content.media_description()->type();
3981 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3982 media_type == cricket::MEDIA_TYPE_VIDEO) {
3983 auto transceiver = GetAssociatedTransceiver(content.name);
3984 RTC_CHECK(transceiver);
3985 session_options->media_description_options.push_back(
3986 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3987 } else {
3988 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003989 // Reject all data sections if data channels are disabled.
3990 // Reject a data section if it has already been rejected.
3991 // Reject all data sections except for the first one.
3992 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3993 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003994 session_options->media_description_options.push_back(
3995 GetMediaDescriptionOptionsForRejectedData(content.name));
3996 } else {
3997 session_options->media_description_options.push_back(
3998 GetMediaDescriptionOptionsForActiveData(content.name));
3999 }
Steve Antondcc3c022017-12-22 16:02:54 -08004000 }
4001 }
htaa2a49d92016-03-04 02:51:39 -08004002}
4003
zhihuang1c378ed2017-08-17 14:10:50 -07004004void PeerConnection::GenerateMediaDescriptionOptions(
4005 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004006 RtpTransceiverDirection audio_direction,
4007 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004008 absl::optional<size_t>* audio_index,
4009 absl::optional<size_t>* video_index,
4010 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004011 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004012 for (const cricket::ContentInfo& content :
4013 session_desc->description()->contents()) {
4014 if (IsAudioContent(&content)) {
4015 // If we already have an audio m= section, reject this extra one.
4016 if (*audio_index) {
4017 session_options->media_description_options.push_back(
4018 cricket::MediaDescriptionOptions(
4019 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004020 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004021 } else {
4022 session_options->media_description_options.push_back(
4023 cricket::MediaDescriptionOptions(
4024 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004025 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004026 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004027 }
4028 } else if (IsVideoContent(&content)) {
4029 // If we already have an video m= section, reject this extra one.
4030 if (*video_index) {
4031 session_options->media_description_options.push_back(
4032 cricket::MediaDescriptionOptions(
4033 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004034 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004035 } else {
4036 session_options->media_description_options.push_back(
4037 cricket::MediaDescriptionOptions(
4038 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004039 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004040 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004041 }
4042 } else {
4043 RTC_DCHECK(IsDataContent(&content));
4044 // If we already have an data m= section, reject this extra one.
4045 if (*data_index) {
4046 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004047 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004048 } else {
4049 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004050 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004051 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004052 }
4053 }
htaa2a49d92016-03-04 02:51:39 -08004054 }
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
Steve Antonfa2260d2017-12-28 16:38:23 -08004057cricket::MediaDescriptionOptions
4058PeerConnection::GetMediaDescriptionOptionsForActiveData(
4059 const std::string& mid) const {
4060 // Direction for data sections is meaningless, but legacy endpoints might
4061 // expect sendrecv.
4062 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4063 RtpTransceiverDirection::kSendRecv,
4064 /*stopped=*/false);
4065 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4066 return options;
4067}
4068
4069cricket::MediaDescriptionOptions
4070PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4071 const std::string& mid) const {
4072 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4073 RtpTransceiverDirection::kInactive,
4074 /*stopped=*/true);
4075 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4076 return options;
4077}
4078
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004079absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004080 switch (data_channel_type_) {
4081 case cricket::DCT_RTP:
4082 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004083 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004084 }
4085 return rtp_data_channel_->content_name();
4086 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004087 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004088 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004089 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004090 }
4091}
4092
Steve Anton4171afb2017-11-20 10:20:22 -08004093void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4094 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4095 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004096 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004097}
4098
Steve Anton4171afb2017-11-20 10:20:22 -08004099void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004100 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004101 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004102 cricket::MediaType media_type,
4103 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004104 RTC_DCHECK(!IsUnifiedPlan());
4105
Steve Anton4171afb2017-11-20 10:20:22 -08004106 std::vector<RtpSenderInfo>* current_senders =
4107 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004108
Steve Anton4171afb2017-11-20 10:20:22 -08004109 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004110 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004111 for (auto sender_it = current_senders->begin();
4112 sender_it != current_senders->end();
4113 /* incremented manually */) {
4114 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004115 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004116 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004117 std::string params_stream_id;
4118 if (params) {
4119 params_stream_id =
4120 (!params->first_stream_id().empty() ? params->first_stream_id()
4121 : kDefaultStreamId);
4122 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004123 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004124 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004125 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004126 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004127 sender_exists) {
4128 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004129 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004130 OnRemoteSenderRemoved(info, media_type);
4131 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004132 }
4133 }
4134
Steve Anton4171afb2017-11-20 10:20:22 -08004135 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004136 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004137 if (!params.has_ssrcs()) {
4138 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4139 // sender, this means it is coming from a Unified Plan endpoint,so we just
4140 // create a default.
4141 default_sender_needed = true;
4142 break;
4143 }
4144
Seth Hampson845e8782018-03-02 11:34:10 -08004145 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004146 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004147 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4148 // not supported in Plan B, we just take the first here and create the
4149 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004150 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004151 (!params.first_stream_id().empty() ? params.first_stream_id()
4152 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004153 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004154 uint32_t ssrc = params.first_ssrc();
4155
4156 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004157 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004158 if (!stream) {
4159 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004160 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004161 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004162 remote_streams_->AddStream(stream);
4163 new_streams->AddStream(stream);
4164 }
4165
Steve Anton4171afb2017-11-20 10:20:22 -08004166 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004167 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004168 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004169 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004170 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004171 }
4172 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004173
Steve Anton4171afb2017-11-20 10:20:22 -08004174 // Add default sender if necessary.
4175 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004176 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004177 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004178 if (!default_stream) {
4179 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004180 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004181 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004182 remote_streams_->AddStream(default_stream);
4183 new_streams->AddStream(default_stream);
4184 }
Steve Anton4171afb2017-11-20 10:20:22 -08004185 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4186 ? kDefaultAudioSenderId
4187 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004188 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004189 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004190 if (!default_sender_info) {
4191 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004192 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004193 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004194 }
4195 }
deadbeefab9b2d12015-10-14 11:33:11 -07004196}
4197
Steve Anton4171afb2017-11-20 10:20:22 -08004198void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4199 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004200 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4201 << " receiver for track_id=" << sender_info.sender_id
4202 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004203
Steve Anton3d954a62018-04-02 11:27:23 -07004204 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004205 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004206 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004207 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004208 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004209 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004210 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004211 }
4212}
4213
Steve Anton4171afb2017-11-20 10:20:22 -08004214void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4215 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004216 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4217 << " receiver for track_id=" << sender_info.sender_id
4218 << " and stream_id=" << sender_info.stream_id;
4219
Seth Hampson845e8782018-03-02 11:34:10 -08004220 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004221
Henrik Boström933d8b02017-10-10 10:05:16 -07004222 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004223 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004224 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4225 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004226 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004227 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004228 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004229 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004230 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004231 }
4232 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004233 // Stopping or destroying a VideoRtpReceiver will end the
4234 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004235 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004236 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004237 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004238 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004239 // There's no guarantee the track is still available, e.g. the track may
4240 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004241 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004242 }
4243 } else {
nisseede5da42017-01-12 05:15:36 -08004244 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004245 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004246 if (receiver) {
4247 observer_->OnRemoveTrack(receiver);
4248 }
deadbeefab9b2d12015-10-14 11:33:11 -07004249}
4250
4251void PeerConnection::UpdateEndedRemoteMediaStreams() {
4252 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4253 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4254 MediaStreamInterface* stream = remote_streams_->at(i);
4255 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4256 streams_to_remove.push_back(stream);
4257 }
4258 }
4259
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004260 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004261 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004262 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004263 }
4264}
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004267 const std::vector<cricket::StreamParams>& streams,
4268 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004269 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004270
Seth Hampson845e8782018-03-02 11:34:10 -08004271 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004272 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004273 for (auto sender_it = current_senders->begin();
4274 sender_it != current_senders->end();
4275 /* incremented manually */) {
4276 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004277 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004278 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4279 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004280 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004281 OnLocalSenderRemoved(info, media_type);
4282 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004283 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004284 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004285 }
4286 }
4287
Steve Anton4171afb2017-11-20 10:20:22 -08004288 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004289 for (const cricket::StreamParams& params : streams) {
4290 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004291 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004292 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004293 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004294 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004295 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004296 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004297 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004298 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004299 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004300 }
4301 }
4302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4305 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004306 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004307 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004308 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004309 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4310 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004312 return;
4313 }
4314
deadbeeffac06552015-11-25 11:26:01 -08004315 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004316 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004317 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004318 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004319 }
deadbeeffac06552015-11-25 11:26:01 -08004320
Seth Hampson5b4f0752018-04-02 16:31:36 -07004321 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004322 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004323}
4324
Steve Anton4171afb2017-11-20 10:20:22 -08004325void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4326 cricket::MediaType media_type) {
4327 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004328 if (!sender) {
4329 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004330 // SessionDescriptions has been renegotiated.
4331 return;
4332 }
deadbeeffac06552015-11-25 11:26:01 -08004333
4334 // A sender has been removed from the SessionDescription but it's still
4335 // associated with the PeerConnection. This only occurs if the SDP doesn't
4336 // match with the calls to CreateSender, AddStream and RemoveStream.
4337 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004339 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004340 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004341 }
deadbeeffac06552015-11-25 11:26:01 -08004342
Steve Anton4171afb2017-11-20 10:20:22 -08004343 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004344}
4345
4346void PeerConnection::UpdateLocalRtpDataChannels(
4347 const cricket::StreamParamsVec& streams) {
4348 std::vector<std::string> existing_channels;
4349
4350 // Find new and active data channels.
4351 for (const cricket::StreamParams& params : streams) {
4352 // |it->sync_label| is actually the data channel label. The reason is that
4353 // we use the same naming of data channels as we do for
4354 // MediaStreams and Tracks.
4355 // For MediaStreams, the sync_label is the MediaStream label and the
4356 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004357 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004358 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004359 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004360 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004361 continue;
4362 }
4363 // Set the SSRC the data channel should use for sending.
4364 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4365 existing_channels.push_back(data_channel_it->first);
4366 }
4367
4368 UpdateClosingRtpDataChannels(existing_channels, true);
4369}
4370
4371void PeerConnection::UpdateRemoteRtpDataChannels(
4372 const cricket::StreamParamsVec& streams) {
4373 std::vector<std::string> existing_channels;
4374
4375 // Find new and active data channels.
4376 for (const cricket::StreamParams& params : streams) {
4377 // The data channel label is either the mslabel or the SSRC if the mslabel
4378 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004379 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004380 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004381 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004382 auto data_channel_it = rtp_data_channels_.find(label);
4383 if (data_channel_it == rtp_data_channels_.end()) {
4384 // This is a new data channel.
4385 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4386 } else {
4387 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4388 }
4389 existing_channels.push_back(label);
4390 }
4391
4392 UpdateClosingRtpDataChannels(existing_channels, false);
4393}
4394
4395void PeerConnection::UpdateClosingRtpDataChannels(
4396 const std::vector<std::string>& active_channels,
4397 bool is_local_update) {
4398 auto it = rtp_data_channels_.begin();
4399 while (it != rtp_data_channels_.end()) {
4400 DataChannel* data_channel = it->second;
4401 if (std::find(active_channels.begin(), active_channels.end(),
4402 data_channel->label()) != active_channels.end()) {
4403 ++it;
4404 continue;
4405 }
4406
4407 if (is_local_update) {
4408 data_channel->SetSendSsrc(0);
4409 } else {
4410 data_channel->RemotePeerRequestClose();
4411 }
4412
4413 if (data_channel->state() == DataChannel::kClosed) {
4414 rtp_data_channels_.erase(it);
4415 it = rtp_data_channels_.begin();
4416 } else {
4417 ++it;
4418 }
4419 }
4420}
4421
4422void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4423 uint32_t remote_ssrc) {
4424 rtc::scoped_refptr<DataChannel> channel(
4425 InternalCreateDataChannel(label, nullptr));
4426 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004427 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004428 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004429 return;
4430 }
4431 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004432 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4433 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004434 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004435}
4436
4437rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4438 const std::string& label,
4439 const InternalDataChannelInit* config) {
4440 if (IsClosed()) {
4441 return nullptr;
4442 }
Steve Anton75737c02017-11-06 10:37:17 -08004443 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004444 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004445 << "InternalCreateDataChannel: Data is not supported in this call.";
4446 return nullptr;
4447 }
4448 InternalDataChannelInit new_config =
4449 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004450 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004451 if (new_config.id < 0) {
4452 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004453 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004454 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004455 RTC_LOG(LS_ERROR)
4456 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004457 return nullptr;
4458 }
4459 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004460 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004461 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004462 return nullptr;
4463 }
4464 }
4465
Steve Anton75737c02017-11-06 10:37:17 -08004466 rtc::scoped_refptr<DataChannel> channel(
4467 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004468 if (!channel) {
4469 sid_allocator_.ReleaseSid(new_config.id);
4470 return nullptr;
4471 }
4472
4473 if (channel->data_channel_type() == cricket::DCT_RTP) {
4474 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004475 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4476 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004477 return nullptr;
4478 }
4479 rtp_data_channels_[channel->label()] = channel;
4480 } else {
4481 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4482 sctp_data_channels_.push_back(channel);
4483 channel->SignalClosed.connect(this,
4484 &PeerConnection::OnSctpDataChannelClosed);
4485 }
4486
Steve Anton2d8609c2018-01-23 16:38:46 -08004487 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004488 return channel;
4489}
4490
4491bool PeerConnection::HasDataChannels() const {
4492 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4493}
4494
4495void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4496 for (const auto& channel : sctp_data_channels_) {
4497 if (channel->id() < 0) {
4498 int sid;
4499 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004500 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004501 continue;
4502 }
4503 channel->SetSctpSid(sid);
4504 }
4505 }
4506}
4507
4508void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004509 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004510 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4511 ++it) {
4512 if (it->get() == channel) {
4513 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004514 // After the closing procedure is done, it's safe to use this ID for
4515 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004516 sid_allocator_.ReleaseSid(channel->id());
4517 }
deadbeefbd292462015-12-14 18:15:29 -08004518 // Since this method is triggered by a signal from the DataChannel,
4519 // we can't free it directly here; we need to free it asynchronously.
4520 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004521 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004522 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4523 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004524 return;
4525 }
4526 }
4527}
4528
deadbeefab9b2d12015-10-14 11:33:11 -07004529void PeerConnection::OnDataChannelDestroyed() {
4530 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4531 // DataChannel may callback to us and try to modify the list.
4532 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4533 temp_rtp_dcs.swap(rtp_data_channels_);
4534 for (const auto& kv : temp_rtp_dcs) {
4535 kv.second->OnTransportChannelDestroyed();
4536 }
4537
4538 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4539 temp_sctp_dcs.swap(sctp_data_channels_);
4540 for (const auto& channel : temp_sctp_dcs) {
4541 channel->OnTransportChannelDestroyed();
4542 }
4543}
4544
4545void PeerConnection::OnDataChannelOpenMessage(
4546 const std::string& label,
4547 const InternalDataChannelInit& config) {
4548 rtc::scoped_refptr<DataChannel> channel(
4549 InternalCreateDataChannel(label, &config));
4550 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004551 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004552 return;
4553 }
4554
deadbeefa601f5c2016-06-06 14:27:39 -07004555 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4556 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004557 observer_->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004558 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004559}
4560
Steve Anton4171afb2017-11-20 10:20:22 -08004561rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4562PeerConnection::GetAudioTransceiver() const {
4563 // This method only works with Plan B SDP, where there is a single
4564 // audio/video transceiver.
4565 RTC_DCHECK(!IsUnifiedPlan());
4566 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004567 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004568 return transceiver;
4569 }
4570 }
4571 RTC_NOTREACHED();
4572 return nullptr;
4573}
4574
4575rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4576PeerConnection::GetVideoTransceiver() const {
4577 // This method only works with Plan B SDP, where there is a single
4578 // audio/video transceiver.
4579 RTC_DCHECK(!IsUnifiedPlan());
4580 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004581 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004582 return transceiver;
4583 }
4584 }
4585 RTC_NOTREACHED();
4586 return nullptr;
4587}
4588
4589// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4590// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004591bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004592 switch (type) {
4593 case cricket::MEDIA_TYPE_AUDIO:
4594 return !GetAudioTransceiver()->internal()->senders().empty();
4595 case cricket::MEDIA_TYPE_VIDEO:
4596 return !GetVideoTransceiver()->internal()->senders().empty();
4597 case cricket::MEDIA_TYPE_DATA:
4598 return false;
4599 }
4600 RTC_NOTREACHED();
4601 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004602}
4603
Steve Anton4171afb2017-11-20 10:20:22 -08004604rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4605PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4606 for (auto transceiver : transceivers_) {
4607 for (auto sender : transceiver->internal()->senders()) {
4608 if (sender->track() == track) {
4609 return sender;
4610 }
4611 }
4612 }
4613 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004614}
4615
Steve Anton4171afb2017-11-20 10:20:22 -08004616rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4617PeerConnection::FindSenderById(const std::string& sender_id) const {
4618 for (auto transceiver : transceivers_) {
4619 for (auto sender : transceiver->internal()->senders()) {
4620 if (sender->id() == sender_id) {
4621 return sender;
4622 }
4623 }
4624 }
4625 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004626}
4627
Steve Anton4171afb2017-11-20 10:20:22 -08004628rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4629PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4630 for (auto transceiver : transceivers_) {
4631 for (auto receiver : transceiver->internal()->receivers()) {
4632 if (receiver->id() == receiver_id) {
4633 return receiver;
4634 }
4635 }
4636 }
4637 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004638}
4639
Steve Anton4171afb2017-11-20 10:20:22 -08004640std::vector<PeerConnection::RtpSenderInfo>*
4641PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4642 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4643 media_type == cricket::MEDIA_TYPE_VIDEO);
4644 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4645 ? &remote_audio_sender_infos_
4646 : &remote_video_sender_infos_;
4647}
4648
4649std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004650 cricket::MediaType media_type) {
4651 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4652 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004653 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4654 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004655}
4656
Steve Anton4171afb2017-11-20 10:20:22 -08004657const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4658 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004659 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004660 const std::string sender_id) const {
4661 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004662 if (sender_info.stream_id == stream_id &&
4663 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004664 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004665 }
4666 }
4667 return nullptr;
4668}
4669
4670DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4671 for (const auto& channel : sctp_data_channels_) {
4672 if (channel->id() == sid) {
4673 return channel;
4674 }
4675 }
4676 return nullptr;
4677}
4678
deadbeef91dd5672016-05-18 16:55:30 -07004679bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004680 const cricket::ServerAddresses& stun_servers,
4681 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004682 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004683 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004684 // To handle both internal and externally created port allocator, we will
4685 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004686 port_allocator_flags_ = port_allocator_->flags();
4687 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4688 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4689 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004690 // If the disable-IPv6 flag was specified, we'll not override it
4691 // by experiment.
4692 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004693 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004694 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4695 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004696 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004697 }
4698
zhihuangb09b3f92017-03-07 14:40:51 -08004699 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004700 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004701 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004702 }
4703
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004704 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004705 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004706 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707 }
4708
honghaiz60347052016-05-31 18:29:12 -07004709 if (configuration.candidate_network_policy ==
4710 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004711 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004712 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004713 }
4714
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004715 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004716 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004717 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4718 }
4719
Qingsi Wanga2d60672018-04-11 16:57:45 -07004720 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004721 // No step delay is used while allocating ports.
4722 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4723 port_allocator_->set_candidate_filter(
4724 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004725 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004726
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004727 auto turn_servers_copy = turn_servers;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004728 if (tls_cert_verifier_ != nullptr) {
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004729 for (auto& turn_server : turn_servers_copy) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004730 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4731 }
4732 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733 // Call this last since it may create pooled allocator sessions using the
4734 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004735 port_allocator_->SetConfiguration(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004736 stun_servers, turn_servers_copy, configuration.ice_candidate_pool_size,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004737 configuration.prune_turn_ports, configuration.turn_customizer,
4738 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004739 return true;
4740}
4741
deadbeef91dd5672016-05-18 16:55:30 -07004742bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004743 const cricket::ServerAddresses& stun_servers,
4744 const std::vector<cricket::RelayServerConfig>& turn_servers,
4745 IceTransportsType type,
4746 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004747 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004748 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004749 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004750 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004751 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004752 // According to JSEP, after setLocalDescription, changing the candidate pool
4753 // size is not allowed, and changing the set of ICE servers will not result
4754 // in new candidates being gathered.
4755 if (local_description()) {
4756 port_allocator_->FreezeCandidatePool();
4757 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004758 // Call this last since it may create pooled allocator sessions using the
4759 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004760 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004761 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004762 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004763}
4764
Steve Antonba818672017-11-06 10:21:57 -08004765cricket::ChannelManager* PeerConnection::channel_manager() const {
4766 return factory_->channel_manager();
4767}
4768
4769MetricsObserverInterface* PeerConnection::metrics_observer() const {
4770 return uma_observer_;
4771}
4772
Elad Alon99c3fe52017-10-13 16:29:40 +02004773bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004774 std::unique_ptr<RtcEventLogOutput> output,
4775 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004776 if (!event_log_) {
4777 return false;
4778 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004779 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004780}
4781
4782void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004783 if (event_log_) {
4784 event_log_->StopLogging();
4785 }
ivoc14d5dbe2016-07-04 07:06:55 -07004786}
nisseeaabdf62017-05-05 02:23:02 -07004787
Steve Anton75737c02017-11-06 10:37:17 -08004788cricket::BaseChannel* PeerConnection::GetChannel(
4789 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004790 for (auto transceiver : transceivers_) {
4791 cricket::BaseChannel* channel = transceiver->internal()->channel();
4792 if (channel && channel->content_name() == content_name) {
4793 return channel;
4794 }
Steve Anton75737c02017-11-06 10:37:17 -08004795 }
4796 if (rtp_data_channel() &&
4797 rtp_data_channel()->content_name() == content_name) {
4798 return rtp_data_channel();
4799 }
4800 return nullptr;
4801}
4802
4803bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4804 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004805 RTC_LOG(LS_INFO)
4806 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004807 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004808 return false;
4809 }
4810 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004811 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004812 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004813 return false;
4814 }
4815
Zhi Huange830e682018-03-30 10:48:35 -07004816 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4817 if (dtls_role) {
4818 *role = *dtls_role;
4819 return true;
4820 }
4821 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004822}
4823
4824bool PeerConnection::GetSslRole(const std::string& content_name,
4825 rtc::SSLRole* role) {
4826 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004827 RTC_LOG(LS_INFO)
4828 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004829 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004830 return false;
4831 }
4832
Zhi Huange830e682018-03-30 10:48:35 -07004833 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4834 if (dtls_role) {
4835 *role = *dtls_role;
4836 return true;
4837 }
4838 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004839}
4840
Steve Antonf8470812017-12-04 10:46:21 -08004841void PeerConnection::SetSessionError(SessionError error,
4842 const std::string& error_desc) {
4843 RTC_DCHECK_RUN_ON(signaling_thread());
4844 if (error != session_error_) {
4845 session_error_ = error;
4846 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004847 }
4848}
4849
Zhi Huange830e682018-03-30 10:48:35 -07004850RTCError PeerConnection::UpdateSessionState(
4851 SdpType type,
4852 cricket::ContentSource source,
4853 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004854 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004855
4856 // If there's already a pending error then no state transition should happen.
4857 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004858 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004859
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004860 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004861 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004862 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004863 }
4864
4865 // Update the signaling state according to the specified state machine (see
4866 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004867 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004868 ChangeSignalingState(source == cricket::CS_LOCAL
4869 ? PeerConnectionInterface::kHaveLocalOffer
4870 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004871 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004872 ChangeSignalingState(source == cricket::CS_LOCAL
4873 ? PeerConnectionInterface::kHaveLocalPrAnswer
4874 : PeerConnectionInterface::kHaveRemotePrAnswer);
4875 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004876 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004877 ChangeSignalingState(PeerConnectionInterface::kStable);
4878 }
4879
4880 // Update internal objects according to the session description's media
4881 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004882 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004883 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004884 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004885 }
4886
Steve Anton8a006912017-12-04 15:25:56 -08004887 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004888}
4889
Steve Anton8a006912017-12-04 15:25:56 -08004890RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004891 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004892 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004893 const SessionDescriptionInterface* sdesc =
4894 (source == cricket::CS_LOCAL ? local_description()
4895 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004896 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004897
4898 // Push down the new SDP media section for each audio/video transceiver.
4899 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004900 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004901 FindMediaSectionForTransceiver(transceiver, sdesc);
4902 cricket::BaseChannel* channel = transceiver->internal()->channel();
4903 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004904 continue;
4905 }
4906 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004907 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004908 if (!content_desc) {
4909 continue;
4910 }
4911 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004912 bool success = (source == cricket::CS_LOCAL)
4913 ? channel->SetLocalContent(content_desc, type, &error)
4914 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004915 if (!success) {
4916 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4917 }
4918 }
4919
4920 // If using the RtpDataChannel, push down the new SDP section for it too.
4921 if (rtp_data_channel_) {
4922 const ContentInfo* data_content =
4923 cricket::GetFirstDataContent(sdesc->description());
4924 if (data_content && !data_content->rejected) {
4925 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004926 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004927 if (data_desc) {
4928 std::string error;
4929 bool success =
4930 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004931 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004932 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004933 if (!success) {
4934 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4935 std::move(error));
4936 }
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
4938 }
4939 }
Steve Antoned10bd92017-12-05 10:52:59 -08004940
Steve Anton75737c02017-11-06 10:37:17 -08004941 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4942 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4943 if (sctp_transport_ && local_description() && remote_description() &&
4944 cricket::GetFirstDataContent(local_description()->description()) &&
4945 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004946 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004947 RTC_FROM_HERE,
4948 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004949 if (!success) {
4950 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4951 "Failed to push down SCTP parameters.");
4952 }
Steve Anton75737c02017-11-06 10:37:17 -08004953 }
Steve Antoned10bd92017-12-05 10:52:59 -08004954
Steve Anton8a006912017-12-04 15:25:56 -08004955 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004956}
4957
4958bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4959 RTC_DCHECK(network_thread()->IsCurrent());
4960 RTC_DCHECK(local_description());
4961 RTC_DCHECK(remote_description());
4962 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4963 // When we support "max-message-size", that would also be pushed down here.
4964 return sctp_transport_->Start(
4965 GetSctpPort(local_description()->description()),
4966 GetSctpPort(remote_description()->description()));
4967}
4968
Steve Anton8a006912017-12-04 15:25:56 -08004969RTCError PeerConnection::PushdownTransportDescription(
4970 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004971 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004972 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004973
Zhi Huange830e682018-03-30 10:48:35 -07004974 if (source == cricket::CS_LOCAL) {
4975 const SessionDescriptionInterface* sdesc = local_description();
4976 RTC_DCHECK(sdesc);
4977 return transport_controller_->SetLocalDescription(type,
4978 sdesc->description());
4979 } else {
4980 const SessionDescriptionInterface* sdesc = remote_description();
4981 RTC_DCHECK(sdesc);
4982 return transport_controller_->SetRemoteDescription(type,
4983 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004984 }
Steve Anton75737c02017-11-06 10:37:17 -08004985}
4986
4987bool PeerConnection::GetTransportDescription(
4988 const SessionDescription* description,
4989 const std::string& content_name,
4990 cricket::TransportDescription* tdesc) {
4991 if (!description || !tdesc) {
4992 return false;
4993 }
4994 const TransportInfo* transport_info =
4995 description->GetTransportInfoByName(content_name);
4996 if (!transport_info) {
4997 return false;
4998 }
4999 *tdesc = transport_info->description;
5000 return true;
5001}
5002
Steve Anton75737c02017-11-06 10:37:17 -08005003cricket::IceConfig PeerConnection::ParseIceConfig(
5004 const PeerConnectionInterface::RTCConfiguration& config) const {
5005 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005006 switch (config.continual_gathering_policy) {
5007 case PeerConnectionInterface::GATHER_ONCE:
5008 gathering_policy = cricket::GATHER_ONCE;
5009 break;
5010 case PeerConnectionInterface::GATHER_CONTINUALLY:
5011 gathering_policy = cricket::GATHER_CONTINUALLY;
5012 break;
5013 default:
5014 RTC_NOTREACHED();
5015 gathering_policy = cricket::GATHER_ONCE;
5016 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005017
Steve Anton75737c02017-11-06 10:37:17 -08005018 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005019 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5020 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005021 ice_config.prioritize_most_likely_candidate_pairs =
5022 config.prioritize_most_likely_ice_candidate_pairs;
5023 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005024 RTCConfigurationToIceConfigOptionalInt(
5025 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005026 ice_config.continual_gathering_policy = gathering_policy;
5027 ice_config.presume_writable_when_fully_relayed =
5028 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005029 ice_config.ice_check_interval_strong_connectivity =
5030 config.ice_check_interval_strong_connectivity;
5031 ice_config.ice_check_interval_weak_connectivity =
5032 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005033 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005034 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005035 ice_config.regather_all_networks_interval_range =
5036 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005037 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005038 return ice_config;
5039}
5040
Steve Anton75737c02017-11-06 10:37:17 -08005041bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5042 std::string* track_id) {
5043 if (!local_description()) {
5044 return false;
5045 }
5046 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5047 track_id);
5048}
5049
5050bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5051 std::string* track_id) {
5052 if (!remote_description()) {
5053 return false;
5054 }
5055 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5056 track_id);
5057}
5058
5059bool PeerConnection::SendData(const cricket::SendDataParams& params,
5060 const rtc::CopyOnWriteBuffer& payload,
5061 cricket::SendDataResult* result) {
5062 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005063 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005064 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005065 return false;
5066 }
5067 return rtp_data_channel_
5068 ? rtp_data_channel_->SendData(params, payload, result)
5069 : network_thread()->Invoke<bool>(
5070 RTC_FROM_HERE,
5071 Bind(&cricket::SctpTransportInternal::SendData,
5072 sctp_transport_.get(), params, payload, result));
5073}
5074
5075bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5076 if (!rtp_data_channel_ && !sctp_transport_) {
5077 // Don't log an error here, because DataChannels are expected to call
5078 // ConnectDataChannel in this state. It's the only way to initially tell
5079 // whether or not the underlying transport is ready.
5080 return false;
5081 }
5082 if (rtp_data_channel_) {
5083 rtp_data_channel_->SignalReadyToSendData.connect(
5084 webrtc_data_channel, &DataChannel::OnChannelReady);
5085 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5086 &DataChannel::OnDataReceived);
5087 } else {
5088 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5089 &DataChannel::OnChannelReady);
5090 SignalSctpDataReceived.connect(webrtc_data_channel,
5091 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005092 SignalSctpClosingProcedureStartedRemotely.connect(
5093 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5094 SignalSctpClosingProcedureComplete.connect(
5095 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005096 }
5097 return true;
5098}
5099
5100void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5101 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005102 RTC_LOG(LS_ERROR)
5103 << "DisconnectDataChannel called when rtp_data_channel_ and "
5104 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005105 return;
5106 }
5107 if (rtp_data_channel_) {
5108 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5109 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5110 } else {
5111 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5112 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005113 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5114 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005115 }
5116}
5117
5118void PeerConnection::AddSctpDataStream(int sid) {
5119 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005120 RTC_LOG(LS_ERROR)
5121 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005122 return;
5123 }
5124 network_thread()->Invoke<void>(
5125 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5126 sctp_transport_.get(), sid));
5127}
5128
5129void PeerConnection::RemoveSctpDataStream(int sid) {
5130 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005133 return;
5134 }
5135 network_thread()->Invoke<void>(
5136 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5137 sctp_transport_.get(), sid));
5138}
5139
5140bool PeerConnection::ReadyToSendData() const {
5141 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5142 sctp_ready_to_send_data_;
5143}
5144
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005145absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005146 if (sctp_mid_ && transport_controller_) {
5147 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5148 if (dtls_transport) {
5149 return dtls_transport->transport_name();
5150 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005151 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005152 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005153 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005154}
5155
Qingsi Wang72a43a12018-02-20 16:03:18 -08005156cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5157 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005158 network_thread()->Invoke<void>(
5159 RTC_FROM_HERE,
5160 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5161 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005162 return candidate_states_list;
5163}
5164
Steve Anton5dfde182018-02-06 10:34:40 -08005165std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5166 const {
5167 std::map<std::string, std::string> transport_names_by_mid;
5168 for (auto transceiver : transceivers_) {
5169 cricket::BaseChannel* channel = transceiver->internal()->channel();
5170 if (channel) {
5171 transport_names_by_mid[channel->content_name()] =
5172 channel->transport_name();
5173 }
Steve Anton75737c02017-11-06 10:37:17 -08005174 }
Steve Anton5dfde182018-02-06 10:34:40 -08005175 if (rtp_data_channel_) {
5176 transport_names_by_mid[rtp_data_channel_->content_name()] =
5177 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005178 }
5179 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005180 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005181 RTC_DCHECK(transport_name);
5182 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005183 }
Steve Anton5dfde182018-02-06 10:34:40 -08005184 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005185}
5186
Steve Anton5dfde182018-02-06 10:34:40 -08005187std::map<std::string, cricket::TransportStats>
5188PeerConnection::GetTransportStatsByNames(
5189 const std::set<std::string>& transport_names) {
5190 if (!network_thread()->IsCurrent()) {
5191 return network_thread()
5192 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5193 RTC_FROM_HERE,
5194 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005195 }
Steve Anton5dfde182018-02-06 10:34:40 -08005196 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5197 for (const std::string& transport_name : transport_names) {
5198 cricket::TransportStats transport_stats;
5199 bool success =
5200 transport_controller_->GetStats(transport_name, &transport_stats);
5201 if (success) {
5202 transport_stats_by_name[transport_name] = std::move(transport_stats);
5203 } else {
5204 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5205 << transport_name;
5206 }
5207 }
5208 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005209}
5210
5211bool PeerConnection::GetLocalCertificate(
5212 const std::string& transport_name,
5213 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005214 if (!certificate) {
5215 return false;
5216 }
5217 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5218 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005219}
5220
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005221std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005222 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005223 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005224}
5225
5226cricket::DataChannelType PeerConnection::data_channel_type() const {
5227 return data_channel_type_;
5228}
5229
5230bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5231 return pending_ice_restarts_.find(content_name) !=
5232 pending_ice_restarts_.end();
5233}
5234
Steve Anton75737c02017-11-06 10:37:17 -08005235bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5236 return transport_controller_->NeedsIceRestart(content_name);
5237}
5238
5239void PeerConnection::OnCertificateReady(
5240 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5241 transport_controller_->SetLocalCertificate(certificate);
5242}
5243
5244void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005245 SetSessionError(SessionError::kTransport,
5246 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005247}
5248
5249void PeerConnection::OnTransportControllerConnectionState(
5250 cricket::IceConnectionState state) {
5251 switch (state) {
5252 case cricket::kIceConnectionConnecting:
5253 // If the current state is Connected or Completed, then there were
5254 // writable channels but now there are not, so the next state must
5255 // be Disconnected.
5256 // kIceConnectionConnecting is currently used as the default,
5257 // un-connected state by the TransportController, so its only use is
5258 // detecting disconnections.
5259 if (ice_connection_state_ ==
5260 PeerConnectionInterface::kIceConnectionConnected ||
5261 ice_connection_state_ ==
5262 PeerConnectionInterface::kIceConnectionCompleted) {
5263 SetIceConnectionState(
5264 PeerConnectionInterface::kIceConnectionDisconnected);
5265 }
5266 break;
5267 case cricket::kIceConnectionFailed:
5268 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5269 break;
5270 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005271 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005272 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005274 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005275 break;
5276 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005277 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005278 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005279 if (ice_connection_state_ !=
5280 PeerConnectionInterface::kIceConnectionConnected) {
5281 // If jumping directly from "checking" to "connected",
5282 // signal "connected" first.
5283 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5284 }
5285 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005286 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005287 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005288 break;
5289 default:
5290 RTC_NOTREACHED();
5291 }
5292}
5293
5294void PeerConnection::OnTransportControllerCandidatesGathered(
5295 const std::string& transport_name,
5296 const cricket::Candidates& candidates) {
5297 RTC_DCHECK(signaling_thread()->IsCurrent());
5298 int sdp_mline_index;
5299 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005300 RTC_LOG(LS_ERROR)
5301 << "OnTransportControllerCandidatesGathered: content name "
5302 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005303 return;
5304 }
5305
5306 for (cricket::Candidates::const_iterator citer = candidates.begin();
5307 citer != candidates.end(); ++citer) {
5308 // Use transport_name as the candidate media id.
5309 std::unique_ptr<JsepIceCandidate> candidate(
5310 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5311 if (local_description()) {
5312 mutable_local_description()->AddCandidate(candidate.get());
5313 }
5314 OnIceCandidate(std::move(candidate));
5315 }
5316}
5317
5318void PeerConnection::OnTransportControllerCandidatesRemoved(
5319 const std::vector<cricket::Candidate>& candidates) {
5320 RTC_DCHECK(signaling_thread()->IsCurrent());
5321 // Sanity check.
5322 for (const cricket::Candidate& candidate : candidates) {
5323 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005324 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005325 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005326 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005327 return;
5328 }
5329 }
5330
5331 if (local_description()) {
5332 mutable_local_description()->RemoveCandidates(candidates);
5333 }
5334 OnIceCandidatesRemoved(candidates);
5335}
5336
5337void PeerConnection::OnTransportControllerDtlsHandshakeError(
5338 rtc::SSLHandshakeError error) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005339 RTC_HISTOGRAM_ENUMERATION(
5340 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5341 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005342}
5343
Steve Antoned10bd92017-12-05 10:52:59 -08005344void PeerConnection::EnableSending() {
5345 for (auto transceiver : transceivers_) {
5346 cricket::BaseChannel* channel = transceiver->internal()->channel();
5347 if (channel && !channel->enabled()) {
5348 channel->Enable(true);
5349 }
Steve Anton75737c02017-11-06 10:37:17 -08005350 }
5351
Steve Anton4171afb2017-11-20 10:20:22 -08005352 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005353 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005354 }
Steve Anton75737c02017-11-06 10:37:17 -08005355}
5356
5357// Returns the media index for a local ice candidate given the content name.
5358bool PeerConnection::GetLocalCandidateMediaIndex(
5359 const std::string& content_name,
5360 int* sdp_mline_index) {
5361 if (!local_description() || !sdp_mline_index) {
5362 return false;
5363 }
5364
5365 bool content_found = false;
5366 const ContentInfos& contents = local_description()->description()->contents();
5367 for (size_t index = 0; index < contents.size(); ++index) {
5368 if (contents[index].name == content_name) {
5369 *sdp_mline_index = static_cast<int>(index);
5370 content_found = true;
5371 break;
5372 }
5373 }
5374 return content_found;
5375}
5376
5377bool PeerConnection::UseCandidatesInSessionDescription(
5378 const SessionDescriptionInterface* remote_desc) {
5379 if (!remote_desc) {
5380 return true;
5381 }
5382 bool ret = true;
5383
5384 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5385 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5386 for (size_t n = 0; n < candidates->count(); ++n) {
5387 const IceCandidateInterface* candidate = candidates->at(n);
5388 bool valid = false;
5389 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5390 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005391 RTC_LOG(LS_INFO)
5392 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005393 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005394 }
5395 continue;
5396 }
5397 ret = UseCandidate(candidate);
5398 if (!ret) {
5399 break;
5400 }
5401 }
5402 }
5403 return ret;
5404}
5405
5406bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5407 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5408 size_t remote_content_size =
5409 remote_description()->description()->contents().size();
5410 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005411 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005412 return false;
5413 }
5414
5415 cricket::ContentInfo content =
5416 remote_description()->description()->contents()[mediacontent_index];
5417 std::vector<cricket::Candidate> candidates;
5418 candidates.push_back(candidate->candidate());
5419 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005420 RTCError error =
5421 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005422 if (error.ok()) {
5423 // Candidates successfully submitted for checking.
5424 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5425 ice_connection_state_ ==
5426 PeerConnectionInterface::kIceConnectionDisconnected) {
5427 // If state is New, then the session has just gotten its first remote ICE
5428 // candidates, so go to Checking.
5429 // If state is Disconnected, the session is re-using old candidates or
5430 // receiving additional ones, so go to Checking.
5431 // If state is Connected, stay Connected.
5432 // TODO(bemasc): If state is Connected, and the new candidates are for a
5433 // newly added transport, then the state actually _should_ move to
5434 // checking. Add a way to distinguish that case.
5435 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5436 }
5437 // TODO(bemasc): If state is Completed, go back to Connected.
5438 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005439 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
5441 return true;
5442}
5443
5444void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005445 // Destroy video channel first since it may have a pointer to the
5446 // voice channel.
5447 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005448 if (!video_info || video_info->rejected) {
5449 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
5451
Steve Anton6fec8802017-12-04 10:37:29 -08005452 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5453 if (!audio_info || audio_info->rejected) {
5454 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456
5457 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5458 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005459 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005460 }
5461}
5462
Steve Antondcc3c022017-12-22 16:02:54 -08005463RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5464 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005465 const cricket::ContentGroup* bundle_group = nullptr;
5466 if (configuration_.bundle_policy ==
5467 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005468 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005469 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005470 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5471 "max-bundle configured but session description "
5472 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005473 }
5474 }
Steve Antondcc3c022017-12-22 16:02:54 -08005475 return std::move(bundle_group);
5476}
5477
5478RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005479 // Creating the media channels. Transports should already have been created
5480 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005481 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005482 if (voice && !voice->rejected &&
5483 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005484 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005485 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005486 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5487 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005488 }
5489 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5490 }
5491
Steve Antondcc3c022017-12-22 16:02:54 -08005492 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005493 if (video && !video->rejected &&
5494 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005495 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005496 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005497 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5498 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005499 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005501 }
5502
Steve Antondcc3c022017-12-22 16:02:54 -08005503 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005504 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5505 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005506 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005507 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5508 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005509 }
5510 }
5511
Steve Anton8a006912017-12-04 15:25:56 -08005512 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005513}
5514
Steve Anton4171afb2017-11-20 10:20:22 -08005515// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005517 const std::string& mid) {
5518 RtpTransportInternal* rtp_transport =
5519 transport_controller_->GetRtpTransport(mid);
5520 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005521 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005522 call_.get(), configuration_.media_config, rtp_transport,
5523 signaling_thread(), mid, SrtpRequired(),
5524 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005525 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005526 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005527 }
Steve Anton75737c02017-11-06 10:37:17 -08005528 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5529 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005530 voice_channel->SignalSentPacket.connect(this,
5531 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005532 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005533 if (uma_observer_) {
5534 voice_channel->SetMetricsObserver(uma_observer_);
5535 }
Steve Anton4171afb2017-11-20 10:20:22 -08005536
Steve Antoneda6ccd2017-12-04 10:21:55 -08005537 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005538}
5539
Steve Anton4171afb2017-11-20 10:20:22 -08005540// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005542 const std::string& mid) {
5543 RtpTransportInternal* rtp_transport =
5544 transport_controller_->GetRtpTransport(mid);
5545 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005546 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005547 call_.get(), configuration_.media_config, rtp_transport,
5548 signaling_thread(), mid, SrtpRequired(),
5549 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005550 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005551 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005552 }
Steve Anton75737c02017-11-06 10:37:17 -08005553 video_channel->SignalDtlsSrtpSetupFailure.connect(
5554 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005555 video_channel->SignalSentPacket.connect(this,
5556 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005557 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005558 if (uma_observer_) {
5559 video_channel->SetMetricsObserver(uma_observer_);
5560 }
Steve Anton4171afb2017-11-20 10:20:22 -08005561
Steve Antoneda6ccd2017-12-04 10:21:55 -08005562 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005563}
5564
Zhi Huange830e682018-03-30 10:48:35 -07005565bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005566 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5567 if (sctp) {
5568 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005569 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005570 << "Trying to create SCTP transport, but didn't compile with "
5571 "SCTP support (HAVE_SCTP)";
5572 return false;
5573 }
5574 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005575 RTC_FROM_HERE,
5576 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005577 return false;
5578 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005579 for (const auto& channel : sctp_data_channels_) {
5580 channel->OnTransportChannelCreated();
5581 }
Steve Anton75737c02017-11-06 10:37:17 -08005582 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005583 RtpTransportInternal* rtp_transport =
5584 transport_controller_->GetRtpTransport(mid);
5585 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005586 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005587 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5588 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005589 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005590 return false;
5591 }
Steve Anton75737c02017-11-06 10:37:17 -08005592 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5593 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5594 rtp_data_channel_->SignalSentPacket.connect(
5595 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005596 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005597 if (uma_observer_) {
5598 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5599 }
Steve Anton75737c02017-11-06 10:37:17 -08005600 }
5601
Steve Anton75737c02017-11-06 10:37:17 -08005602 return true;
5603}
5604
5605Call::Stats PeerConnection::GetCallStats() {
5606 if (!worker_thread()->IsCurrent()) {
5607 return worker_thread()->Invoke<Call::Stats>(
5608 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5609 }
5610 if (call_) {
5611 return call_->GetStats();
5612 } else {
5613 return Call::Stats();
5614 }
5615}
5616
Zhi Huange830e682018-03-30 10:48:35 -07005617bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005618 RTC_DCHECK(network_thread()->IsCurrent());
5619 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005620 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005621 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005622 RTC_DCHECK(dtls_transport);
5623 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005624 RTC_DCHECK(sctp_transport_);
5625 sctp_invoker_.reset(new rtc::AsyncInvoker());
5626 sctp_transport_->SignalReadyToSendData.connect(
5627 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5628 sctp_transport_->SignalDataReceived.connect(
5629 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005630 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5631 // another thread. Would be nice if there was a helper class similar to
5632 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5633 // code.
5634 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5635 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5636 sctp_transport_->SignalClosingProcedureComplete.connect(
5637 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005638 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005639 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005640 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005641}
5642
5643void PeerConnection::DestroySctpTransport_n() {
5644 RTC_DCHECK(network_thread()->IsCurrent());
5645 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005646 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005647 sctp_invoker_.reset(nullptr);
5648 sctp_ready_to_send_data_ = false;
5649}
5650
5651void PeerConnection::OnSctpTransportReadyToSendData_n() {
5652 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5653 RTC_DCHECK(network_thread()->IsCurrent());
5654 // Note: Cannot use rtc::Bind here because it will grab a reference to
5655 // PeerConnection and potentially cause PeerConnection to live longer than
5656 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5657 // be destroyed before PeerConnection is destroyed, and at that point all
5658 // pending tasks will be cleared.
5659 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5660 OnSctpTransportReadyToSendData_s(true);
5661 });
5662}
5663
5664void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5665 RTC_DCHECK(signaling_thread()->IsCurrent());
5666 sctp_ready_to_send_data_ = ready;
5667 SignalSctpReadyToSendData(ready);
5668}
5669
5670void PeerConnection::OnSctpTransportDataReceived_n(
5671 const cricket::ReceiveDataParams& params,
5672 const rtc::CopyOnWriteBuffer& payload) {
5673 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5674 RTC_DCHECK(network_thread()->IsCurrent());
5675 // Note: Cannot use rtc::Bind here because it will grab a reference to
5676 // PeerConnection and potentially cause PeerConnection to live longer than
5677 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5678 // be destroyed before PeerConnection is destroyed, and at that point all
5679 // pending tasks will be cleared.
5680 sctp_invoker_->AsyncInvoke<void>(
5681 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5682 OnSctpTransportDataReceived_s(params, payload);
5683 });
5684}
5685
5686void PeerConnection::OnSctpTransportDataReceived_s(
5687 const cricket::ReceiveDataParams& params,
5688 const rtc::CopyOnWriteBuffer& payload) {
5689 RTC_DCHECK(signaling_thread()->IsCurrent());
5690 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5691 // Received OPEN message; parse and signal that a new data channel should
5692 // be created.
5693 std::string label;
5694 InternalDataChannelInit config;
5695 config.id = params.ssrc;
5696 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005697 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5698 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005699 return;
5700 }
5701 config.open_handshake_role = InternalDataChannelInit::kAcker;
5702 OnDataChannelOpenMessage(label, config);
5703 } else {
5704 // Otherwise just forward the signal.
5705 SignalSctpDataReceived(params, payload);
5706 }
5707}
5708
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005709void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005710 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5711 RTC_DCHECK(network_thread()->IsCurrent());
5712 sctp_invoker_->AsyncInvoke<void>(
5713 RTC_FROM_HERE, signaling_thread(),
5714 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005715 &SignalSctpClosingProcedureStartedRemotely, sid));
5716}
5717
5718void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5719 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5720 RTC_DCHECK(network_thread()->IsCurrent());
5721 sctp_invoker_->AsyncInvoke<void>(
5722 RTC_FROM_HERE, signaling_thread(),
5723 rtc::Bind(&sigslot::signal1<int>::operator(),
5724 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005725}
5726
5727// Returns false if bundle is enabled and rtcp_mux is disabled.
5728bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5729 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5730 if (!bundle_enabled)
5731 return true;
5732
5733 const cricket::ContentGroup* bundle_group =
5734 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5735 RTC_DCHECK(bundle_group != NULL);
5736
5737 const cricket::ContentInfos& contents = desc->contents();
5738 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5739 citer != contents.end(); ++citer) {
5740 const cricket::ContentInfo* content = (&*citer);
5741 RTC_DCHECK(content != NULL);
5742 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005743 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005744 if (!HasRtcpMuxEnabled(content))
5745 return false;
5746 }
5747 }
5748 // RTCP-MUX is enabled in all the contents.
5749 return true;
5750}
5751
5752bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005753 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005754}
5755
Steve Anton8a006912017-12-04 15:25:56 -08005756RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005757 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005758 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005759 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005760 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
5762
5763 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005764 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766
Steve Anton3828c062017-12-06 10:34:51 -08005767 SdpType type = sdesc->GetType();
5768 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5769 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005770 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005771 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005772 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005773 }
5774
5775 // Verify crypto settings.
5776 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005777 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5778 dtls_enabled_) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005779 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005780 if (!crypto_error.ok()) {
5781 return crypto_error;
5782 }
Steve Anton75737c02017-11-06 10:37:17 -08005783 }
5784
5785 // Verify ice-ufrag and ice-pwd.
5786 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5788 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005789 }
5790
5791 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5793 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795
5796 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5797 // m-lines that do not rtcp-mux enabled.
5798
5799 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005800 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005801 // With an answer we want to compare the new answer session description with
5802 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005803 const cricket::SessionDescription* offer_desc =
5804 (source == cricket::CS_LOCAL) ? remote_description()->description()
5805 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5807 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5808 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5810 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005811 }
5812 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005813 // The re-offers should respect the order of m= sections in current
5814 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005815 // With a re-offer, either the current local or current remote descriptions
5816 // could be the most up to date, so we would like to check against both of
5817 // them if they exist. It could be the case that one of them has a 0 port
5818 // for a media section, but the other does not. This is important to check
5819 // against in the case that we are recycling an m= section.
5820 const cricket::SessionDescription* current_desc = nullptr;
5821 const cricket::SessionDescription* secondary_current_desc = nullptr;
5822 if (local_description()) {
5823 current_desc = local_description()->description();
5824 if (remote_description()) {
5825 secondary_current_desc = remote_description()->description();
5826 }
5827 } else if (remote_description()) {
5828 current_desc = remote_description()->description();
5829 }
Steve Anton75737c02017-11-06 10:37:17 -08005830 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005831 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5832 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5834 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005835 }
5836 }
5837
Steve Antonba42e992018-04-09 14:10:01 -07005838 if (IsUnifiedPlan()) {
5839 // Ensure that each audio and video media section has at most one
5840 // "StreamParams". This will return an error if receiving a session
5841 // description from a "Plan B" endpoint which adds multiple tracks of the
5842 // same type. With Unified Plan, there can only be at most one track per
5843 // media section.
5844 for (const ContentInfo& content : sdesc->description()->contents()) {
5845 const MediaContentDescription& desc = *content.description;
5846 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5847 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5848 desc.streams().size() > 1u) {
5849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5850 "Media section has more than one track specified "
5851 "with a=ssrc lines which is not supported with "
5852 "Unified Plan.");
5853 }
5854 }
5855 }
5856
Steve Anton8a006912017-12-04 15:25:56 -08005857 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005858}
5859
Steve Anton3828c062017-12-06 10:34:51 -08005860bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005861 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005862 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005863 return (state == PeerConnectionInterface::kStable) ||
5864 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005865 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005866 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005867 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5868 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5869 }
5870}
5871
Steve Anton3828c062017-12-06 10:34:51 -08005872bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005873 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005874 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005875 return (state == PeerConnectionInterface::kStable) ||
5876 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005877 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005878 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005879 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5880 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5881 }
5882}
5883
Steve Antonf8470812017-12-04 10:46:21 -08005884const char* PeerConnection::SessionErrorToString(SessionError error) const {
5885 switch (error) {
5886 case SessionError::kNone:
5887 return "ERROR_NONE";
5888 case SessionError::kContent:
5889 return "ERROR_CONTENT";
5890 case SessionError::kTransport:
5891 return "ERROR_TRANSPORT";
5892 }
5893 RTC_NOTREACHED();
5894 return "";
5895}
5896
Steve Anton75737c02017-11-06 10:37:17 -08005897std::string PeerConnection::GetSessionErrorMsg() {
5898 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005899 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5900 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005901 return desc.str();
5902}
5903
Steve Anton8e20f172018-03-06 10:55:04 -08005904void PeerConnection::ReportSdpFormatReceived(
5905 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005906 int num_audio_mlines = 0;
5907 int num_video_mlines = 0;
5908 int num_audio_tracks = 0;
5909 int num_video_tracks = 0;
5910 for (const ContentInfo& content : remote_offer.description()->contents()) {
5911 cricket::MediaType media_type = content.media_description()->type();
5912 int num_tracks = std::max(
5913 1, static_cast<int>(content.media_description()->streams().size()));
5914 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5915 num_audio_mlines += 1;
5916 num_audio_tracks += num_tracks;
5917 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5918 num_video_mlines += 1;
5919 num_video_tracks += num_tracks;
5920 }
5921 }
5922 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5923 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5924 format = kSdpFormatReceivedComplexUnifiedPlan;
5925 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5926 format = kSdpFormatReceivedComplexPlanB;
5927 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5928 format = kSdpFormatReceivedSimple;
5929 }
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005930 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5931 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005932}
5933
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005934void PeerConnection::NoteUsageEvent(UsageEvent event) {
5935 RTC_DCHECK_RUN_ON(signaling_thread());
5936 usage_event_accumulator_ |= static_cast<int>(event);
5937}
5938
5939void PeerConnection::ReportUsagePattern() const {
5940 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005941 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5942 usage_event_accumulator_,
5943 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005944}
5945
Steve Anton0ffaaa22018-02-23 10:31:30 -08005946void PeerConnection::ReportNegotiatedSdpSemantics(
5947 const SessionDescriptionInterface& answer) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005948 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005949 switch (answer.description()->msid_signaling()) {
5950 case 0:
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005951 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005952 break;
5953 case cricket::kMsidSignalingMediaSection:
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005954 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005955 break;
5956 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005957 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005958 break;
5959 case cricket::kMsidSignalingMediaSection |
5960 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005961 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005962 break;
5963 default:
5964 RTC_NOTREACHED();
5965 }
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07005966 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5967 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005968}
5969
Steve Anton75737c02017-11-06 10:37:17 -08005970// We need to check the local/remote description for the Transport instead of
5971// the session, because a new Transport added during renegotiation may have
5972// them unset while the session has them set from the previous negotiation.
5973// Not doing so may trigger the auto generation of transport description and
5974// mess up DTLS identity information, ICE credential, etc.
5975bool PeerConnection::ReadyToUseRemoteCandidate(
5976 const IceCandidateInterface* candidate,
5977 const SessionDescriptionInterface* remote_desc,
5978 bool* valid) {
5979 *valid = true;
5980
5981 const SessionDescriptionInterface* current_remote_desc =
5982 remote_desc ? remote_desc : remote_description();
5983
5984 if (!current_remote_desc) {
5985 return false;
5986 }
5987
5988 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5989 size_t remote_content_size =
5990 current_remote_desc->description()->contents().size();
5991 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005992 RTC_LOG(LS_ERROR)
5993 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5994 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005995
5996 *valid = false;
5997 return false;
5998 }
5999
6000 cricket::ContentInfo content =
6001 current_remote_desc->description()->contents()[mediacontent_index];
6002
6003 const std::string transport_name = GetTransportName(content.name);
6004 if (transport_name.empty()) {
6005 return false;
6006 }
Zhi Huange830e682018-03-30 10:48:35 -07006007 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006008}
6009
6010bool PeerConnection::SrtpRequired() const {
6011 return dtls_enabled_ ||
6012 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6013}
6014
6015void PeerConnection::OnTransportControllerGatheringState(
6016 cricket::IceGatheringState state) {
6017 RTC_DCHECK(signaling_thread()->IsCurrent());
6018 if (state == cricket::kIceGatheringGathering) {
6019 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6020 } else if (state == cricket::kIceGatheringComplete) {
6021 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6022 }
6023}
6024
6025void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006026 std::map<std::string, std::set<cricket::MediaType>>
6027 media_types_by_transport_name;
6028 for (auto transceiver : transceivers_) {
6029 if (transceiver->internal()->channel()) {
6030 const std::string& transport_name =
6031 transceiver->internal()->channel()->transport_name();
6032 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006033 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006034 }
Steve Anton75737c02017-11-06 10:37:17 -08006035 }
6036 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6038 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
Zhi Huange830e682018-03-30 10:48:35 -07006040
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006041 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006042 if (transport_name) {
6043 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006044 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006045 }
Zhi Huange830e682018-03-30 10:48:35 -07006046
Steve Antonc7b964c2018-02-01 14:39:45 -08006047 for (const auto& entry : media_types_by_transport_name) {
6048 const std::string& transport_name = entry.first;
6049 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006050 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006051 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006052 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006053 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006054 }
6055 }
6056}
6057// Walk through the ConnectionInfos to gather best connection usage
6058// for IPv4 and IPv6.
6059void PeerConnection::ReportBestConnectionState(
6060 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 for (const cricket::TransportChannelStats& channel_stats :
6062 stats.channel_stats) {
6063 for (const cricket::ConnectionInfo& connection_info :
6064 channel_stats.connection_infos) {
6065 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006066 continue;
6067 }
6068
Steve Antonc7b964c2018-02-01 14:39:45 -08006069 const cricket::Candidate& local = connection_info.local_candidate;
6070 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006071
6072 // Increment the counter for IceCandidatePairType.
6073 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6074 (local.type() == RELAY_PORT_TYPE &&
6075 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006076 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6077 GetIceCandidatePairCounter(local, remote),
6078 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006079 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006080 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6081 GetIceCandidatePairCounter(local, remote),
6082 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006083 } else {
6084 RTC_CHECK(0);
6085 }
Steve Anton75737c02017-11-06 10:37:17 -08006086
6087 // Increment the counter for IP type.
6088 if (local.address().family() == AF_INET) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006089 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6090 kBestConnections_IPv4,
6091 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006092 } else if (local.address().family() == AF_INET6) {
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006093 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6094 kBestConnections_IPv6,
6095 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006096 } else {
6097 RTC_CHECK(0);
6098 }
6099
6100 return;
6101 }
6102 }
6103}
6104
6105void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006106 const cricket::TransportStats& stats,
6107 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006108 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6109 return;
6110 }
6111
6112 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6113 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6114 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6115 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6116 return;
6117 }
6118
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006119 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6120 for (cricket::MediaType media_type : media_types) {
6121 switch (media_type) {
6122 case cricket::MEDIA_TYPE_AUDIO:
6123 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6124 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6125 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6126 break;
6127 case cricket::MEDIA_TYPE_VIDEO:
6128 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6129 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6130 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6131 break;
6132 case cricket::MEDIA_TYPE_DATA:
6133 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6134 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6135 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6136 break;
6137 default:
6138 RTC_NOTREACHED();
6139 continue;
6140 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006141 }
Qingsi Wang1a2cc0a2018-07-10 15:17:12 -07006142 }
6143
6144 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6145 for (cricket::MediaType media_type : media_types) {
6146 switch (media_type) {
6147 case cricket::MEDIA_TYPE_AUDIO:
6148 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6149 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6150 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6151 break;
6152 case cricket::MEDIA_TYPE_VIDEO:
6153 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6154 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6155 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6156 break;
6157 case cricket::MEDIA_TYPE_DATA:
6158 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6159 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6160 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6161 break;
6162 default:
6163 RTC_NOTREACHED();
6164 continue;
6165 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006166 }
Steve Anton75737c02017-11-06 10:37:17 -08006167 }
6168}
6169
6170void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6171 RTC_DCHECK(worker_thread()->IsCurrent());
6172 RTC_DCHECK(call_);
6173 call_->OnSentPacket(sent_packet);
6174}
6175
6176const std::string PeerConnection::GetTransportName(
6177 const std::string& content_name) {
6178 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006179 if (channel) {
6180 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
Steve Anton6fec8802017-12-04 10:37:29 -08006182 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006183 RTC_DCHECK(sctp_mid_);
6184 if (content_name == *sctp_mid_) {
6185 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006186 }
6187 }
6188 // Return an empty string if failed to retrieve the transport name.
6189 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006190}
6191
Steve Anton6fec8802017-12-04 10:37:29 -08006192void PeerConnection::DestroyTransceiverChannel(
6193 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6194 transceiver) {
6195 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006196
Steve Anton6fec8802017-12-04 10:37:29 -08006197 cricket::BaseChannel* channel = transceiver->internal()->channel();
6198 if (channel) {
6199 transceiver->internal()->SetChannel(nullptr);
6200 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006201 }
6202}
6203
6204void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006205 if (rtp_data_channel_) {
6206 OnDataChannelDestroyed();
6207 DestroyBaseChannel(rtp_data_channel_);
6208 rtp_data_channel_ = nullptr;
6209 }
6210
6211 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6212 // grab a reference to this PeerConnection. If this is called from the
6213 // PeerConnection destructor, the RefCountedObject vtable will have already
6214 // been destroyed (since it is a subclass of PeerConnection) and using
6215 // rtc::Bind will cause "Pure virtual function called" error to appear.
6216
6217 if (sctp_transport_) {
6218 OnDataChannelDestroyed();
6219 network_thread()->Invoke<void>(RTC_FROM_HERE,
6220 [this] { DestroySctpTransport_n(); });
6221 }
6222}
6223
6224void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6225 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006226 switch (channel->media_type()) {
6227 case cricket::MEDIA_TYPE_AUDIO:
6228 channel_manager()->DestroyVoiceChannel(
6229 static_cast<cricket::VoiceChannel*>(channel));
6230 break;
6231 case cricket::MEDIA_TYPE_VIDEO:
6232 channel_manager()->DestroyVideoChannel(
6233 static_cast<cricket::VideoChannel*>(channel));
6234 break;
6235 case cricket::MEDIA_TYPE_DATA:
6236 channel_manager()->DestroyRtpDataChannel(
6237 static_cast<cricket::RtpDataChannel*>(channel));
6238 break;
6239 default:
6240 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6241 break;
6242 }
Zhi Huange830e682018-03-30 10:48:35 -07006243}
Steve Anton6fec8802017-12-04 10:37:29 -08006244
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006245bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006246 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006247 RtpTransportInternal* rtp_transport,
6248 cricket::DtlsTransportInternal* dtls_transport) {
6249 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006250 auto base_channel = GetChannel(mid);
6251 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006252 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006253 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006254 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006255 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006256 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006257 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006258}
6259
Harald Alvestrand89061872018-01-02 14:08:34 +01006260void PeerConnection::ClearStatsCache() {
6261 if (stats_collector_) {
6262 stats_collector_->ClearCachedStatsReport();
6263 }
6264}
6265
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006266} // namespace webrtc