blob: 7f7cebd9fd9a49c7eb506f75f82164d3573299bd [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"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010021#include "absl/strings/match.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/jsepicecandidate.h"
23#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020026#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080028#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020029#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "logging/rtc_event_log/rtc_event_log.h"
31#include "media/sctp/sctptransport.h"
32#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080033#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "pc/channelmanager.h"
35#include "pc/dtmfsender.h"
36#include "pc/mediastream.h"
37#include "pc/mediastreamobserver.h"
38#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080039#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/rtpreceiver.h"
41#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080042#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080043#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "pc/streamcollection.h"
45#include "pc/videocapturertracksource.h"
46#include "pc/videotrack.h"
47#include "rtc_base/bind.h"
48#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010050#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020052#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Amit Hilbuchc63ddb22019-01-02 10:13:58 -080062using cricket::SessionDescription;
63using cricket::SimulcastLayerList;
Steve Anton75737c02017-11-06 10:37:17 -080064using cricket::TransportInfo;
65
66using cricket::LOCAL_PORT_TYPE;
67using cricket::STUN_PORT_TYPE;
68using cricket::RELAY_PORT_TYPE;
69using cricket::PRFLX_PORT_TYPE;
70
Steve Antonba818672017-11-06 10:21:57 -080071namespace webrtc {
72
Steve Anton75737c02017-11-06 10:37:17 -080073// Error messages
74const char kBundleWithoutRtcpMux[] =
75 "rtcp-mux must be enabled when BUNDLE "
76 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080077const char kInvalidCandidates[] = "Description contains invalid candidates.";
78const char kInvalidSdp[] = "Invalid session description.";
79const char kMlineMismatchInAnswer[] =
80 "The order of m-lines in answer doesn't match order in offer. Rejecting "
81 "answer.";
82const char kMlineMismatchInSubsequentOffer[] =
83 "The order of m-lines in subsequent offer doesn't match order from "
84 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080085const char kSdpWithoutDtlsFingerprint[] =
86 "Called with SDP without DTLS fingerprint.";
87const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
88const char kSdpWithoutIceUfragPwd[] =
89 "Called with SDP without ice-ufrag and ice-pwd.";
90const char kSessionError[] = "Session error code: ";
91const char kSessionErrorDesc[] = "Session error description: ";
92const char kDtlsSrtpSetupFailureRtp[] =
93 "Couldn't set up DTLS-SRTP on RTP channel.";
94const char kDtlsSrtpSetupFailureRtcp[] =
95 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Steve Anton75737c02017-11-06 10:37:17 -080097namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000098
Seth Hampson845e8782018-03-02 11:34:10 -080099static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -0800100static const char kDefaultAudioSenderId[] = "defaulta0";
101static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700102
zhihuang8f65cdf2016-05-06 18:40:30 -0700103// The length of RTCP CNAMEs.
104static const int kRtcpCnameLength = 16;
105
Steve Antonad182762018-09-05 20:22:40 +0000106enum {
107 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
108 MSG_SET_SESSIONDESCRIPTION_FAILED,
109 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
110 MSG_GETSTATS,
111 MSG_FREE_DATACHANNELS,
112 MSG_REPORT_USAGE_PATTERN,
113};
114
Harald Alvestrand19793842018-06-25 12:03:50 +0200115static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
116
Steve Antonad182762018-09-05 20:22:40 +0000117struct SetSessionDescriptionMsg : public rtc::MessageData {
118 explicit SetSessionDescriptionMsg(
119 webrtc::SetSessionDescriptionObserver* observer)
120 : observer(observer) {}
121
122 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
123 RTCError error;
124};
125
126struct CreateSessionDescriptionMsg : public rtc::MessageData {
127 explicit CreateSessionDescriptionMsg(
128 webrtc::CreateSessionDescriptionObserver* observer)
129 : observer(observer) {}
130
131 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
132 RTCError error;
133};
134
135struct GetStatsMsg : public rtc::MessageData {
136 GetStatsMsg(webrtc::StatsObserver* observer,
137 webrtc::MediaStreamTrackInterface* track)
138 : observer(observer), track(track) {}
139 rtc::scoped_refptr<webrtc::StatsObserver> observer;
140 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
141};
142
deadbeefab9b2d12015-10-14 11:33:11 -0700143// Check if we can send |new_stream| on a PeerConnection.
144bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
145 webrtc::MediaStreamInterface* new_stream) {
146 if (!new_stream || !current_streams) {
147 return false;
148 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700149 if (current_streams->find(new_stream->id()) != nullptr) {
150 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100151 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700152 return false;
153 }
154 return true;
155}
156
deadbeef5e97fb52015-10-15 12:49:08 -0700157// If the direction is "recvonly" or "inactive", treat the description
158// as containing no streams.
159// See: https://code.google.com/p/webrtc/issues/detail?id=5054
160std::vector<cricket::StreamParams> GetActiveStreams(
161 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800162 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700163 ? desc->streams()
164 : std::vector<cricket::StreamParams>();
165}
166
deadbeefab9b2d12015-10-14 11:33:11 -0700167bool IsValidOfferToReceiveMedia(int value) {
168 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
169 return (value >= Options::kUndefined) &&
170 (value <= Options::kMaxOfferToReceiveMedia);
171}
172
zhihuang1c378ed2017-08-17 14:10:50 -0700173// Add options to |[audio/video]_media_description_options| from |senders|.
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800174void AddPlanBRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700175 const std::vector<rtc::scoped_refptr<
176 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700177 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200178 cricket::MediaDescriptionOptions* video_media_description_options,
179 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700180 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700181 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
182 if (audio_media_description_options) {
183 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 } else {
187 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
188 if (video_media_description_options) {
189 video_media_description_options->AddVideoSender(
Amit Hilbuchc63ddb22019-01-02 10:13:58 -0800190 sender->id(), sender->internal()->stream_ids(), {},
191 SimulcastLayerList(), num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700192 }
193 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700194 }
zhihuang1c378ed2017-08-17 14:10:50 -0700195}
olka3c747662017-08-17 06:50:32 -0700196
zhihuang1c378ed2017-08-17 14:10:50 -0700197// Add options to |session_options| from |rtp_data_channels|.
198void AddRtpDataChannelOptions(
199 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
200 rtp_data_channels,
201 cricket::MediaDescriptionOptions* data_media_description_options) {
202 if (!data_media_description_options) {
203 return;
204 }
deadbeefab9b2d12015-10-14 11:33:11 -0700205 // Check for data channels.
206 for (const auto& kv : rtp_data_channels) {
207 const DataChannel* channel = kv.second;
208 if (channel->state() == DataChannel::kConnecting ||
209 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700210 // Legacy RTP data channels are signaled with the track/stream ID set to
211 // the data channel's label.
212 data_media_description_options->AddRtpDataChannel(channel->label(),
213 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700214 }
215 }
216}
217
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700218uint32_t ConvertIceTransportTypeToCandidateFilter(
219 PeerConnectionInterface::IceTransportsType type) {
220 switch (type) {
221 case PeerConnectionInterface::kNone:
222 return cricket::CF_NONE;
223 case PeerConnectionInterface::kRelay:
224 return cricket::CF_RELAY;
225 case PeerConnectionInterface::kNoHost:
226 return (cricket::CF_ALL & ~cricket::CF_HOST);
227 case PeerConnectionInterface::kAll:
228 return cricket::CF_ALL;
229 default:
nissec80e7412017-01-11 05:56:46 -0800230 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700231 }
232 return cricket::CF_NONE;
233}
234
deadbeef293e9262017-01-11 12:28:30 -0800235// Helper to set an error and return from a method.
236bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
237 if (error) {
238 error->set_type(type);
239 }
240 return type == webrtc::RTCErrorType::NONE;
241}
242
Steve Anton038834f2017-07-14 15:59:59 -0700243bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700244 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700245 if (error_out) {
246 *error_out = std::move(error);
247 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700248 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700249}
250
Steve Antonba818672017-11-06 10:21:57 -0800251std::string GetSignalingStateString(
252 PeerConnectionInterface::SignalingState state) {
253 switch (state) {
254 case PeerConnectionInterface::kStable:
255 return "kStable";
256 case PeerConnectionInterface::kHaveLocalOffer:
257 return "kHaveLocalOffer";
258 case PeerConnectionInterface::kHaveLocalPrAnswer:
259 return "kHavePrAnswer";
260 case PeerConnectionInterface::kHaveRemoteOffer:
261 return "kHaveRemoteOffer";
262 case PeerConnectionInterface::kHaveRemotePrAnswer:
263 return "kHaveRemotePrAnswer";
264 case PeerConnectionInterface::kClosed:
265 return "kClosed";
266 }
267 RTC_NOTREACHED();
268 return "";
269}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700270
Steve Anton75737c02017-11-06 10:37:17 -0800271IceCandidatePairType GetIceCandidatePairCounter(
272 const cricket::Candidate& local,
273 const cricket::Candidate& remote) {
274 const auto& l = local.type();
275 const auto& r = remote.type();
276 const auto& host = LOCAL_PORT_TYPE;
277 const auto& srflx = STUN_PORT_TYPE;
278 const auto& relay = RELAY_PORT_TYPE;
279 const auto& prflx = PRFLX_PORT_TYPE;
280 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800281 bool local_hostname =
282 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
283 bool remote_hostname = !remote.address().hostname().empty() &&
284 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800285 bool local_private = IPIsPrivate(local.address().ipaddr());
286 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800287 if (local_hostname) {
288 if (remote_hostname) {
289 return kIceCandidatePairHostNameHostName;
290 } else if (remote_private) {
291 return kIceCandidatePairHostNameHostPrivate;
292 } else {
293 return kIceCandidatePairHostNameHostPublic;
294 }
295 } else if (local_private) {
296 if (remote_hostname) {
297 return kIceCandidatePairHostPrivateHostName;
298 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800299 return kIceCandidatePairHostPrivateHostPrivate;
300 } else {
301 return kIceCandidatePairHostPrivateHostPublic;
302 }
303 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800304 if (remote_hostname) {
305 return kIceCandidatePairHostPublicHostName;
306 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800307 return kIceCandidatePairHostPublicHostPrivate;
308 } else {
309 return kIceCandidatePairHostPublicHostPublic;
310 }
311 }
312 }
313 if (l == host && r == srflx)
314 return kIceCandidatePairHostSrflx;
315 if (l == host && r == relay)
316 return kIceCandidatePairHostRelay;
317 if (l == host && r == prflx)
318 return kIceCandidatePairHostPrflx;
319 if (l == srflx && r == host)
320 return kIceCandidatePairSrflxHost;
321 if (l == srflx && r == srflx)
322 return kIceCandidatePairSrflxSrflx;
323 if (l == srflx && r == relay)
324 return kIceCandidatePairSrflxRelay;
325 if (l == srflx && r == prflx)
326 return kIceCandidatePairSrflxPrflx;
327 if (l == relay && r == host)
328 return kIceCandidatePairRelayHost;
329 if (l == relay && r == srflx)
330 return kIceCandidatePairRelaySrflx;
331 if (l == relay && r == relay)
332 return kIceCandidatePairRelayRelay;
333 if (l == relay && r == prflx)
334 return kIceCandidatePairRelayPrflx;
335 if (l == prflx && r == host)
336 return kIceCandidatePairPrflxHost;
337 if (l == prflx && r == srflx)
338 return kIceCandidatePairPrflxSrflx;
339 if (l == prflx && r == relay)
340 return kIceCandidatePairPrflxRelay;
341 return kIceCandidatePairMax;
342}
343
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800344// Logic to decide if an m= section can be recycled. This means that the new
345// m= section is not rejected, but the old local or remote m= section is
346// rejected. |old_content_one| and |old_content_two| refer to the m= section
347// of the old remote and old local descriptions in no particular order.
348// We need to check both the old local and remote because either
349// could be the most current from the latest negotation.
350bool IsMediaSectionBeingRecycled(SdpType type,
351 const ContentInfo& content,
352 const ContentInfo* old_content_one,
353 const ContentInfo* old_content_two) {
354 return type == SdpType::kOffer && !content.rejected &&
355 ((old_content_one && old_content_one->rejected) ||
356 (old_content_two && old_content_two->rejected));
357}
358
Steve Anton75737c02017-11-06 10:37:17 -0800359// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800360// |current_desc|. The number of m= sections in |new_desc| should be no
361// less than |current_desc|. In the case of checking an answer's
362// |new_desc|, the |current_desc| is the last offer that was set as the
363// local or remote. In the case of checking an offer's |new_desc| we
364// check against the local and remote descriptions stored from the last
365// negotiation, because either of these could be the most up to date for
366// possible rejected m sections. These are the |current_desc| and
367// |secondary_current_desc|.
368bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
369 const SessionDescription* secondary_current_desc,
370 const SessionDescription& new_desc,
371 const SdpType type) {
372 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
377 const cricket::ContentInfo* secondary_content_info = nullptr;
378 if (secondary_current_desc &&
379 i < secondary_current_desc->contents().size()) {
380 secondary_content_info = &secondary_current_desc->contents()[i];
381 }
382 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
383 &current_desc.contents()[i],
384 secondary_content_info)) {
385 // For new offer descriptions, if the media section can be recycled, it's
386 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800387 continue;
388 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800389 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800390 return false;
391 }
392 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800393 new_desc.contents()[i].media_description();
394 const MediaContentDescription* current_desc_mdesc =
395 current_desc.contents()[i].media_description();
396 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800397 return false;
398 }
399 }
400 return true;
401}
402
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800403bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
404 const SessionDescription& desc2) {
405 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800406}
407
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700408void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
409 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200410 // Array of structs needed to map {KeyExchangeProtocolType,
411 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
412 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
413 static constexpr struct {
414 KeyExchangeProtocolType protocol_type;
415 cricket::MediaType media_type;
416 KeyExchangeProtocolMedia protocol_media;
417 } kEnumCounterKeyProtocolMediaMap[] = {
418 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
419 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
420 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
421 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
422 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
423 kEnumCounterKeyProtocolMediaTypeDtlsData},
424 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
425 kEnumCounterKeyProtocolMediaTypeSdesAudio},
426 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
427 kEnumCounterKeyProtocolMediaTypeSdesVideo},
428 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
429 kEnumCounterKeyProtocolMediaTypeSdesData},
430 };
431
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700432 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
433 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100434
Mirko Bonadeiab499822018-09-11 10:43:20 +0200435 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
436 if (i.protocol_type == protocol_type && i.media_type == media_type) {
437 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
438 i.protocol_media,
439 kEnumCounterKeyProtocolMediaTypeMax);
440 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100441 }
442}
443
Harald Alvestrand76829d72018-07-18 23:24:36 +0200444void NoteAddIceCandidateResult(int result) {
445 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
446 kAddIceCandidateMax);
447}
448
Steve Anton75737c02017-11-06 10:37:17 -0800449// Checks that each non-rejected content has SDES crypto keys or a DTLS
450// fingerprint, unless it's in a BUNDLE group, in which case only the
451// BUNDLE-tag section (first media section/description in the BUNDLE group)
452// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
453// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
454// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700455RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800456 const cricket::ContentGroup* bundle =
457 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800458 for (const cricket::ContentInfo& content_info : desc->contents()) {
459 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800460 continue;
461 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100462 // Note what media is used with each crypto protocol, for all sections.
463 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
464 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700465 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800466 const std::string& mid = content_info.name;
467 if (bundle && bundle->HasContentName(mid) &&
468 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800469 // This isn't the first media section in the BUNDLE group, so it's not
470 // required to have crypto attributes, since only the crypto attributes
471 // from the first section actually get used.
472 continue;
473 }
474
475 // If the content isn't rejected or bundled into another m= section, crypto
476 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800477 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800478 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800479 if (!media || !tinfo) {
480 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800481 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800482 }
483 if (dtls_enabled) {
484 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100485 RTC_LOG(LS_WARNING)
486 << "Session description must have DTLS fingerprint if "
487 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800488 return RTCError(RTCErrorType::INVALID_PARAMETER,
489 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800490 }
491 } else {
492 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100493 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800494 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800495 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800496 }
497 }
498 }
Steve Anton8a006912017-12-04 15:25:56 -0800499 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800500}
501
502// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
503// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
504// media section/description in the BUNDLE group) needs a ufrag and pwd.
505bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
506 const cricket::ContentGroup* bundle =
507 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800508 for (const cricket::ContentInfo& content_info : desc->contents()) {
509 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800510 continue;
511 }
Steve Anton8a006912017-12-04 15:25:56 -0800512 const std::string& mid = content_info.name;
513 if (bundle && bundle->HasContentName(mid) &&
514 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800515 // This isn't the first media section in the BUNDLE group, so it's not
516 // required to have ufrag/password, since only the ufrag/password from
517 // the first section actually get used.
518 continue;
519 }
520
521 // If the content isn't rejected or bundled into another m= section,
522 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800523 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800524 if (!tinfo) {
525 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100526 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800527 return false;
528 }
529 if (tinfo->description.ice_ufrag.empty() ||
530 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800532 return false;
533 }
534 }
535 return true;
536}
537
Steve Anton75737c02017-11-06 10:37:17 -0800538// Get the SCTP port out of a SessionDescription.
539// Return -1 if not found.
540int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800541 const cricket::DataContentDescription* data_desc =
542 GetFirstDataContentDescription(session_description);
543 RTC_DCHECK(data_desc);
544 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800545 return -1;
546 }
Steve Anton75737c02017-11-06 10:37:17 -0800547 std::string value;
548 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
549 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 if (!codec.Matches(match_pattern)) {
552 continue;
553 }
554 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
555 return rtc::FromString<int>(value);
556 }
557 }
558 return -1;
559}
560
Steve Anton75737c02017-11-06 10:37:17 -0800561// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
562bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
563 const SessionDescriptionInterface* new_desc,
564 const std::string& content_name) {
565 if (!old_desc) {
566 return false;
567 }
568 const SessionDescription* new_sd = new_desc->description();
569 const SessionDescription* old_sd = old_desc->description();
570 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
571 if (!cinfo || cinfo->rejected) {
572 return false;
573 }
574 // If the content isn't rejected, check if ufrag and password has changed.
575 const cricket::TransportDescription* new_transport_desc =
576 new_sd->GetTransportDescriptionByName(content_name);
577 const cricket::TransportDescription* old_transport_desc =
578 old_sd->GetTransportDescriptionByName(content_name);
579 if (!new_transport_desc || !old_transport_desc) {
580 // No transport description exists. This is not an ICE restart.
581 return false;
582 }
583 if (cricket::IceCredentialsChanged(
584 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
585 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
587 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800588 return true;
589 }
590 return false;
591}
592
Steve Anton80dd7b52018-02-16 17:08:42 -0800593// Generates a string error message for SetLocalDescription/SetRemoteDescription
594// from an RTCError.
595std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
596 SdpType type,
597 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200598 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800599 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
600 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200601 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800602}
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
605 std::string output = "streams=[";
606 const char* separator = "";
607 for (const auto& stream_id : stream_ids) {
608 output.append(separator).append(stream_id);
609 separator = ", ";
610 }
611 output.append("]");
612 return output;
613}
614
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200615absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700616 int rtc_configuration_parameter) {
617 if (rtc_configuration_parameter ==
618 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200619 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700620 }
621 return rtc_configuration_parameter;
622}
623
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800624cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
625 switch (type) {
626 case DataMessageType::kText:
627 return cricket::DMT_TEXT;
628 case DataMessageType::kBinary:
629 return cricket::DMT_BINARY;
630 case DataMessageType::kControl:
631 return cricket::DMT_CONTROL;
632 default:
633 return cricket::DMT_NONE;
634 }
635 return cricket::DMT_NONE;
636}
637
638DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
639 switch (type) {
640 case cricket::DMT_TEXT:
641 return DataMessageType::kText;
642 case cricket::DMT_BINARY:
643 return DataMessageType::kBinary;
644 case cricket::DMT_CONTROL:
645 return DataMessageType::kControl;
646 case cricket::DMT_NONE:
647 default:
648 RTC_NOTREACHED();
649 }
650 return DataMessageType::kControl;
651}
652
Steve Anton06817cd2018-12-18 15:55:30 -0800653// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
654// and return a reference to it.
655// Generated MIDs should be no more than 3 bytes long to take up less space in
656// the RTP packet.
657const std::string& AllocateMid(std::set<std::string>* used_mids) {
658 RTC_DCHECK(used_mids);
659 // We're boring: just generate MIDs 0, 1, 2, ...
660 size_t i = 0;
661 std::set<std::string>::iterator it;
662 bool inserted;
663 do {
664 std::string mid = rtc::ToString(i++);
665 auto insert_result = used_mids->insert(mid);
666 it = insert_result.first;
667 inserted = insert_result.second;
668 } while (!inserted);
669 return *it;
670}
671
Steve Anton75737c02017-11-06 10:37:17 -0800672} // namespace
673
Henrik Boström31638672017-11-23 17:48:32 +0100674// Upon completion, posts a task to execute the callback of the
675// SetSessionDescriptionObserver asynchronously on the same thread. At this
676// point, the state of the peer connection might no longer reflect the effects
677// of the SetRemoteDescription operation, as the peer connection could have been
678// modified during the post.
679// TODO(hbos): Remove this class once we remove the version of
680// PeerConnectionInterface::SetRemoteDescription() that takes a
681// SetSessionDescriptionObserver as an argument.
682class PeerConnection::SetRemoteDescriptionObserverAdapter
683 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
684 public:
685 SetRemoteDescriptionObserverAdapter(
686 rtc::scoped_refptr<PeerConnection> pc,
687 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
688 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
689
690 // SetRemoteDescriptionObserverInterface implementation.
691 void OnSetRemoteDescriptionComplete(RTCError error) override {
692 if (error.ok())
693 pc_->PostSetSessionDescriptionSuccess(wrapper_);
694 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100695 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100696 }
697
698 private:
699 rtc::scoped_refptr<PeerConnection> pc_;
700 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
701};
702
deadbeef293e9262017-01-11 12:28:30 -0800703bool PeerConnectionInterface::RTCConfiguration::operator==(
704 const PeerConnectionInterface::RTCConfiguration& o) const {
705 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700706 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800707 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000708 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700709 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800710 BundlePolicy bundle_policy;
711 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700712 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
713 int ice_candidate_pool_size;
714 bool disable_ipv6;
715 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700716 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100717 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700718 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200719 absl::optional<int> screencast_min_bitrate;
720 absl::optional<bool> combined_audio_video_bwe;
721 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800722 TcpCandidatePolicy tcp_candidate_policy;
723 CandidateNetworkPolicy candidate_network_policy;
724 int audio_jitter_buffer_max_packets;
725 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100726 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800727 int ice_connection_receiving_timeout;
728 int ice_backup_candidate_pair_ping_interval;
729 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800730 bool prioritize_most_likely_ice_candidate_pairs;
731 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800732 bool prune_turn_ports;
733 bool presume_writable_when_fully_relayed;
734 bool enable_ice_renomination;
735 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200736 absl::optional<int> ice_check_interval_strong_connectivity;
737 absl::optional<int> ice_check_interval_weak_connectivity;
738 absl::optional<int> ice_check_min_interval;
739 absl::optional<int> ice_unwritable_timeout;
740 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800741 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200742 absl::optional<int> stun_candidate_keepalive_interval;
743 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200744 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800745 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200746 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700747 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700748 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700749 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700750 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100751 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800752 };
753 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
754 "Did you add something to RTCConfiguration and forget to "
755 "update operator==?");
756 return type == o.type && servers == o.servers &&
757 bundle_policy == o.bundle_policy &&
758 rtcp_mux_policy == o.rtcp_mux_policy &&
759 tcp_candidate_policy == o.tcp_candidate_policy &&
760 candidate_network_policy == o.candidate_network_policy &&
761 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
762 audio_jitter_buffer_fast_accelerate ==
763 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100764 audio_jitter_buffer_min_delay_ms ==
765 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800766 ice_connection_receiving_timeout ==
767 o.ice_connection_receiving_timeout &&
768 ice_backup_candidate_pair_ping_interval ==
769 o.ice_backup_candidate_pair_ping_interval &&
770 continual_gathering_policy == o.continual_gathering_policy &&
771 certificates == o.certificates &&
772 prioritize_most_likely_ice_candidate_pairs ==
773 o.prioritize_most_likely_ice_candidate_pairs &&
774 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800775 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700776 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100777 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800778 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800779 screencast_min_bitrate == o.screencast_min_bitrate &&
780 combined_audio_video_bwe == o.combined_audio_video_bwe &&
781 enable_dtls_srtp == o.enable_dtls_srtp &&
782 ice_candidate_pool_size == o.ice_candidate_pool_size &&
783 prune_turn_ports == o.prune_turn_ports &&
784 presume_writable_when_fully_relayed ==
785 o.presume_writable_when_fully_relayed &&
786 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800787 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800788 ice_check_interval_strong_connectivity ==
789 o.ice_check_interval_strong_connectivity &&
790 ice_check_interval_weak_connectivity ==
791 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700792 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700793 ice_unwritable_timeout == o.ice_unwritable_timeout &&
794 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800795 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800796 stun_candidate_keepalive_interval ==
797 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200798 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800799 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800800 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700801 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700802 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700803 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700804 use_media_transport_for_data_channels ==
805 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100806 crypto_options == o.crypto_options &&
807 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800808}
809
810bool PeerConnectionInterface::RTCConfiguration::operator!=(
811 const PeerConnectionInterface::RTCConfiguration& o) const {
812 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800813}
814
zhihuang8f65cdf2016-05-06 18:40:30 -0700815// Generate a RTCP CNAME when a PeerConnection is created.
816std::string GenerateRtcpCname() {
817 std::string cname;
818 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800820 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700821 }
822 return cname;
823}
824
zhihuang1c378ed2017-08-17 14:10:50 -0700825bool ValidateOfferAnswerOptions(
826 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
827 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
828 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700829}
830
zhihuang1c378ed2017-08-17 14:10:50 -0700831// From |rtc_options|, fill parts of |session_options| shared by all generated
832// m= sections (in other words, nothing that involves a map/array).
833void ExtractSharedMediaSessionOptions(
834 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
835 cricket::MediaSessionOptions* session_options) {
836 session_options->vad_enabled = rtc_options.voice_activity_detection;
837 session_options->bundle_enabled = rtc_options.use_rtp_mux;
838}
zhihuanga77e6bb2017-08-14 18:17:48 -0700839
zhihuang38ede132017-06-15 12:52:32 -0700840PeerConnection::PeerConnection(PeerConnectionFactory* factory,
841 std::unique_ptr<RtcEventLog> event_log,
842 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700844 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700845 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700846 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700847 remote_streams_(StreamCollection::Create()),
848 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000849
850PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100851 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800852 RTC_DCHECK_RUN_ON(signaling_thread());
853
Steve Anton8af21862017-12-15 11:20:13 -0800854 // Need to stop transceivers before destroying the stats collector because
855 // AudioRtpSender has a reference to the StatsCollector it will update when
856 // stopping.
857 for (auto transceiver : transceivers_) {
858 transceiver->Stop();
859 }
Steve Anton4171afb2017-11-20 10:20:22 -0800860
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700861 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800862 if (stats_collector_) {
863 stats_collector_->WaitForPendingRequest();
864 stats_collector_ = nullptr;
865 }
Steve Anton75737c02017-11-06 10:37:17 -0800866
Steve Anton8af21862017-12-15 11:20:13 -0800867 // Don't destroy BaseChannels until after stats has been cleaned up so that
868 // the last stats request can still read from the channels.
869 DestroyAllChannels();
870
Mirko Bonadei675513b2017-11-09 11:09:25 +0100871 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800872
873 webrtc_session_desc_factory_.reset();
874 sctp_invoker_.reset();
875 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800876 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800877 transport_controller_.reset();
878
deadbeef91dd5672016-05-18 16:55:30 -0700879 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700880 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700881 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700882 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700883 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700884 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800885 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700886 event_log_.reset();
887 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000888}
889
Steve Anton8af21862017-12-15 11:20:13 -0800890void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800891 // Destroy video channels first since they may have a pointer to a voice
892 // channel.
893 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800894 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800895 DestroyTransceiverChannel(transceiver);
896 }
897 }
898 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800899 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800900 DestroyTransceiverChannel(transceiver);
901 }
902 }
903 DestroyDataChannel();
904}
905
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000907 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700908 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100909 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700910
911 RTCError config_error = ValidateConfiguration(configuration);
912 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100913 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700914 return false;
915 }
916
Benjamin Wrightcab58882018-05-02 15:12:47 -0700917 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_ERROR)
919 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100920 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800921 return false;
922 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200923
Benjamin Wrightcab58882018-05-02 15:12:47 -0700924 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800925 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100926 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100927 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800928 return false;
929 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700930
Benjamin Wrightcab58882018-05-02 15:12:47 -0700931 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700932 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700933 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700934 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800935
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200936 cricket::ServerAddresses stun_servers;
937 std::vector<cricket::RelayServerConfig> turn_servers;
938
939 RTCErrorType parse_error =
940 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
941 if (parse_error != RTCErrorType::NONE) {
942 return false;
943 }
944
deadbeef91dd5672016-05-18 16:55:30 -0700945 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700946 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700947 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200948 RTC_FROM_HERE,
949 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
950 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 return false;
952 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200953 // If initialization was successful, note if STUN or TURN servers
954 // were supplied.
955 if (!stun_servers.empty()) {
956 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
957 }
958 if (!turn_servers.empty()) {
959 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
960 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700962 // Send information about IPv4/IPv6 status.
963 PeerConnectionAddressFamilyCounter address_family;
964 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
965 address_family = kPeerConnection_IPv6;
966 } else {
967 address_family = kPeerConnection_IPv4;
968 }
969 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
970 kPeerConnectionAddressFamilyCounter_Max);
971
Zhi Huange830e682018-03-30 10:48:35 -0700972 const PeerConnectionFactoryInterface::Options& options = factory_->options();
973
Steve Anton75737c02017-11-06 10:37:17 -0800974 // RFC 3264: The numeric value of the session id and version in the
975 // o line MUST be representable with a "64 bit signed integer".
976 // Due to this constraint session id |session_id_| is max limited to
977 // LLONG_MAX.
978 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700979 JsepTransportController::Config config;
980 config.redetermine_role_on_ice_restart =
981 configuration.redetermine_role_on_ice_restart;
982 config.ssl_max_version = factory_->options().ssl_max_version;
983 config.disable_encryption = options.disable_encryption;
984 config.bundle_policy = configuration.bundle_policy;
985 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700986 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
987 // stub.
988 config.crypto_options = configuration.crypto_options.has_value()
989 ? *configuration.crypto_options
990 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700991 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700992 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700993#if defined(ENABLE_EXTERNAL_AUTH)
994 config.enable_external_auth = true;
995#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700996 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700997
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700998 if (configuration.use_media_transport ||
999 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001000 if (!factory_->media_transport_factory()) {
1001 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001002 << "PeerConnecton is initialized with use_media_transport = true or "
1003 << "use_media_transport_for_data_channels = true "
1004 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001005 return false;
1006 }
1007
1008 config.media_transport_factory = factory_->media_transport_factory();
1009 }
1010
Zhi Huange830e682018-03-30 10:48:35 -07001011 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001012 signaling_thread(), network_thread(), port_allocator_.get(),
1013 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001014 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001015 this, &PeerConnection::OnTransportControllerConnectionState);
1016 transport_controller_->SignalStandardizedIceConnectionState.connect(
1017 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001018 transport_controller_->SignalConnectionState.connect(
1019 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001020 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001021 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001022 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001023 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001024 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001025 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1026 transport_controller_->SignalDtlsHandshakeError.connect(
1027 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1028
1029 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001030
deadbeefab9b2d12015-10-14 11:33:11 -07001031 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001032 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033
Steve Antonba818672017-11-06 10:21:57 -08001034 configuration_ = configuration;
1035
Steve Anton75737c02017-11-06 10:37:17 -08001036 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1037 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1038 if (!configuration.certificates.empty()) {
1039 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1040 // just picking the first one. The decision should be made based on the DTLS
1041 // handshake. The DTLS negotiations need to know about all certificates.
1042 certificate = configuration.certificates[0];
1043 }
1044
Steve Antond25da372017-11-06 14:50:29 -08001045 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001046
1047 if (options.disable_encryption) {
1048 dtls_enabled_ = false;
1049 } else {
1050 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001051 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001052 // |configuration| can override the default |dtls_enabled_| value.
1053 if (configuration.enable_dtls_srtp) {
1054 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1055 }
1056 }
1057
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001058 if (configuration.use_media_transport_for_data_channels) {
1059 if (configuration.enable_rtp_data_channel) {
1060 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1061 "use_media_transport_for_data_channels are "
1062 "incompatible and cannot both be set to true";
1063 return false;
1064 }
1065 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1066 } else if (configuration.enable_rtp_data_channel) {
1067 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1068 // set. It takes precendence over the disable_sctp_data_channels
1069 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001070 data_channel_type_ = cricket::DCT_RTP;
1071 } else {
1072 // DTLS has to be enabled to use SCTP.
1073 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1074 data_channel_type_ = cricket::DCT_SCTP;
1075 }
1076 }
1077
1078 video_options_.screencast_min_bitrate_kbps =
1079 configuration.screencast_min_bitrate;
1080 audio_options_.combined_audio_video_bwe =
1081 configuration.combined_audio_video_bwe;
1082
1083 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001084 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001085
1086 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001087 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001088
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001089 audio_options_.audio_jitter_buffer_min_delay_ms =
1090 configuration.audio_jitter_buffer_min_delay_ms;
1091
Steve Anton75737c02017-11-06 10:37:17 -08001092 // Whether the certificate generator/certificate is null or not determines
1093 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1094 // the right instructions by clearing the variables if needed.
1095 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001096 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001097 certificate = nullptr;
1098 } else if (certificate) {
1099 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001100 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001101 }
1102
1103 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1104 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001105 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001106 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1107 this, &PeerConnection::OnCertificateReady);
1108
1109 if (options.disable_encryption) {
1110 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1111 }
1112
1113 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001114 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001115 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001116
Steve Anton4171afb2017-11-20 10:20:22 -08001117 // Add default audio/video transceivers for Plan B SDP.
1118 if (!IsUnifiedPlan()) {
1119 transceivers_.push_back(
1120 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1121 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1122 transceivers_.push_back(
1123 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1124 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1125 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001126 int delay_ms =
1127 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001128 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1129 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 return true;
1131}
1132
Steve Anton038834f2017-07-14 15:59:59 -07001133RTCError PeerConnection::ValidateConfiguration(
1134 const RTCConfiguration& config) const {
1135 if (config.ice_regather_interval_range &&
1136 config.continual_gathering_policy == GATHER_ONCE) {
1137 return RTCError(RTCErrorType::INVALID_PARAMETER,
1138 "ice_regather_interval_range specified but continual "
1139 "gathering policy is GATHER_ONCE");
1140 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001141 auto result =
1142 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1143 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001144}
1145
Yves Gerey665174f2018-06-19 15:03:05 +02001146rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001147 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1148 "Plan SdpSemantics. Please use GetSenders "
1149 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001150 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151}
1152
Yves Gerey665174f2018-06-19 15:03:05 +02001153rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001154 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1155 "Plan SdpSemantics. Please use GetReceivers "
1156 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001157 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158}
1159
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001160bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001161 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1162 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001163 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164 if (IsClosed()) {
1165 return false;
1166 }
deadbeefab9b2d12015-10-14 11:33:11 -07001167 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001168 return false;
1169 }
deadbeefab9b2d12015-10-14 11:33:11 -07001170
1171 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001172 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1173 observer->SignalAudioTrackAdded.connect(this,
1174 &PeerConnection::OnAudioTrackAdded);
1175 observer->SignalAudioTrackRemoved.connect(
1176 this, &PeerConnection::OnAudioTrackRemoved);
1177 observer->SignalVideoTrackAdded.connect(this,
1178 &PeerConnection::OnVideoTrackAdded);
1179 observer->SignalVideoTrackRemoved.connect(
1180 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001181 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001182
deadbeefab9b2d12015-10-14 11:33:11 -07001183 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001184 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001185 }
1186 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001187 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001188 }
1189
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001190 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001191 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001192 return true;
1193}
1194
1195void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001196 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1197 "Plan SdpSemantics. Please use RemoveTrack "
1198 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001199 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001200 if (!IsClosed()) {
1201 for (const auto& track : local_stream->GetAudioTracks()) {
1202 RemoveAudioTrack(track.get(), local_stream);
1203 }
1204 for (const auto& track : local_stream->GetVideoTracks()) {
1205 RemoveVideoTrack(track.get(), local_stream);
1206 }
deadbeefab9b2d12015-10-14 11:33:11 -07001207 }
deadbeefab9b2d12015-10-14 11:33:11 -07001208 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001209 stream_observers_.erase(
1210 std::remove_if(
1211 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001212 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001213 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001214 }),
1215 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001217 if (IsClosed()) {
1218 return;
1219 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001220 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001221}
1222
Steve Anton2d6c76a2018-01-05 17:10:52 -08001223RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001224 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001225 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001226 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001227 if (!track) {
1228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1229 }
1230 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1231 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1233 "Track has invalid kind: " + track->kind());
1234 }
Steve Antonf9381f02017-12-14 10:23:57 -08001235 if (IsClosed()) {
1236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1237 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001238 }
Steve Anton4171afb2017-11-20 10:20:22 -08001239 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001240 LOG_AND_RETURN_ERROR(
1241 RTCErrorType::INVALID_PARAMETER,
1242 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001243 }
Steve Antonf9381f02017-12-14 10:23:57 -08001244 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001245 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1246 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001247 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001248 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001249 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001250 }
1251 return sender_or_error;
1252}
deadbeefe1f9d832016-01-14 15:35:42 -08001253
Steve Antonf9381f02017-12-14 10:23:57 -08001254RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1255PeerConnection::AddTrackPlanB(
1256 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001257 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001258 if (stream_ids.size() > 1u) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1260 "AddTrack with more than one stream is not "
1261 "supported with Plan B semantics.");
1262 }
1263 std::vector<std::string> adjusted_stream_ids = stream_ids;
1264 if (adjusted_stream_ids.empty()) {
1265 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1266 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001267 cricket::MediaType media_type =
1268 (track->kind() == MediaStreamTrackInterface::kAudioKind
1269 ? cricket::MEDIA_TYPE_AUDIO
1270 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001271 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001272 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001273 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001274 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001275 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001276 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001277 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001278 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001279 if (sender_info) {
1280 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001281 }
Steve Antonf9381f02017-12-14 10:23:57 -08001282 } else {
1283 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001284 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001285 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001286 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001287 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001288 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001289 if (sender_info) {
1290 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001291 }
deadbeefe1f9d832016-01-14 15:35:42 -08001292 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001293 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001294}
deadbeefe1f9d832016-01-14 15:35:42 -08001295
Steve Antonf9381f02017-12-14 10:23:57 -08001296RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1297PeerConnection::AddTrackUnifiedPlan(
1298 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001299 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001300 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1301 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001302 RTC_LOG(LS_INFO) << "Reusing an existing "
1303 << cricket::MediaTypeToString(transceiver->media_type())
1304 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001305 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001306 transceiver->internal()->set_direction(
1307 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001308 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001309 transceiver->internal()->set_direction(
1310 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001312 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001313 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001314 } else {
1315 cricket::MediaType media_type =
1316 (track->kind() == MediaStreamTrackInterface::kAudioKind
1317 ? cricket::MEDIA_TYPE_AUDIO
1318 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001319 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1320 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001321 std::string sender_id = track->id();
1322 // Avoid creating a sender with an existing ID by generating a random ID.
1323 // This can happen if this is the second time AddTrack has created a sender
1324 // for this track.
1325 if (FindSenderById(sender_id)) {
1326 sender_id = rtc::CreateRandomUuid();
1327 }
Florent Castelli892acf02018-10-01 22:47:20 +02001328 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001329 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1330 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001331 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001332 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001333 }
Steve Antonf9381f02017-12-14 10:23:57 -08001334 return transceiver->sender();
1335}
1336
1337rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1338PeerConnection::FindFirstTransceiverForAddedTrack(
1339 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1340 RTC_DCHECK(track);
1341 for (auto transceiver : transceivers_) {
1342 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001343 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001344 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001345 !transceiver->internal()->has_ever_been_used_to_send() &&
1346 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001347 return transceiver;
1348 }
1349 }
1350 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001351}
1352
1353bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1354 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001355 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001356}
1357
Steve Anton24db5732018-07-23 10:27:33 -07001358RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001359 rtc::scoped_refptr<RtpSenderInterface> sender) {
1360 if (!sender) {
1361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1362 }
deadbeefe1f9d832016-01-14 15:35:42 -08001363 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001364 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1365 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001366 }
Steve Antonf9381f02017-12-14 10:23:57 -08001367 if (IsUnifiedPlan()) {
1368 auto transceiver = FindTransceiverBySender(sender);
1369 if (!transceiver || !sender->track()) {
1370 return RTCError::OK();
1371 }
1372 sender->SetTrack(nullptr);
1373 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001374 transceiver->internal()->set_direction(
1375 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001376 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001377 transceiver->internal()->set_direction(
1378 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001379 }
Steve Anton4171afb2017-11-20 10:20:22 -08001380 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001381 bool removed;
1382 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1383 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1384 } else {
1385 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1386 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1387 }
1388 if (!removed) {
1389 LOG_AND_RETURN_ERROR(
1390 RTCErrorType::INVALID_PARAMETER,
1391 "Couldn't find sender " + sender->id() + " to remove.");
1392 }
Steve Anton4171afb2017-11-20 10:20:22 -08001393 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001394 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001395 return RTCError::OK();
1396}
1397
1398rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1399PeerConnection::FindTransceiverBySender(
1400 rtc::scoped_refptr<RtpSenderInterface> sender) {
1401 for (auto transceiver : transceivers_) {
1402 if (transceiver->sender() == sender) {
1403 return transceiver;
1404 }
1405 }
1406 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001407}
1408
Steve Anton9158ef62017-11-27 13:01:52 -08001409RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1410PeerConnection::AddTransceiver(
1411 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1412 return AddTransceiver(track, RtpTransceiverInit());
1413}
1414
1415RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1416PeerConnection::AddTransceiver(
1417 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1418 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001419 RTC_CHECK(IsUnifiedPlan())
1420 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001421 if (!track) {
1422 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1423 }
1424 cricket::MediaType media_type;
1425 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1426 media_type = cricket::MEDIA_TYPE_AUDIO;
1427 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1428 media_type = cricket::MEDIA_TYPE_VIDEO;
1429 } else {
1430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1431 "Track kind is not audio or video");
1432 }
1433 return AddTransceiver(media_type, track, init);
1434}
1435
1436RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1437PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1438 return AddTransceiver(media_type, RtpTransceiverInit());
1439}
1440
1441RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1442PeerConnection::AddTransceiver(cricket::MediaType media_type,
1443 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001444 RTC_CHECK(IsUnifiedPlan())
1445 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001446 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1447 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1449 "media type is not audio or video");
1450 }
1451 return AddTransceiver(media_type, nullptr, init);
1452}
1453
1454RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1455PeerConnection::AddTransceiver(
1456 cricket::MediaType media_type,
1457 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001458 const RtpTransceiverInit& init,
1459 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001460 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1461 media_type == cricket::MEDIA_TYPE_VIDEO));
1462 if (track) {
1463 RTC_DCHECK_EQ(media_type,
1464 (track->kind() == MediaStreamTrackInterface::kAudioKind
1465 ? cricket::MEDIA_TYPE_AUDIO
1466 : cricket::MEDIA_TYPE_VIDEO));
1467 }
1468
1469 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001470 if (init.send_encodings.size() > 1) {
1471 LOG_AND_RETURN_ERROR(
1472 RTCErrorType::UNSUPPORTED_PARAMETER,
1473 "Attempted to create an encoder with more than 1 encoding parameter.");
1474 }
1475
1476 for (const auto& encoding : init.send_encodings) {
1477 if (encoding.ssrc.has_value()) {
1478 LOG_AND_RETURN_ERROR(
1479 RTCErrorType::UNSUPPORTED_PARAMETER,
1480 "Attempted to set an unimplemented parameter of RtpParameters.");
1481 }
1482 }
1483
1484 RtpParameters parameters;
1485 parameters.encodings = init.send_encodings;
1486 if (UnimplementedRtpParameterHasValue(parameters)) {
1487 LOG_AND_RETURN_ERROR(
1488 RTCErrorType::UNSUPPORTED_PARAMETER,
1489 "Attempted to set an unimplemented parameter of RtpParameters.");
1490 }
Steve Anton9158ef62017-11-27 13:01:52 -08001491
Steve Anton3d954a62018-04-02 11:27:23 -07001492 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1493 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001494 // Set the sender ID equal to the track ID if the track is specified unless
1495 // that sender ID is already in use.
1496 std::string sender_id =
1497 (track && !FindSenderById(track->id()) ? track->id()
1498 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001499 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1500 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001501 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1502 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1503 transceiver->internal()->set_direction(init.direction);
1504
Steve Anton22da89f2018-01-25 13:58:07 -08001505 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001506 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001507 }
Steve Antonf9381f02017-12-14 10:23:57 -08001508
1509 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1510}
1511
Steve Anton02ee47c2018-01-10 16:26:06 -08001512rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1513PeerConnection::CreateSender(
1514 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001515 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001516 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001517 const std::vector<std::string>& stream_ids,
1518 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001519 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001520 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1521 RTC_DCHECK(!track ||
1522 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1523 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1524 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001525 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001526 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 } else {
1528 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1529 RTC_DCHECK(!track ||
1530 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1531 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001532 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001533 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001535 bool set_track_succeeded = sender->SetTrack(track);
1536 RTC_DCHECK(set_track_succeeded);
1537 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001538 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 return sender;
1540}
1541
1542rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1543PeerConnection::CreateReceiver(cricket::MediaType media_type,
1544 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001545 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1546 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001547 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001548 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001549 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1550 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001551 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001552 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001553 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001554 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001555 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1556 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001557 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001558 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001559 return receiver;
1560}
1561
1562rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1563PeerConnection::CreateAndAddTransceiver(
1564 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1565 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1566 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001567 // Ensure that the new sender does not have an ID that is already in use by
1568 // another sender.
1569 // Allow receiver IDs to conflict since those come from remote SDP (which
1570 // could be invalid, but should not cause a crash).
1571 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001572 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1573 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001574 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001575 transceiver->internal()->SignalNegotiationNeeded.connect(
1576 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001577 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001578}
1579
Steve Anton52d86772018-02-20 15:48:12 -08001580void PeerConnection::OnNegotiationNeeded() {
1581 RTC_DCHECK_RUN_ON(signaling_thread());
1582 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001583 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001584}
1585
deadbeeffac06552015-11-25 11:26:01 -08001586rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001587 const std::string& kind,
1588 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001589 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1590 "Plan SdpSemantics. Please use AddTransceiver "
1591 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001592 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001593 if (IsClosed()) {
1594 return nullptr;
1595 }
Steve Anton4171afb2017-11-20 10:20:22 -08001596
Seth Hampson5b4f0752018-04-02 16:31:36 -07001597 // Internally we need to have one stream with Plan B semantics, so we
1598 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001599 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001600 if (stream_id.empty()) {
1601 stream_ids.push_back(rtc::CreateRandomUuid());
1602 RTC_LOG(LS_INFO)
1603 << "No stream_id specified for sender. Generated stream ID: "
1604 << stream_ids[0];
1605 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001606 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001607 }
1608
Steve Anton4171afb2017-11-20 10:20:22 -08001609 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001610 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001611 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001612 auto* audio_sender = new AudioRtpSender(
1613 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001614 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001615 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001616 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001617 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001618 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001619 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001620 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001621 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001622 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001623 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001624 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001625 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001626 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001627 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001628 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001629 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001630
deadbeefe1f9d832016-01-14 15:35:42 -08001631 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001632}
1633
deadbeef70ab1a12015-09-28 16:53:55 -07001634std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1635 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001636 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001637 for (auto sender : GetSendersInternal()) {
1638 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001639 }
1640 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001641}
1642
Steve Anton4171afb2017-11-20 10:20:22 -08001643std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1644PeerConnection::GetSendersInternal() const {
1645 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1646 all_senders;
1647 for (auto transceiver : transceivers_) {
1648 auto senders = transceiver->internal()->senders();
1649 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1650 }
1651 return all_senders;
1652}
1653
deadbeef70ab1a12015-09-28 16:53:55 -07001654std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1655PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001656 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001657 for (const auto& receiver : GetReceiversInternal()) {
1658 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001659 }
1660 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001661}
1662
Steve Anton4171afb2017-11-20 10:20:22 -08001663std::vector<
1664 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1665PeerConnection::GetReceiversInternal() const {
1666 std::vector<
1667 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1668 all_receivers;
1669 for (auto transceiver : transceivers_) {
1670 auto receivers = transceiver->internal()->receivers();
1671 all_receivers.insert(all_receivers.end(), receivers.begin(),
1672 receivers.end());
1673 }
1674 return all_receivers;
1675}
1676
Steve Anton9158ef62017-11-27 13:01:52 -08001677std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1678PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001679 RTC_CHECK(IsUnifiedPlan())
1680 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001681 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1682 for (auto transceiver : transceivers_) {
1683 all_transceivers.push_back(transceiver);
1684 }
1685 return all_transceivers;
1686}
1687
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001689 MediaStreamTrackInterface* track,
1690 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001691 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001692 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001693 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001694 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 return false;
1696 }
1697
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001698 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001699 // The StatsCollector is used to tell if a track is valid because it may
1700 // remember tracks that the PeerConnection previously removed.
1701 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001702 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1703 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001704 return false;
1705 }
Steve Antonad182762018-09-05 20:22:40 +00001706 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1707 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708 return true;
1709}
1710
hbos74e1a4f2016-09-15 23:33:01 -07001711void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001712 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001713 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001714 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001715 stats_collector_->GetStatsReport(callback);
1716}
1717
Henrik Boström1df1bf82018-03-20 13:24:20 +01001718void PeerConnection::GetStats(
1719 rtc::scoped_refptr<RtpSenderInterface> selector,
1720 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1721 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1722 RTC_DCHECK(callback);
1723 RTC_DCHECK(stats_collector_);
1724 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1725 if (selector) {
1726 for (const auto& proxy_transceiver : transceivers_) {
1727 for (const auto& proxy_sender :
1728 proxy_transceiver->internal()->senders()) {
1729 if (proxy_sender == selector) {
1730 internal_sender = proxy_sender->internal();
1731 break;
1732 }
1733 }
1734 if (internal_sender)
1735 break;
1736 }
1737 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001738 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001739 // belong to the PeerConnection (in Plan B, senders can be removed from the
1740 // PeerConnection). This means that "all the stats objects representing the
1741 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1742 // produces an empty stats report.
1743 stats_collector_->GetStatsReport(internal_sender, callback);
1744}
1745
1746void PeerConnection::GetStats(
1747 rtc::scoped_refptr<RtpReceiverInterface> selector,
1748 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1749 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1750 RTC_DCHECK(callback);
1751 RTC_DCHECK(stats_collector_);
1752 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1753 if (selector) {
1754 for (const auto& proxy_transceiver : transceivers_) {
1755 for (const auto& proxy_receiver :
1756 proxy_transceiver->internal()->receivers()) {
1757 if (proxy_receiver == selector) {
1758 internal_receiver = proxy_receiver->internal();
1759 break;
1760 }
1761 }
1762 if (internal_receiver)
1763 break;
1764 }
1765 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001766 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001767 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1768 // the PeerConnection). This means that "all the stats objects representing
1769 // the selector" is an empty set. Invoking GetStatsReport() with a null
1770 // selector produces an empty stats report.
1771 stats_collector_->GetStatsReport(internal_receiver, callback);
1772}
1773
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1775 return signaling_state_;
1776}
1777
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778PeerConnectionInterface::IceConnectionState
1779PeerConnection::ice_connection_state() {
1780 return ice_connection_state_;
1781}
1782
Alex Loiko9289eda2018-11-23 16:18:59 +00001783PeerConnectionInterface::IceConnectionState
1784PeerConnection::standardized_ice_connection_state() {
1785 return standardized_ice_connection_state_;
1786}
1787
Jonas Olsson635474e2018-10-18 15:58:17 +02001788PeerConnectionInterface::PeerConnectionState
1789PeerConnection::peer_connection_state() {
1790 return connection_state_;
1791}
1792
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793PeerConnectionInterface::IceGatheringState
1794PeerConnection::ice_gathering_state() {
1795 return ice_gathering_state_;
1796}
1797
Yves Gerey665174f2018-06-19 15:03:05 +02001798rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799 const std::string& label,
1800 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001801 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001802
deadbeefab9b2d12015-10-14 11:33:11 -07001803 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001804
kwibergd1fe2812016-04-27 06:47:29 -07001805 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001806 if (config) {
1807 internal_config.reset(new InternalDataChannelInit(*config));
1808 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001809 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001810 InternalCreateDataChannel(label, internal_config.get()));
1811 if (!channel.get()) {
1812 return nullptr;
1813 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001815 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1816 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001817 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001818 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001819 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001820 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821 return DataChannelProxy::Create(signaling_thread(), channel.get());
1822}
1823
1824void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001825 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001826 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001827
nisse7ce109a2017-01-31 00:57:56 -08001828 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001829 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001830 return;
1831 }
deadbeefab9b2d12015-10-14 11:33:11 -07001832
Steve Anton8d3444d2017-10-20 15:30:51 -07001833 if (IsClosed()) {
1834 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001835 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001836 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001837 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001838 return;
1839 }
1840
zhihuang1c378ed2017-08-17 14:10:50 -07001841 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001842 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001843 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001844 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001845 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001846 return;
1847 }
1848
Steve Anton22da89f2018-01-25 13:58:07 -08001849 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1850 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1851 if (IsUnifiedPlan()) {
1852 RTCError error = HandleLegacyOfferOptions(options);
1853 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001854 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001855 return;
1856 }
1857 }
1858
zhihuang1c378ed2017-08-17 14:10:50 -07001859 cricket::MediaSessionOptions session_options;
1860 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001861 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862}
1863
Steve Anton22da89f2018-01-25 13:58:07 -08001864RTCError PeerConnection::HandleLegacyOfferOptions(
1865 const RTCOfferAnswerOptions& options) {
1866 RTC_DCHECK(IsUnifiedPlan());
1867
1868 if (options.offer_to_receive_audio == 0) {
1869 RemoveRecvDirectionFromReceivingTransceiversOfType(
1870 cricket::MEDIA_TYPE_AUDIO);
1871 } else if (options.offer_to_receive_audio == 1) {
1872 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1873 } else if (options.offer_to_receive_audio > 1) {
1874 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1875 "offer_to_receive_audio > 1 is not supported.");
1876 }
1877
1878 if (options.offer_to_receive_video == 0) {
1879 RemoveRecvDirectionFromReceivingTransceiversOfType(
1880 cricket::MEDIA_TYPE_VIDEO);
1881 } else if (options.offer_to_receive_video == 1) {
1882 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1883 } else if (options.offer_to_receive_video > 1) {
1884 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1885 "offer_to_receive_video > 1 is not supported.");
1886 }
1887
1888 return RTCError::OK();
1889}
1890
1891void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1892 cricket::MediaType media_type) {
1893 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001894 RtpTransceiverDirection new_direction =
1895 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1896 if (new_direction != transceiver->direction()) {
1897 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1898 << " transceiver (MID="
1899 << transceiver->mid().value_or("<not set>") << ") from "
1900 << RtpTransceiverDirectionToString(
1901 transceiver->direction())
1902 << " to "
1903 << RtpTransceiverDirectionToString(new_direction)
1904 << " since CreateOffer specified offer_to_receive=0";
1905 transceiver->internal()->set_direction(new_direction);
1906 }
Steve Anton22da89f2018-01-25 13:58:07 -08001907 }
1908}
1909
1910void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1911 cricket::MediaType media_type) {
1912 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001913 RTC_LOG(LS_INFO)
1914 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1915 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001916 RtpTransceiverInit init;
1917 init.direction = RtpTransceiverDirection::kRecvOnly;
1918 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1919 }
1920}
1921
1922std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1923PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1924 std::vector<
1925 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1926 receiving_transceivers;
1927 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001928 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001929 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1930 receiving_transceivers.push_back(transceiver);
1931 }
1932 }
1933 return receiving_transceivers;
1934}
1935
htaa2a49d92016-03-04 02:51:39 -08001936void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1937 const RTCOfferAnswerOptions& options) {
1938 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001939 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001940 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001941 return;
1942 }
1943
Steve Antondffead82018-02-06 10:31:29 -08001944 if (!(signaling_state_ == kHaveRemoteOffer ||
1945 signaling_state_ == kHaveLocalPrAnswer)) {
1946 std::string error =
1947 "PeerConnection cannot create an answer in a state other than "
1948 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001949 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001950 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001951 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001952 return;
1953 }
1954
Steve Antondffead82018-02-06 10:31:29 -08001955 // The remote description should be set if we're in the right state.
1956 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001957
Steve Anton22da89f2018-01-25 13:58:07 -08001958 if (IsUnifiedPlan()) {
1959 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1960 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1961 "supported with Unified Plan semantics. Use the "
1962 "RtpTransceiver API instead.";
1963 }
1964 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1965 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1966 "supported with Unified Plan semantics. Use the "
1967 "RtpTransceiver API instead.";
1968 }
1969 }
1970
htaa2a49d92016-03-04 02:51:39 -08001971 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001972 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001973
Steve Antond25da372017-11-06 14:50:29 -08001974 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975}
1976
1977void PeerConnection::SetLocalDescription(
1978 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001979 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001980 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001981
Steve Anton80dd7b52018-02-16 17:08:42 -08001982 // The SetLocalDescription contract is that we take ownership of the session
1983 // description regardless of the outcome, so wrap it in a unique_ptr right
1984 // away. Ideally, SetLocalDescription's signature will be changed to take the
1985 // description as a unique_ptr argument to formalize this agreement.
1986 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1987
nisse7ce109a2017-01-31 00:57:56 -08001988 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001989 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990 return;
1991 }
Steve Anton8a006912017-12-04 15:25:56 -08001992
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001994 PostSetSessionDescriptionFailure(
1995 observer,
1996 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 return;
1998 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001999
Steve Anton80dd7b52018-02-16 17:08:42 -08002000 // If a session error has occurred the PeerConnection is in a possibly
2001 // inconsistent state so fail right away.
2002 if (session_error() != SessionError::kNone) {
2003 std::string error_message = GetSessionErrorMsg();
2004 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002005 PostSetSessionDescriptionFailure(
2006 observer,
2007 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002008 return;
2009 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002010
Steve Anton80dd7b52018-02-16 17:08:42 -08002011 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2012 if (!error.ok()) {
2013 std::string error_message = GetSetDescriptionErrorMessage(
2014 cricket::CS_LOCAL, desc->GetType(), error);
2015 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002016 PostSetSessionDescriptionFailure(
2017 observer,
2018 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002019 return;
2020 }
2021
2022 // Grab the description type before moving ownership to ApplyLocalDescription,
2023 // which may destroy it before returning.
2024 const SdpType type = desc->GetType();
2025
2026 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002027 // |desc| may be destroyed at this point.
2028
2029 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002030 // If ApplyLocalDescription fails, the PeerConnection could be in an
2031 // inconsistent state, so act conservatively here and set the session error
2032 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2033 SetSessionError(SessionError::kContent, error.message());
2034 std::string error_message =
2035 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2036 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002037 PostSetSessionDescriptionFailure(
2038 observer,
2039 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002040 return;
2041 }
Steve Anton8a006912017-12-04 15:25:56 -08002042 RTC_DCHECK(local_description());
2043
2044 PostSetSessionDescriptionSuccess(observer);
2045
Steve Antonad182762018-09-05 20:22:40 +00002046 // MaybeStartGathering needs to be called after posting
2047 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2048 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002049 transport_controller_->MaybeStartGathering();
2050
Steve Antona3a92c22017-12-07 10:27:41 -08002051 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002052 // TODO(deadbeef): We already had to hop to the network thread for
2053 // MaybeStartGathering...
2054 network_thread()->Invoke<void>(
2055 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2056 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002057 // Make UMA notes about what was agreed to.
2058 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002059 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002060 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002061}
2062
2063RTCError PeerConnection::ApplyLocalDescription(
2064 std::unique_ptr<SessionDescriptionInterface> desc) {
2065 RTC_DCHECK_RUN_ON(signaling_thread());
2066 RTC_DCHECK(desc);
2067
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002068 // Update stats here so that we have the most recent stats for tracks and
2069 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002070 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002071
Steve Antondcc3c022017-12-22 16:02:54 -08002072 // Take a reference to the old local description since it's used below to
2073 // compare against the new local description. When setting the new local
2074 // description, grab ownership of the replaced session description in case it
2075 // is the same as |old_local_description|, to keep it alive for the duration
2076 // of the method.
2077 const SessionDescriptionInterface* old_local_description =
2078 local_description();
2079 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002080 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002081 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002082 replaced_local_description = pending_local_description_
2083 ? std::move(pending_local_description_)
2084 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002085 current_local_description_ = std::move(desc);
2086 pending_local_description_ = nullptr;
2087 current_remote_description_ = std::move(pending_remote_description_);
2088 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002089 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002090 pending_local_description_ = std::move(desc);
2091 }
2092 // The session description to apply now must be accessed by
2093 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002094 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002095
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002096 if (!is_caller_) {
2097 if (remote_description()) {
2098 // Remote description was applied first, so this PC is the callee.
2099 is_caller_ = false;
2100 } else {
2101 // Local description is applied first, so this PC is the caller.
2102 is_caller_ = true;
2103 }
2104 }
2105
Zhi Huange830e682018-03-30 10:48:35 -07002106 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2107 if (!error.ok()) {
2108 return error;
2109 }
2110
Steve Antondcc3c022017-12-22 16:02:54 -08002111 if (IsUnifiedPlan()) {
2112 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002113 cricket::CS_LOCAL, *local_description(), old_local_description,
2114 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002115 if (!error.ok()) {
2116 return error;
2117 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002118 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2119 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002120 for (auto transceiver : transceivers_) {
2121 const ContentInfo* content =
2122 FindMediaSectionForTransceiver(transceiver, local_description());
2123 if (!content) {
2124 continue;
2125 }
2126 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002127 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2128 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002129 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2131 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2132 // "recvonly", process the removal of a remote track for the media
2133 // description, given transceiver, removeList, and muteTracks.
2134 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2135 (transceiver->internal()->fired_direction() &&
2136 RtpTransceiverDirectionHasRecv(
2137 *transceiver->internal()->fired_direction()))) {
2138 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2139 &removed_streams);
2140 }
2141 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2142 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002143 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002144 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002145 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002146 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002147 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002148 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002149 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002150 }
2151 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002152 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002153 }
2154 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002155 // Media channels will be created only when offer is set. These may use new
2156 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002157 if (type == SdpType::kOffer) {
2158 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2159 // description is applied. Restore back to old description.
2160 RTCError error = CreateChannels(*local_description()->description());
2161 if (!error.ok()) {
2162 return error;
2163 }
2164 }
Steve Antondcc3c022017-12-22 16:02:54 -08002165 // Remove unused channels if MediaContentDescription is rejected.
2166 RemoveUnusedChannels(local_description()->description());
2167 }
Steve Anton8a006912017-12-04 15:25:56 -08002168
Zhi Huange830e682018-03-30 10:48:35 -07002169 error = UpdateSessionState(type, cricket::CS_LOCAL,
2170 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002171 if (!error.ok()) {
2172 return error;
2173 }
Steve Antondcc3c022017-12-22 16:02:54 -08002174
Steve Anton8a006912017-12-04 15:25:56 -08002175 if (remote_description()) {
2176 // Now that we have a local description, we can push down remote candidates.
2177 UseCandidatesInSessionDescription(remote_description());
2178 }
2179
2180 pending_ice_restarts_.clear();
2181 if (session_error() != SessionError::kNone) {
2182 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2183 }
2184
deadbeefab9b2d12015-10-14 11:33:11 -07002185 // If setting the description decided our SSL role, allocate any necessary
2186 // SCTP sids.
2187 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002188 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002189 AllocateSctpSids(role);
2190 }
2191
Steve Antond3679212018-01-17 17:41:02 -08002192 if (IsUnifiedPlan()) {
2193 for (auto transceiver : transceivers_) {
2194 const ContentInfo* content =
2195 FindMediaSectionForTransceiver(transceiver, local_description());
2196 if (!content) {
2197 continue;
2198 }
Steve Anton74255ff2018-01-24 18:32:57 -08002199 const auto& streams = content->media_description()->streams();
2200 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002201 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002202 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002203 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002204 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002205 } else {
2206 // 0 is a special value meaning "this sender has no associated send
2207 // stream". Need to call this so the sender won't attempt to configure
2208 // a no longer existing stream and run into DCHECKs in the lower
2209 // layers.
2210 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002211 }
2212 }
2213 } else {
2214 // Plan B semantics.
2215
Steve Antondcc3c022017-12-22 16:02:54 -08002216 // Update state and SSRC of local MediaStreams and DataChannels based on the
2217 // local session description.
2218 const cricket::ContentInfo* audio_content =
2219 GetFirstAudioContent(local_description()->description());
2220 if (audio_content) {
2221 if (audio_content->rejected) {
2222 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2223 } else {
2224 const cricket::AudioContentDescription* audio_desc =
2225 audio_content->media_description()->as_audio();
2226 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2227 }
deadbeeffaac4972015-11-12 15:33:07 -08002228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229
Steve Antondcc3c022017-12-22 16:02:54 -08002230 const cricket::ContentInfo* video_content =
2231 GetFirstVideoContent(local_description()->description());
2232 if (video_content) {
2233 if (video_content->rejected) {
2234 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2235 } else {
2236 const cricket::VideoContentDescription* video_desc =
2237 video_content->media_description()->as_video();
2238 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2239 }
deadbeeffaac4972015-11-12 15:33:07 -08002240 }
deadbeefab9b2d12015-10-14 11:33:11 -07002241 }
2242
2243 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002244 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002245 if (data_content) {
2246 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002247 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002248 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002249 cricket::kMediaProtocolRtpPrefix)) {
2250 UpdateLocalRtpDataChannels(data_desc->streams());
2251 }
2252 }
2253
Steve Anton8a006912017-12-04 15:25:56 -08002254 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255}
2256
Steve Anton06817cd2018-12-18 15:55:30 -08002257// The SDP parser used to populate these values by default for the 'content
2258// name' if an a=mid line was absent.
2259static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2260 switch (media_type) {
2261 case cricket::MEDIA_TYPE_AUDIO:
2262 return cricket::CN_AUDIO;
2263 case cricket::MEDIA_TYPE_VIDEO:
2264 return cricket::CN_VIDEO;
2265 case cricket::MEDIA_TYPE_DATA:
2266 return cricket::CN_DATA;
2267 }
2268 RTC_NOTREACHED();
2269 return "";
2270}
2271
2272void PeerConnection::FillInMissingRemoteMids(
2273 cricket::SessionDescription* remote_description) {
2274 RTC_DCHECK(remote_description);
2275 const cricket::ContentInfos& local_contents =
2276 (local_description() ? local_description()->description()->contents()
2277 : cricket::ContentInfos());
2278 std::set<std::string> used_mids = seen_mids_;
2279 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2280 cricket::ContentInfo& content = remote_description->contents()[i];
2281 if (!content.name.empty()) {
2282 continue;
2283 }
2284 absl::string_view new_mid;
2285 absl::string_view source_explanation;
2286 if (IsUnifiedPlan()) {
2287 if (i < local_contents.size()) {
2288 new_mid = local_contents[i].name;
2289 source_explanation = "from the matching local media section";
2290 } else {
2291 new_mid = AllocateMid(&used_mids);
2292 source_explanation = "generated just now";
2293 }
2294 } else {
2295 new_mid = GetDefaultMidForPlanB(content.media_description()->type());
2296 source_explanation = "to match pre-existing behavior";
2297 }
2298 content.name = std::string(new_mid);
2299 remote_description->transport_infos()[i].content_name =
2300 std::string(new_mid);
2301 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2302 << " is missing an a=mid line. Filling in the value '"
2303 << new_mid << "' " << source_explanation << ".";
2304 }
2305}
2306
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002308 SetSessionDescriptionObserver* observer,
2309 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002310 SetRemoteDescription(
2311 std::unique_ptr<SessionDescriptionInterface>(desc),
2312 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2313 new SetRemoteDescriptionObserverAdapter(this, observer)));
2314}
2315
2316void PeerConnection::SetRemoteDescription(
2317 std::unique_ptr<SessionDescriptionInterface> desc,
2318 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002319 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002320
nisse7ce109a2017-01-31 00:57:56 -08002321 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002322 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 return;
2324 }
Steve Anton8a006912017-12-04 15:25:56 -08002325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002327 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002328 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 return;
2330 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002331
Steve Anton80dd7b52018-02-16 17:08:42 -08002332 // If a session error has occurred the PeerConnection is in a possibly
2333 // inconsistent state so fail right away.
2334 if (session_error() != SessionError::kNone) {
2335 std::string error_message = GetSessionErrorMsg();
2336 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2337 observer->OnSetRemoteDescriptionComplete(
2338 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2339 return;
2340 }
Steve Anton71439a62018-02-15 11:53:06 -08002341
Steve Antonba42e992018-04-09 14:10:01 -07002342 if (desc->GetType() == SdpType::kOffer) {
2343 // Report to UMA the format of the received offer.
2344 ReportSdpFormatReceived(*desc);
2345 }
2346
Steve Anton06817cd2018-12-18 15:55:30 -08002347 // Handle remote descriptions missing a=mid lines for interop with legacy end
2348 // points.
2349 FillInMissingRemoteMids(desc->description());
2350
Steve Anton80dd7b52018-02-16 17:08:42 -08002351 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002352 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002353 std::string error_message = GetSetDescriptionErrorMessage(
2354 cricket::CS_REMOTE, desc->GetType(), error);
2355 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002356 observer->OnSetRemoteDescriptionComplete(
2357 RTCError(error.type(), std::move(error_message)));
2358 return;
2359 }
Steve Anton71439a62018-02-15 11:53:06 -08002360
Steve Anton80dd7b52018-02-16 17:08:42 -08002361 // Grab the description type before moving ownership to
2362 // ApplyRemoteDescription, which may destroy it before returning.
2363 const SdpType type = desc->GetType();
2364
2365 error = ApplyRemoteDescription(std::move(desc));
2366 // |desc| may be destroyed at this point.
2367
2368 if (!error.ok()) {
2369 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2370 // inconsistent state, so act conservatively here and set the session error
2371 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2372 SetSessionError(SessionError::kContent, error.message());
2373 std::string error_message =
2374 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2375 RTC_LOG(LS_ERROR) << error_message;
2376 observer->OnSetRemoteDescriptionComplete(
2377 RTCError(error.type(), std::move(error_message)));
2378 return;
2379 }
2380 RTC_DCHECK(remote_description());
2381
2382 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002383 // TODO(deadbeef): We already had to hop to the network thread for
2384 // MaybeStartGathering...
2385 network_thread()->Invoke<void>(
2386 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2387 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002388 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002389 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002390 }
2391
2392 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002393 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002394}
2395
2396RTCError PeerConnection::ApplyRemoteDescription(
2397 std::unique_ptr<SessionDescriptionInterface> desc) {
2398 RTC_DCHECK_RUN_ON(signaling_thread());
2399 RTC_DCHECK(desc);
2400
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 // Update stats here so that we have the most recent stats for tracks and
2402 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002403 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002404
Steve Antondcc3c022017-12-22 16:02:54 -08002405 // Take a reference to the old remote description since it's used below to
2406 // compare against the new remote description. When setting the new remote
2407 // description, grab ownership of the replaced session description in case it
2408 // is the same as |old_remote_description|, to keep it alive for the duration
2409 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002410 const SessionDescriptionInterface* old_remote_description =
2411 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002412 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002413 SdpType type = desc->GetType();
2414 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002415 replaced_remote_description = pending_remote_description_
2416 ? std::move(pending_remote_description_)
2417 : std::move(current_remote_description_);
2418 current_remote_description_ = std::move(desc);
2419 pending_remote_description_ = nullptr;
2420 current_local_description_ = std::move(pending_local_description_);
2421 } else {
2422 replaced_remote_description = std::move(pending_remote_description_);
2423 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 }
Steve Anton8a006912017-12-04 15:25:56 -08002425 // The session description to apply now must be accessed by
2426 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002427 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428
Zhi Huange830e682018-03-30 10:48:35 -07002429 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2430 if (!error.ok()) {
2431 return error;
2432 }
Steve Anton8a006912017-12-04 15:25:56 -08002433 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002434 if (IsUnifiedPlan()) {
2435 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002436 cricket::CS_REMOTE, *remote_description(), local_description(),
2437 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002438 if (!error.ok()) {
2439 return error;
2440 }
Steve Antondcc3c022017-12-22 16:02:54 -08002441 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002442 // Media channels will be created only when offer is set. These may use new
2443 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002444 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002445 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002446 // description is applied. Restore back to old description.
2447 RTCError error = CreateChannels(*remote_description()->description());
2448 if (!error.ok()) {
2449 return error;
2450 }
2451 }
Steve Antondcc3c022017-12-22 16:02:54 -08002452 // Remove unused channels if MediaContentDescription is rejected.
2453 RemoveUnusedChannels(remote_description()->description());
2454 }
Steve Anton8a006912017-12-04 15:25:56 -08002455
Zhi Huange830e682018-03-30 10:48:35 -07002456 // NOTE: Candidates allocation will be initiated only when
2457 // SetLocalDescription is called.
2458 error = UpdateSessionState(type, cricket::CS_REMOTE,
2459 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002460 if (!error.ok()) {
2461 return error;
2462 }
2463
2464 if (local_description() &&
2465 !UseCandidatesInSessionDescription(remote_description())) {
2466 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2467 }
2468
2469 if (old_remote_description) {
2470 for (const cricket::ContentInfo& content :
2471 old_remote_description->description()->contents()) {
2472 // Check if this new SessionDescription contains new ICE ufrag and
2473 // password that indicates the remote peer requests an ICE restart.
2474 // TODO(deadbeef): When we start storing both the current and pending
2475 // remote description, this should reset pending_ice_restarts and compare
2476 // against the current description.
2477 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2478 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002479 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002480 pending_ice_restarts_.insert(content.name);
2481 }
2482 } else {
2483 // We retain all received candidates only if ICE is not restarted.
2484 // When ICE is restarted, all previous candidates belong to an old
2485 // generation and should not be kept.
2486 // TODO(deadbeef): This goes against the W3C spec which says the remote
2487 // description should only contain candidates from the last set remote
2488 // description plus any candidates added since then. We should remove
2489 // this once we're sure it won't break anything.
2490 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2491 old_remote_description, content.name, mutable_remote_description());
2492 }
2493 }
2494 }
2495
2496 if (session_error() != SessionError::kNone) {
2497 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2498 }
2499
2500 // Set the the ICE connection state to connecting since the connection may
2501 // become writable with peer reflexive candidates before any remote candidate
2502 // is signaled.
2503 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2504 // is to have a new signal the indicates a change in checking state from the
2505 // transport and expose a new checking() member from transport that can be
2506 // read to determine the current checking state. The existing SignalConnecting
2507 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002508 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002509 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002510 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2511 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2512 }
2513
deadbeefab9b2d12015-10-14 11:33:11 -07002514 // If setting the description decided our SSL role, allocate any necessary
2515 // SCTP sids.
2516 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002517 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002518 AllocateSctpSids(role);
2519 }
2520
Steve Antondcc3c022017-12-22 16:02:54 -08002521 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002522 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002523 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002524 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002526 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002527 for (auto transceiver : transceivers_) {
2528 const ContentInfo* content =
2529 FindMediaSectionForTransceiver(transceiver, remote_description());
2530 if (!content) {
2531 continue;
2532 }
2533 const MediaContentDescription* media_desc = content->media_description();
2534 RtpTransceiverDirection local_direction =
2535 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002536 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2537 // RTCSessionDescription: Set the associated remote streams given
2538 // transceiver.[[Receiver]], msids, addList, and removeList".
2539 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2540 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2541 std::vector<std::string> stream_ids;
2542 if (!media_desc->streams().empty()) {
2543 // The remote description has signaled the stream IDs.
2544 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002545 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002546 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2547 << " (" << GetStreamIdsString(stream_ids) << ").";
2548 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2549 stream_ids, &added_streams,
2550 &removed_streams);
2551 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2552 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2553 // and transceiver's current direction is neither sendrecv nor recvonly,
2554 // process the addition of a remote track for the media description.
2555 if (!transceiver->fired_direction() ||
2556 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2557 RTC_LOG(LS_INFO)
2558 << "Processing the addition of a remote track for MID="
2559 << content->name << ".";
2560 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002561 }
Steve Antondcc3c022017-12-22 16:02:54 -08002562 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002563 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2564 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2565 // removal of a remote track for the media description, given transceiver,
2566 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002567 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002568 (transceiver->fired_direction() &&
2569 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2570 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2571 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002572 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002573 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2574 transceiver->internal()->set_fired_direction(local_direction);
2575 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2576 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002577 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002578 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2579 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002580 transceiver->internal()->set_current_direction(local_direction);
2581 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002582 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2583 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002584 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002585 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2586 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002587 transceiver->Stop();
2588 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002589 if (!content->rejected &&
2590 RtpTransceiverDirectionHasRecv(local_direction)) {
2591 // Set ssrc to 0 in the case of an unsignalled ssrc.
2592 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002593 if (!media_desc->streams().empty() &&
2594 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002595 ssrc = media_desc->streams()[0].first_ssrc();
2596 }
2597 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002598 }
Steve Antondcc3c022017-12-22 16:02:54 -08002599 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002600 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002601 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002602 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002603 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002604 observer->OnTrack(transceiver);
2605 observer->OnAddTrack(transceiver->receiver(),
2606 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002607 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002608 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002609 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002610 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002611 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002612 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002613 }
2614 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002615 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002616 }
Steve Antondcc3c022017-12-22 16:02:54 -08002617 }
2618
Henrik Boströmfdb92012017-11-09 19:55:44 +01002619 const cricket::ContentInfo* audio_content =
2620 GetFirstAudioContent(remote_description()->description());
2621 const cricket::ContentInfo* video_content =
2622 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002623 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002624 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002625 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002626 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002627 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002628 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002629
2630 // Check if the descriptions include streams, just in case the peer supports
2631 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002632 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002633 (audio_desc && !audio_desc->streams().empty()) ||
2634 (video_desc && !video_desc->streams().empty())) {
2635 remote_peer_supports_msid_ = true;
2636 }
deadbeefab9b2d12015-10-14 11:33:11 -07002637
2638 // We wait to signal new streams until we finish processing the description,
2639 // since only at that point will new streams have all their tracks.
2640 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2641
Steve Antondcc3c022017-12-22 16:02:54 -08002642 if (!IsUnifiedPlan()) {
2643 // TODO(steveanton): When removing RTP senders/receivers in response to a
2644 // rejected media section, there is some cleanup logic that expects the
2645 // voice/ video channel to still be set. But in this method the voice/video
2646 // channel would have been destroyed by the SetRemoteDescription caller
2647 // above so the cleanup that relies on them fails to run. The RemoveSenders
2648 // calls should be moved to right before the DestroyChannel calls to fix
2649 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002650
Steve Antondcc3c022017-12-22 16:02:54 -08002651 // Find all audio rtp streams and create corresponding remote AudioTracks
2652 // and MediaStreams.
2653 if (audio_content) {
2654 if (audio_content->rejected) {
2655 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2656 } else {
2657 bool default_audio_track_needed =
2658 !remote_peer_supports_msid_ &&
2659 RtpTransceiverDirectionHasSend(audio_desc->direction());
2660 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2661 default_audio_track_needed, audio_desc->type(),
2662 new_streams);
2663 }
deadbeeffaac4972015-11-12 15:33:07 -08002664 }
deadbeefab9b2d12015-10-14 11:33:11 -07002665
Steve Antondcc3c022017-12-22 16:02:54 -08002666 // Find all video rtp streams and create corresponding remote VideoTracks
2667 // and MediaStreams.
2668 if (video_content) {
2669 if (video_content->rejected) {
2670 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2671 } else {
2672 bool default_video_track_needed =
2673 !remote_peer_supports_msid_ &&
2674 RtpTransceiverDirectionHasSend(video_desc->direction());
2675 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2676 default_video_track_needed, video_desc->type(),
2677 new_streams);
2678 }
deadbeeffaac4972015-11-12 15:33:07 -08002679 }
deadbeefab9b2d12015-10-14 11:33:11 -07002680
Steve Antondcc3c022017-12-22 16:02:54 -08002681 // Update the DataChannels with the information from the remote peer.
2682 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002683 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002684 cricket::kMediaProtocolRtpPrefix)) {
2685 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2686 }
deadbeefab9b2d12015-10-14 11:33:11 -07002687 }
deadbeefab9b2d12015-10-14 11:33:11 -07002688
Steve Antondcc3c022017-12-22 16:02:54 -08002689 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002690 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002691 for (size_t i = 0; i < new_streams->count(); ++i) {
2692 MediaStreamInterface* new_stream = new_streams->at(i);
2693 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002694 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002695 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2696 }
deadbeefab9b2d12015-10-14 11:33:11 -07002697
Steve Antondcc3c022017-12-22 16:02:54 -08002698 UpdateEndedRemoteMediaStreams();
2699 }
deadbeefab9b2d12015-10-14 11:33:11 -07002700
Steve Anton8a006912017-12-04 15:25:56 -08002701 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002702}
2703
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002704void PeerConnection::SetAssociatedRemoteStreams(
2705 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2706 const std::vector<std::string>& stream_ids,
2707 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2708 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2709 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2710 for (const std::string& stream_id : stream_ids) {
2711 rtc::scoped_refptr<MediaStreamInterface> stream =
2712 remote_streams_->find(stream_id);
2713 if (!stream) {
2714 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2715 MediaStream::Create(stream_id));
2716 remote_streams_->AddStream(stream);
2717 added_streams->push_back(stream);
2718 }
2719 media_streams.push_back(stream);
2720 }
2721 // Special case: "a=msid" missing, use random stream ID.
2722 if (media_streams.empty() &&
2723 !(remote_description()->description()->msid_signaling() &
2724 cricket::kMsidSignalingMediaSection)) {
2725 if (!missing_msid_default_stream_) {
2726 missing_msid_default_stream_ = MediaStreamProxy::Create(
2727 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2728 added_streams->push_back(missing_msid_default_stream_);
2729 }
2730 media_streams.push_back(missing_msid_default_stream_);
2731 }
2732 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2733 receiver->streams();
2734 // SetStreams() will add/remove the receiver's track to/from the streams. This
2735 // differs from the spec - the spec uses an "addList" and "removeList" to
2736 // update the stream-track relationships in a later step. We do this earlier,
2737 // changing the order of things, but the end-result is the same.
2738 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2739 // instead. https://crbug.com/webrtc/9480
2740 receiver->SetStreams(media_streams);
2741 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2742}
2743
Steve Anton0f5400a2018-07-17 14:25:36 -07002744void PeerConnection::ProcessRemovalOfRemoteTrack(
2745 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2746 transceiver,
2747 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2748 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2749 RTC_DCHECK(transceiver->mid());
2750 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2751 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002752 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002753 transceiver->internal()->receiver_internal()->streams();
2754 // This will remove the remote track from the streams.
2755 transceiver->internal()->receiver_internal()->set_stream_ids({});
2756 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002757 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2758}
2759
2760void PeerConnection::RemoveRemoteStreamsIfEmpty(
2761 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2762 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2763 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2764 // streams, see if the stream was removed by checking if this was the last
2765 // receiver with that stream ID.
2766 for (auto remote_stream : remote_streams) {
2767 if (remote_stream->GetAudioTracks().empty() &&
2768 remote_stream->GetVideoTracks().empty()) {
2769 remote_streams_->RemoveStream(remote_stream);
2770 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002771 }
2772 }
2773}
2774
Steve Antondcc3c022017-12-22 16:02:54 -08002775RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2776 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002777 const SessionDescriptionInterface& new_session,
2778 const SessionDescriptionInterface* old_local_description,
2779 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002780 RTC_DCHECK(IsUnifiedPlan());
2781
Steve Anton7464fca2018-01-19 11:10:37 -08002782 const cricket::ContentGroup* bundle_group = nullptr;
2783 if (new_session.GetType() == SdpType::kOffer) {
2784 auto bundle_group_or_error =
2785 GetEarlyBundleGroup(*new_session.description());
2786 if (!bundle_group_or_error.ok()) {
2787 return bundle_group_or_error.MoveError();
2788 }
2789 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002790 }
Steve Antondcc3c022017-12-22 16:02:54 -08002791
Steve Antondcc3c022017-12-22 16:02:54 -08002792 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002793 for (size_t i = 0; i < new_contents.size(); ++i) {
2794 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002795 cricket::MediaType media_type = new_content.media_description()->type();
2796 seen_mids_.insert(new_content.name);
2797 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2798 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002799 const cricket::ContentInfo* old_local_content = nullptr;
2800 if (old_local_description &&
2801 i < old_local_description->description()->contents().size()) {
2802 old_local_content =
2803 &old_local_description->description()->contents()[i];
2804 }
2805 const cricket::ContentInfo* old_remote_content = nullptr;
2806 if (old_remote_description &&
2807 i < old_remote_description->description()->contents().size()) {
2808 old_remote_content =
2809 &old_remote_description->description()->contents()[i];
2810 }
Steve Antondcc3c022017-12-22 16:02:54 -08002811 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002812 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2813 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002814 if (!transceiver_or_error.ok()) {
2815 return transceiver_or_error.MoveError();
2816 }
2817 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002818 RTCError error =
2819 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2820 if (!error.ok()) {
2821 return error;
2822 }
2823 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002824 if (GetDataMid() && new_content.name != *GetDataMid()) {
2825 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002826 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2827 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002828 continue;
2829 }
2830 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2831 if (!error.ok()) {
2832 return error;
2833 }
Steve Antondcc3c022017-12-22 16:02:54 -08002834 } else {
2835 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2836 "Unknown section type.");
2837 }
2838 }
2839
2840 return RTCError::OK();
2841}
2842
2843RTCError PeerConnection::UpdateTransceiverChannel(
2844 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2845 transceiver,
2846 const cricket::ContentInfo& content,
2847 const cricket::ContentGroup* bundle_group) {
2848 RTC_DCHECK(IsUnifiedPlan());
2849 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002850 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002851 if (content.rejected) {
2852 if (channel) {
2853 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002854 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002855 }
2856 } else {
2857 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002858 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002859 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002860 } else {
Steve Anton69470252018-02-09 11:43:08 -08002861 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002862 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002863 }
2864 if (!channel) {
2865 LOG_AND_RETURN_ERROR(
2866 RTCErrorType::INTERNAL_ERROR,
2867 "Failed to create channel for mid=" + content.name);
2868 }
2869 transceiver->internal()->SetChannel(channel);
2870 }
2871 }
2872 return RTCError::OK();
2873}
2874
Steve Antonfa2260d2017-12-28 16:38:23 -08002875RTCError PeerConnection::UpdateDataChannel(
2876 cricket::ContentSource source,
2877 const cricket::ContentInfo& content,
2878 const cricket::ContentGroup* bundle_group) {
2879 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002880 // If data channels are disabled, ignore this media section. CreateAnswer
2881 // will take care of rejecting it.
2882 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002883 }
2884 if (content.rejected) {
2885 DestroyDataChannel();
2886 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002887 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002888 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002889 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2890 "Failed to create data channel.");
2891 }
2892 }
2893 if (source == cricket::CS_REMOTE) {
2894 const MediaContentDescription* data_desc = content.media_description();
2895 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2896 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2897 }
2898 }
2899 }
2900 return RTCError::OK();
2901}
2902
Steve Antondcc3c022017-12-22 16:02:54 -08002903RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2904PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002905 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002906 size_t mline_index,
2907 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002908 const ContentInfo* old_local_content,
2909 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002910 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002911 // If this is an offer then the m= section might be recycled. If the m=
2912 // section is being recycled (defined as: rejected in the current local or
2913 // remote description and not rejected in new description), dissociate the
2914 // currently associated RtpTransceiver by setting its mid property to null,
2915 // and discard the mapping between the transceiver and its m= section index.
2916 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2917 old_remote_content)) {
2918 // We want to dissociate the transceiver that has the rejected mid.
2919 const std::string& old_mid =
2920 (old_local_content && old_local_content->rejected)
2921 ? old_local_content->name
2922 : old_remote_content->name;
2923 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002924 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002925 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2926 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002927 old_transceiver->internal()->set_mid(absl::nullopt);
2928 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002929 }
2930 }
2931 const MediaContentDescription* media_desc = content.media_description();
2932 auto transceiver = GetAssociatedTransceiver(content.name);
2933 if (source == cricket::CS_LOCAL) {
2934 // Find the RtpTransceiver that corresponds to this m= section, using the
2935 // mapping between transceivers and m= section indices established when
2936 // creating the offer.
2937 if (!transceiver) {
2938 transceiver = GetTransceiverByMLineIndex(mline_index);
2939 }
2940 if (!transceiver) {
2941 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2942 "Unknown transceiver");
2943 }
2944 } else {
2945 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2946 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2947 // of the same type...
2948 if (!transceiver &&
2949 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2950 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2951 }
2952 // If no RtpTransceiver was found in the previous step, create one with a
2953 // recvonly direction.
2954 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002955 RTC_LOG(LS_INFO) << "Adding "
2956 << cricket::MediaTypeToString(media_desc->type())
2957 << " transceiver for MID=" << content.name
2958 << " at i=" << mline_index
2959 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002960 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002961 auto sender =
2962 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002963 std::string receiver_id;
2964 if (!media_desc->streams().empty()) {
2965 receiver_id = media_desc->streams()[0].id;
2966 } else {
2967 receiver_id = rtc::CreateRandomUuid();
2968 }
2969 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002970 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002971 transceiver->internal()->set_direction(
2972 RtpTransceiverDirection::kRecvOnly);
2973 }
2974 }
2975 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002976 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002977 LOG_AND_RETURN_ERROR(
2978 RTCErrorType::INVALID_PARAMETER,
2979 "Transceiver type does not match media description type.");
2980 }
2981 // Associate the found or created RtpTransceiver with the m= section by
2982 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2983 // section, and establish a mapping between the transceiver and the index of
2984 // the m= section.
2985 transceiver->internal()->set_mid(content.name);
2986 transceiver->internal()->set_mline_index(mline_index);
2987 return std::move(transceiver);
2988}
2989
2990rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2991PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2992 RTC_DCHECK(IsUnifiedPlan());
2993 for (auto transceiver : transceivers_) {
2994 if (transceiver->mid() == mid) {
2995 return transceiver;
2996 }
2997 }
2998 return nullptr;
2999}
3000
3001rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3002PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3003 RTC_DCHECK(IsUnifiedPlan());
3004 for (auto transceiver : transceivers_) {
3005 if (transceiver->internal()->mline_index() == mline_index) {
3006 return transceiver;
3007 }
3008 }
3009 return nullptr;
3010}
3011
3012rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3013PeerConnection::FindAvailableTransceiverToReceive(
3014 cricket::MediaType media_type) const {
3015 RTC_DCHECK(IsUnifiedPlan());
3016 // From JSEP section 5.10 (Applying a Remote Description):
3017 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3018 // the same type that were added to the PeerConnection by addTrack and are not
3019 // associated with any m= section and are not stopped, find the first such
3020 // RtpTransceiver.
3021 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003022 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003023 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3024 !transceiver->stopped()) {
3025 return transceiver;
3026 }
3027 }
3028 return nullptr;
3029}
3030
Steve Antoned10bd92017-12-05 10:52:59 -08003031const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3032 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3033 transceiver,
3034 const SessionDescriptionInterface* sdesc) const {
3035 RTC_DCHECK(transceiver);
3036 RTC_DCHECK(sdesc);
3037 if (IsUnifiedPlan()) {
3038 if (!transceiver->internal()->mid()) {
3039 // This transceiver is not associated with a media section yet.
3040 return nullptr;
3041 }
3042 return sdesc->description()->GetContentByName(
3043 *transceiver->internal()->mid());
3044 } else {
3045 // Plan B only allows at most one audio and one video section, so use the
3046 // first media section of that type.
3047 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003048 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003049 }
3050}
3051
deadbeef46c73892016-11-16 19:42:04 -08003052PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3053 return configuration_;
3054}
3055
deadbeef293e9262017-01-11 12:28:30 -08003056bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3057 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003058 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003059 if (IsClosed()) {
3060 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3061 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3062 }
3063
Qingsi Wanga2d60672018-04-11 16:57:45 -07003064 // According to JSEP, after setLocalDescription, changing the candidate pool
3065 // size is not allowed, and changing the set of ICE servers will not result
3066 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003067 if (local_description() && configuration.ice_candidate_pool_size !=
3068 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003069 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3070 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003071 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003072 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003073
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003074 if (local_description() &&
3075 configuration.use_media_transport != configuration_.use_media_transport) {
3076 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3077 "SetLocalDescription.";
3078 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3079 }
3080
3081 if (remote_description() &&
3082 configuration.use_media_transport != configuration_.use_media_transport) {
3083 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3084 "SetRemoteDescription.";
3085 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3086 }
3087
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003088 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003089 configuration.use_media_transport_for_data_channels !=
3090 configuration_.use_media_transport_for_data_channels) {
3091 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3092 "after calling SetLocalDescription.";
3093 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3094 }
3095
3096 if (remote_description() &&
3097 configuration.use_media_transport_for_data_channels !=
3098 configuration_.use_media_transport_for_data_channels) {
3099 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3100 "after calling SetRemoteDescription.";
3101 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3102 }
3103
3104 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003105 configuration.crypto_options != configuration_.crypto_options) {
3106 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3107 "SetLocalDescription.";
3108 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3109 }
3110
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003111 if (configuration.use_media_transport_for_data_channels ||
3112 configuration.use_media_transport) {
3113 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3114 << "Media transport requires MaxBundle policy.";
3115 }
3116
deadbeef293e9262017-01-11 12:28:30 -08003117 // The simplest (and most future-compatible) way to tell if the config was
3118 // modified in an invalid way is to copy each property we do support
3119 // modifying, then use operator==. There are far more properties we don't
3120 // support modifying than those we do, and more could be added.
3121 RTCConfiguration modified_config = configuration_;
3122 modified_config.servers = configuration.servers;
3123 modified_config.type = configuration.type;
3124 modified_config.ice_candidate_pool_size =
3125 configuration.ice_candidate_pool_size;
3126 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003127 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003128 modified_config.ice_check_interval_strong_connectivity =
3129 configuration.ice_check_interval_strong_connectivity;
3130 modified_config.ice_check_interval_weak_connectivity =
3131 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003132 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3133 modified_config.ice_unwritable_min_checks =
3134 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003135 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003136 modified_config.stun_candidate_keepalive_interval =
3137 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003138 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003139 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003140 modified_config.active_reset_srtp_params =
3141 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003142 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003143 modified_config.use_media_transport_for_data_channels =
3144 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003145 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003146 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003147 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3148 }
3149
Steve Anton038834f2017-07-14 15:59:59 -07003150 // Validate the modified configuration.
3151 RTCError validate_error = ValidateConfiguration(modified_config);
3152 if (!validate_error.ok()) {
3153 return SafeSetError(std::move(validate_error), error);
3154 }
3155
deadbeef293e9262017-01-11 12:28:30 -08003156 // Note that this isn't possible through chromium, since it's an unsigned
3157 // short in WebIDL.
3158 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003159 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003160 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3161 }
3162
3163 // Parse ICE servers before hopping to network thread.
3164 cricket::ServerAddresses stun_servers;
3165 std::vector<cricket::RelayServerConfig> turn_servers;
3166 RTCErrorType parse_error =
3167 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3168 if (parse_error != RTCErrorType::NONE) {
3169 return SafeSetError(parse_error, error);
3170 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003171 // Note if STUN or TURN servers were supplied.
3172 if (!stun_servers.empty()) {
3173 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3174 }
3175 if (!turn_servers.empty()) {
3176 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3177 }
deadbeef293e9262017-01-11 12:28:30 -08003178
3179 // In theory this shouldn't fail.
3180 if (!network_thread()->Invoke<bool>(
3181 RTC_FROM_HERE,
3182 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3183 stun_servers, turn_servers, modified_config.type,
3184 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003185 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003186 modified_config.turn_customizer,
3187 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003188 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003189 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3190 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003191
deadbeefd1a38b52016-12-10 13:15:33 -08003192 // As described in JSEP, calling setConfiguration with new ICE servers or
3193 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3194 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003195 if (modified_config.servers != configuration_.servers ||
3196 modified_config.type != configuration_.type ||
3197 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003198 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003199 }
skvladd1f5fda2017-02-03 16:54:05 -08003200
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003201 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003202 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003203 modified_config.use_media_transport ||
3204 modified_config.use_media_transport_for_data_channels
3205 ? factory_->media_transport_factory()
3206 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003207
Zhi Huangb57e1692018-06-12 11:41:11 -07003208 if (configuration_.active_reset_srtp_params !=
3209 modified_config.active_reset_srtp_params) {
3210 transport_controller_->SetActiveResetSrtpParams(
3211 modified_config.active_reset_srtp_params);
3212 }
3213
deadbeef293e9262017-01-11 12:28:30 -08003214 configuration_ = modified_config;
3215 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003216}
3217
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003218bool PeerConnection::AddIceCandidate(
3219 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003220 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003221 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003222 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003223 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003224 return false;
3225 }
Steve Antond25da372017-11-06 14:50:29 -08003226
3227 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003228 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003229 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003230 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003231 return false;
3232 }
3233
3234 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003235 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003236 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003237 return false;
3238 }
3239
3240 bool valid = false;
3241 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3242 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003243 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003244 return false;
3245 }
3246
3247 // Add this candidate to the remote session description.
3248 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003249 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003250 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003251 return false;
3252 }
3253
3254 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003255 bool result = UseCandidate(ice_candidate);
3256 if (result) {
3257 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3258 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3259 } else {
3260 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3261 }
3262 return result;
Steve Antond25da372017-11-06 14:50:29 -08003263 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003264 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003265 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003266 return true;
3267 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003268}
3269
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003270bool PeerConnection::RemoveIceCandidates(
3271 const std::vector<cricket::Candidate>& candidates) {
3272 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003273 if (IsClosed()) {
3274 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3275 return false;
3276 }
3277
Steve Antond25da372017-11-06 14:50:29 -08003278 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003279 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3280 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003281 return false;
3282 }
3283
3284 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003285 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003286 return false;
3287 }
3288
3289 size_t number_removed =
3290 mutable_remote_description()->RemoveCandidates(candidates);
3291 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003292 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003293 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003294 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003295 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003296 }
3297
3298 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003299 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3300 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003301 RTC_LOG(LS_ERROR)
3302 << "RemoveIceCandidates: Error when removing remote candidates: "
3303 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003304 }
3305 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003306}
3307
Niels Möller0c4f7be2018-05-07 14:01:37 +02003308RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003309 if (!worker_thread()->IsCurrent()) {
3310 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003311 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003312 }
3313
Niels Möller0c4f7be2018-05-07 14:01:37 +02003314 const bool has_min = bitrate.min_bitrate_bps.has_value();
3315 const bool has_start = bitrate.start_bitrate_bps.has_value();
3316 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003317 if (has_min && *bitrate.min_bitrate_bps < 0) {
3318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3319 "min_bitrate_bps <= 0");
3320 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003321 if (has_start) {
3322 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003324 "start_bitrate_bps < min_bitrate_bps");
3325 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003326 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3327 "curent_bitrate_bps < 0");
3328 }
3329 }
3330 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003331 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003332 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003333 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003334 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3336 "max_bitrate_bps < min_bitrate_bps");
3337 } else if (*bitrate.max_bitrate_bps < 0) {
3338 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3339 "max_bitrate_bps < 0");
3340 }
3341 }
3342
zstein4b979802017-06-02 14:37:37 -07003343 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003344 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003345
3346 return RTCError::OK();
3347}
3348
Alex Narest78609d52017-10-20 10:37:47 +02003349void PeerConnection::SetBitrateAllocationStrategy(
3350 std::unique_ptr<rtc::BitrateAllocationStrategy>
3351 bitrate_allocation_strategy) {
3352 rtc::Thread* worker_thread = factory_->worker_thread();
3353 if (!worker_thread->IsCurrent()) {
3354 rtc::BitrateAllocationStrategy* strategy_raw =
3355 bitrate_allocation_strategy.release();
3356 auto functor = [this, strategy_raw]() {
3357 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003358 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003359 };
3360 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3361 return;
3362 }
3363 RTC_DCHECK(call_.get());
3364 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3365}
3366
henrika5f6bf242017-11-01 11:06:56 +01003367void PeerConnection::SetAudioPlayout(bool playout) {
3368 if (!worker_thread()->IsCurrent()) {
3369 worker_thread()->Invoke<void>(
3370 RTC_FROM_HERE,
3371 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3372 return;
3373 }
3374 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003375 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003376 audio_state->SetPlayout(playout);
3377}
3378
3379void PeerConnection::SetAudioRecording(bool recording) {
3380 if (!worker_thread()->IsCurrent()) {
3381 worker_thread()->Invoke<void>(
3382 RTC_FROM_HERE,
3383 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3384 return;
3385 }
3386 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003387 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003388 audio_state->SetRecording(recording);
3389}
3390
Steve Anton8c0f7a72017-10-03 10:03:10 -07003391std::unique_ptr<rtc::SSLCertificate>
3392PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003393 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3394 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003395 return nullptr;
3396 }
Steve Antonf25303e2018-10-16 15:23:31 -07003397 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003398}
3399
Zhi Huang70b820f2018-01-27 14:16:15 -08003400std::unique_ptr<rtc::SSLCertChain>
3401PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003402 auto audio_transceiver = GetFirstAudioTransceiver();
3403 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003404 return nullptr;
3405 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003406 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003407 audio_transceiver->internal()->channel()->transport_name());
3408}
3409
3410rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3411PeerConnection::GetFirstAudioTransceiver() const {
3412 for (auto transceiver : transceivers_) {
3413 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3414 return transceiver;
3415 }
3416 }
3417 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003418}
3419
ivoc14d5dbe2016-07-04 07:06:55 -07003420bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3421 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003422 // TODO(eladalon): It would be better to not allow negative values into PC.
3423 const size_t max_size = (max_size_bytes < 0)
3424 ? RtcEventLog::kUnlimitedOutput
3425 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003426 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3427 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3428 output_period_ms = 5000;
3429 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003430 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003431 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003432 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003433}
3434
Bjorn Tereliusde939432017-11-20 17:38:14 +01003435bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3436 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003437 // TODO(eladalon): In C++14, this can be done with a lambda.
3438 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003439 bool operator()() {
3440 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3441 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003442 PeerConnection* const pc;
3443 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003444 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003445 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003446 return worker_thread()->Invoke<bool>(
3447 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003448}
3449
3450void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003451 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003452 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3453}
3454
Harald Alvestrandad88c882018-11-28 16:47:46 +01003455rtc::scoped_refptr<DtlsTransportInterface>
3456PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3457 return transport_controller_->LookupDtlsTransportByMid(mid);
3458}
3459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003461 return pending_local_description_ ? pending_local_description_.get()
3462 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003463}
3464
3465const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003466 return pending_remote_description_ ? pending_remote_description_.get()
3467 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003468}
3469
deadbeeffe4a8a42016-12-20 17:56:17 -08003470const SessionDescriptionInterface* PeerConnection::current_local_description()
3471 const {
Steve Anton75737c02017-11-06 10:37:17 -08003472 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003473}
3474
3475const SessionDescriptionInterface* PeerConnection::current_remote_description()
3476 const {
Steve Anton75737c02017-11-06 10:37:17 -08003477 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003478}
3479
3480const SessionDescriptionInterface* PeerConnection::pending_local_description()
3481 const {
Steve Anton75737c02017-11-06 10:37:17 -08003482 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003483}
3484
3485const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3486 const {
Steve Anton75737c02017-11-06 10:37:17 -08003487 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003488}
3489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003490void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003491 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492 // Update stats here so that we have the most recent stats for tracks and
3493 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003494 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495
Steve Anton75737c02017-11-06 10:37:17 -08003496 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003497 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003498
Steve Anton8af21862017-12-15 11:20:13 -08003499 for (auto transceiver : transceivers_) {
3500 transceiver->Stop();
3501 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003502
3503 // Ensure that all asynchronous stats requests are completed before destroying
3504 // the transport controller below.
3505 if (stats_collector_) {
3506 stats_collector_->WaitForPendingRequest();
3507 }
3508
3509 // Don't destroy BaseChannels until after stats has been cleaned up so that
3510 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003511 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003512
Qingsi Wang93a84392018-01-30 17:13:09 -08003513 // The event log is used in the transport controller, which must be outlived
3514 // by the former. CreateOffer by the peer connection is implemented
3515 // asynchronously and if the peer connection is closed without resetting the
3516 // WebRTC session description factory, the session description factory would
3517 // call the transport controller.
3518 webrtc_session_desc_factory_.reset();
3519 transport_controller_.reset();
3520
deadbeef42a42632017-03-10 15:18:00 -08003521 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003522 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3523 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003524
Steve Anton978b8762017-09-29 12:15:02 -07003525 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003526 call_.reset();
3527 // The event log must outlive call (and any other object that uses it).
3528 event_log_.reset();
3529 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003530 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003531 // The .h file says that observer can be discarded after close() returns.
3532 // Make sure this is true.
3533 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534}
3535
Steve Antonad182762018-09-05 20:22:40 +00003536void PeerConnection::OnMessage(rtc::Message* msg) {
3537 switch (msg->message_id) {
3538 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3539 SetSessionDescriptionMsg* param =
3540 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3541 param->observer->OnSuccess();
3542 delete param;
3543 break;
3544 }
3545 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3546 SetSessionDescriptionMsg* param =
3547 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3548 param->observer->OnFailure(std::move(param->error));
3549 delete param;
3550 break;
3551 }
3552 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3553 CreateSessionDescriptionMsg* param =
3554 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3555 param->observer->OnFailure(std::move(param->error));
3556 delete param;
3557 break;
3558 }
3559 case MSG_GETSTATS: {
3560 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3561 StatsReports reports;
3562 stats_->GetStats(param->track, &reports);
3563 param->observer->OnComplete(reports);
3564 delete param;
3565 break;
3566 }
3567 case MSG_FREE_DATACHANNELS: {
3568 sctp_data_channels_to_free_.clear();
3569 break;
3570 }
3571 case MSG_REPORT_USAGE_PATTERN: {
3572 ReportUsagePattern();
3573 break;
3574 }
3575 default:
3576 RTC_NOTREACHED() << "Not implemented";
3577 break;
3578 }
3579}
3580
Steve Antonafb0bb72018-02-20 11:35:37 -08003581cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3582 RTC_DCHECK(!IsUnifiedPlan());
3583 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3584 GetAudioTransceiver()->internal()->channel());
3585 if (voice_channel) {
3586 return voice_channel->media_channel();
3587 } else {
3588 return nullptr;
3589 }
3590}
3591
3592cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3593 RTC_DCHECK(!IsUnifiedPlan());
3594 auto* video_channel = static_cast<cricket::VideoChannel*>(
3595 GetVideoTransceiver()->internal()->channel());
3596 if (video_channel) {
3597 return video_channel->media_channel();
3598 } else {
3599 return nullptr;
3600 }
3601}
3602
Steve Anton4171afb2017-11-20 10:20:22 -08003603void PeerConnection::CreateAudioReceiver(
3604 MediaStreamInterface* stream,
3605 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003606 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3607 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003608 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3609 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003610 auto* audio_receiver = new AudioRtpReceiver(
3611 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003612 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003613 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3614 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3615 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003616 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003617 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003618 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003619}
3620
Steve Anton4171afb2017-11-20 10:20:22 -08003621void PeerConnection::CreateVideoReceiver(
3622 MediaStreamInterface* stream,
3623 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003624 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3625 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003626 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3627 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003628 auto* video_receiver = new VideoRtpReceiver(
3629 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003630 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003631 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3632 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3633 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003634 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003635 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003636 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003637}
3638
deadbeef70ab1a12015-09-28 16:53:55 -07003639// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3640// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003641rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003642 const RtpSenderInfo& remote_sender_info) {
3643 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3644 if (!receiver) {
3645 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3646 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003647 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003648 }
Steve Anton4171afb2017-11-20 10:20:22 -08003649 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3650 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3651 } else {
3652 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3653 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003654 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003655}
3656
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003657void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3658 MediaStreamInterface* stream) {
3659 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003660 RTC_DCHECK(track);
3661 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003662 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003663 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003664 // We already have a sender for this track, so just change the stream_id
3665 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003666 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003667 return;
3668 }
3669
3670 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003671 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003672 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003673 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003674 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003675 // If the sender has already been configured in SDP, we call SetSsrc,
3676 // which will connect the sender to the underlying transport. This can
3677 // occur if a local session description that contains the ID of the sender
3678 // is set before AddStream is called. It can also occur if the local
3679 // session description is not changed and RemoveStream is called, and
3680 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003681 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003682 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003683 if (sender_info) {
3684 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003685 }
3686}
3687
3688// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3689// indefinitely, when we have unified plan SDP.
3690void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3691 MediaStreamInterface* stream) {
3692 RTC_DCHECK(!IsClosed());
3693 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003694 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003695 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3696 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003697 return;
3698 }
Steve Anton4171afb2017-11-20 10:20:22 -08003699 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003700}
3701
3702void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3703 MediaStreamInterface* stream) {
3704 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003705 RTC_DCHECK(track);
3706 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003707 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003708 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003709 // We already have a sender for this track, so just change the stream_id
3710 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003711 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003712 return;
3713 }
3714
3715 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003716 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003717 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003718 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003719 GetVideoTransceiver()->internal()->AddSender(new_sender);
3720 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003721 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003722 if (sender_info) {
3723 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003724 }
3725}
3726
3727void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3728 MediaStreamInterface* stream) {
3729 RTC_DCHECK(!IsClosed());
3730 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003731 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003732 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3733 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003734 return;
3735 }
Steve Anton4171afb2017-11-20 10:20:22 -08003736 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003737}
3738
Steve Antonba818672017-11-06 10:21:57 -08003739void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003740 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003741 if (ice_connection_state_ == new_state) {
3742 return;
3743 }
3744
deadbeefcbecd352015-09-23 11:50:27 -07003745 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003746 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003747 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003748 return;
3749 }
Steve Antonba818672017-11-06 10:21:57 -08003750
Mirko Bonadei675513b2017-11-09 11:09:25 +01003751 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3752 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003753 RTC_DCHECK(ice_connection_state_ !=
3754 PeerConnectionInterface::kIceConnectionClosed);
3755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003756 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003757 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003758}
3759
Alex Loiko9289eda2018-11-23 16:18:59 +00003760void PeerConnection::SetStandardizedIceConnectionState(
3761 PeerConnectionInterface::IceConnectionState new_state) {
3762 RTC_DCHECK(signaling_thread()->IsCurrent());
3763 if (standardized_ice_connection_state_ == new_state)
3764 return;
3765 if (IsClosed())
3766 return;
3767 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003768 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003769}
3770
Jonas Olsson635474e2018-10-18 15:58:17 +02003771void PeerConnection::SetConnectionState(
3772 PeerConnectionInterface::PeerConnectionState new_state) {
3773 RTC_DCHECK(signaling_thread()->IsCurrent());
3774 if (connection_state_ == new_state)
3775 return;
3776 if (IsClosed())
3777 return;
3778 connection_state_ = new_state;
3779 Observer()->OnConnectionChange(new_state);
3780}
3781
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003782void PeerConnection::OnIceGatheringChange(
3783 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003784 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003785 if (IsClosed()) {
3786 return;
3787 }
3788 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003789 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003790}
3791
jbauch81bf7b02017-03-25 08:31:12 -07003792void PeerConnection::OnIceCandidate(
3793 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003794 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003795 if (IsClosed()) {
3796 return;
3797 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003798 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003799 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3800 candidate->candidate().address().IsPrivateIP()) {
3801 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3802 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003803 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003804}
3805
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003806void PeerConnection::OnIceCandidatesRemoved(
3807 const std::vector<cricket::Candidate>& candidates) {
3808 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003809 if (IsClosed()) {
3810 return;
3811 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003812 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003813}
3814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003815void PeerConnection::ChangeSignalingState(
3816 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003817 RTC_DCHECK(signaling_thread()->IsCurrent());
3818 if (signaling_state_ == signaling_state) {
3819 return;
3820 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003821 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3822 << GetSignalingStateString(signaling_state_)
3823 << " New state: "
3824 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003825 signaling_state_ = signaling_state;
3826 if (signaling_state == kClosed) {
3827 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003828 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003829 standardized_ice_connection_state_ =
3830 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003831 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3832 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003833 if (ice_gathering_state_ != kIceGatheringComplete) {
3834 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003835 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003836 }
3837 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003838 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003839}
3840
deadbeefeb459812015-12-15 19:24:43 -08003841void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3842 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003843 if (IsClosed()) {
3844 return;
3845 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003846 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003847 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003848}
3849
deadbeefeb459812015-12-15 19:24:43 -08003850void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3851 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003852 if (IsClosed()) {
3853 return;
3854 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003855 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003856 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003857}
3858
3859void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3860 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003861 if (IsClosed()) {
3862 return;
3863 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003864 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003865 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003866}
3867
3868void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3869 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003870 if (IsClosed()) {
3871 return;
3872 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003873 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003874 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003875}
3876
Henrik Boström31638672017-11-23 17:48:32 +01003877void PeerConnection::PostSetSessionDescriptionSuccess(
3878 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003879 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3880 signaling_thread()->Post(RTC_FROM_HERE, this,
3881 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003882}
3883
deadbeefab9b2d12015-10-14 11:33:11 -07003884void PeerConnection::PostSetSessionDescriptionFailure(
3885 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003886 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003887 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003888 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3889 msg->error = std::move(error);
3890 signaling_thread()->Post(RTC_FROM_HERE, this,
3891 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003892}
3893
3894void PeerConnection::PostCreateSessionDescriptionFailure(
3895 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003896 RTCError error) {
3897 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003898 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3899 msg->error = std::move(error);
3900 signaling_thread()->Post(RTC_FROM_HERE, this,
3901 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003902}
3903
zhihuang1c378ed2017-08-17 14:10:50 -07003904void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003905 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003906 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003907 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003908
Steve Antondcc3c022017-12-22 16:02:54 -08003909 if (IsUnifiedPlan()) {
3910 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3911 } else {
3912 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3913 }
3914
Steve Antonfa2260d2017-12-28 16:38:23 -08003915 // Intentionally unset the data channel type for RTP data channel with the
3916 // second condition. Otherwise the RTP data channels would be successfully
3917 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3918 // when building with chromium. We want to leave RTP data channels broken, so
3919 // people won't try to use them.
3920 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3921 session_options->data_channel_type = data_channel_type();
3922 }
3923
Steve Antondcc3c022017-12-22 16:02:54 -08003924 // Apply ICE restart flag and renomination flag.
3925 for (auto& options : session_options->media_description_options) {
3926 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3927 options.transport_options.enable_ice_renomination =
3928 configuration_.enable_ice_renomination;
3929 }
3930
3931 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003932 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003933 session_options->pooled_ice_credentials =
3934 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3935 RTC_FROM_HERE,
3936 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3937 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003938 session_options->offer_extmap_allow_mixed =
3939 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003940}
3941
3942void PeerConnection::GetOptionsForPlanBOffer(
3943 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3944 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003945 // Figure out transceiver directional preferences.
3946 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3947 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3948
3949 // By default, generate sendrecv/recvonly m= sections.
3950 bool recv_audio = true;
3951 bool recv_video = true;
3952
3953 // By default, only offer a new m= section if we have media to send with it.
3954 bool offer_new_audio_description = send_audio;
3955 bool offer_new_video_description = send_video;
3956 bool offer_new_data_description = HasDataChannels();
3957
3958 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003959 if (offer_answer_options.offer_to_receive_audio !=
3960 RTCOfferAnswerOptions::kUndefined) {
3961 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003962 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003963 offer_new_audio_description ||
3964 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003965 }
Steve Antondcc3c022017-12-22 16:02:54 -08003966 if (offer_answer_options.offer_to_receive_video !=
3967 RTCOfferAnswerOptions::kUndefined) {
3968 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003969 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003970 offer_new_video_description ||
3971 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003972 }
3973
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003974 absl::optional<size_t> audio_index;
3975 absl::optional<size_t> video_index;
3976 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003977 // If a current description exists, generate m= sections in the same order,
3978 // using the first audio/video/data section that appears and rejecting
3979 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003980 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003981 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003982 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003983 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3984 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3985 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003986 }
3987
zhihuang1c378ed2017-08-17 14:10:50 -07003988 // Add audio/video/data m= sections to the end if needed.
3989 if (!audio_index && offer_new_audio_description) {
3990 session_options->media_description_options.push_back(
3991 cricket::MediaDescriptionOptions(
3992 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003993 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3994 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003995 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003996 }
zhihuang1c378ed2017-08-17 14:10:50 -07003997 if (!video_index && offer_new_video_description) {
3998 session_options->media_description_options.push_back(
3999 cricket::MediaDescriptionOptions(
4000 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004001 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4002 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004003 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004004 }
zhihuang1c378ed2017-08-17 14:10:50 -07004005 if (!data_index && offer_new_data_description) {
4006 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004007 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004008 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004009 }
4010
4011 cricket::MediaDescriptionOptions* audio_media_description_options =
4012 !audio_index ? nullptr
4013 : &session_options->media_description_options[*audio_index];
4014 cricket::MediaDescriptionOptions* video_media_description_options =
4015 !video_index ? nullptr
4016 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004017
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004018 AddPlanBRtpSenderOptions(GetSendersInternal(),
4019 audio_media_description_options,
4020 video_media_description_options,
4021 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004022}
4023
Steve Antondcc3c022017-12-22 16:02:54 -08004024static cricket::MediaDescriptionOptions
4025GetMediaDescriptionOptionsForTransceiver(
4026 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4027 transceiver,
4028 const std::string& mid) {
4029 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004030 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004031 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004032 // This behavior is specified in JSEP. The gist is that:
4033 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4034 // sendrecv.
4035 // 2. If the MSID is included, then it must be included in any subsequent
4036 // offer/answer exactly the same until the RtpTransceiver is stopped.
4037 if (!transceiver->stopped() &&
4038 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4039 transceiver->internal()->has_ever_been_used_to_send())) {
4040 cricket::SenderOptions sender_options;
4041 sender_options.track_id = transceiver->sender()->id();
4042 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004043 int num_send_encoding_layers =
4044 transceiver->sender()->init_send_encodings().size();
4045 sender_options.num_sim_layers =
4046 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004047 media_description_options.sender_options.push_back(sender_options);
4048 }
Steve Antondcc3c022017-12-22 16:02:54 -08004049 return media_description_options;
4050}
4051
Steve Anton5c72e712018-12-10 14:25:30 -08004052// Returns the ContentInfo at mline index |i|, or null if none exists.
4053static const ContentInfo* GetContentByIndex(
4054 const SessionDescriptionInterface* sdesc,
4055 size_t i) {
4056 if (!sdesc) {
4057 return nullptr;
4058 }
4059 const ContentInfos& contents = sdesc->description()->contents();
4060 return (i < contents.size() ? &contents[i] : nullptr);
4061}
4062
Steve Antondcc3c022017-12-22 16:02:54 -08004063void PeerConnection::GetOptionsForUnifiedPlanOffer(
4064 const RTCOfferAnswerOptions& offer_answer_options,
4065 cricket::MediaSessionOptions* session_options) {
4066 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4067 // Offers) and 5.2.2 (Subsequent Offers).
4068 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4069 const ContentInfos& local_contents =
4070 (local_description() ? local_description()->description()->contents()
4071 : ContentInfos());
4072 const ContentInfos& remote_contents =
4073 (remote_description() ? remote_description()->description()->contents()
4074 : ContentInfos());
4075 // The mline indices that can be recycled. New transceivers should reuse these
4076 // slots first.
4077 std::queue<size_t> recycleable_mline_indices;
4078 // Track the MIDs used in previous offer/answer exchanges and the current
4079 // offer so that new, unique MIDs are generated.
4080 std::set<std::string> used_mids = seen_mids_;
4081 // First, go through each media section that exists in either the local or
4082 // remote description and generate a media section in this offer for the
4083 // associated transceiver. If a media section can be recycled, generate a
4084 // default, rejected media section here that can be later overwritten.
4085 for (size_t i = 0;
4086 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4087 // Either |local_content| or |remote_content| is non-null.
4088 const ContentInfo* local_content =
4089 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004090 const ContentInfo* current_local_content =
4091 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004092 const ContentInfo* remote_content =
4093 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004094 const ContentInfo* current_remote_content =
4095 GetContentByIndex(current_remote_description(), i);
4096 bool had_been_rejected =
4097 (current_local_content && current_local_content->rejected) ||
4098 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004099 const std::string& mid =
4100 (local_content ? local_content->name : remote_content->name);
4101 cricket::MediaType media_type =
4102 (local_content ? local_content->media_description()->type()
4103 : remote_content->media_description()->type());
4104 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4105 media_type == cricket::MEDIA_TYPE_VIDEO) {
4106 auto transceiver = GetAssociatedTransceiver(mid);
4107 RTC_CHECK(transceiver);
4108 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004109 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004110 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004111 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004112 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4113 RtpTransceiverDirection::kInactive,
4114 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004115 recycleable_mline_indices.push(i);
4116 } else {
4117 session_options->media_description_options.push_back(
4118 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4119 // CreateOffer shouldn't really cause any state changes in
4120 // PeerConnection, but we need a way to match new transceivers to new
4121 // media sections in SetLocalDescription and JSEP specifies this is done
4122 // by recording the index of the media section generated for the
4123 // transceiver in the offer.
4124 transceiver->internal()->set_mline_index(i);
4125 }
4126 } else {
4127 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004128 RTC_CHECK(GetDataMid());
4129 if (had_been_rejected || mid != *GetDataMid()) {
4130 session_options->media_description_options.push_back(
4131 GetMediaDescriptionOptionsForRejectedData(mid));
4132 } else {
4133 session_options->media_description_options.push_back(
4134 GetMediaDescriptionOptionsForActiveData(mid));
4135 }
Steve Antondcc3c022017-12-22 16:02:54 -08004136 }
4137 }
4138 // Next, look for transceivers that are newly added (that is, are not stopped
4139 // and not associated). Reuse media sections marked as recyclable first,
4140 // otherwise append to the end of the offer. New media sections should be
4141 // added in the order they were added to the PeerConnection.
4142 for (auto transceiver : transceivers_) {
4143 if (transceiver->mid() || transceiver->stopped()) {
4144 continue;
4145 }
4146 size_t mline_index;
4147 if (!recycleable_mline_indices.empty()) {
4148 mline_index = recycleable_mline_indices.front();
4149 recycleable_mline_indices.pop();
4150 session_options->media_description_options[mline_index] =
4151 GetMediaDescriptionOptionsForTransceiver(transceiver,
4152 AllocateMid(&used_mids));
4153 } else {
4154 mline_index = session_options->media_description_options.size();
4155 session_options->media_description_options.push_back(
4156 GetMediaDescriptionOptionsForTransceiver(transceiver,
4157 AllocateMid(&used_mids)));
4158 }
4159 // See comment above for why CreateOffer changes the transceiver's state.
4160 transceiver->internal()->set_mline_index(mline_index);
4161 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004162 // Lastly, add a m-section if we have local data channels and an m section
4163 // does not already exist.
4164 if (!GetDataMid() && HasDataChannels()) {
4165 session_options->media_description_options.push_back(
4166 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4167 }
Steve Antondcc3c022017-12-22 16:02:54 -08004168}
4169
4170void PeerConnection::GetOptionsForAnswer(
4171 const RTCOfferAnswerOptions& offer_answer_options,
4172 cricket::MediaSessionOptions* session_options) {
4173 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4174
4175 if (IsUnifiedPlan()) {
4176 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4177 } else {
4178 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4179 }
4180
Steve Antonfa2260d2017-12-28 16:38:23 -08004181 // Intentionally unset the data channel type for RTP data channel. Otherwise
4182 // the RTP data channels would be successfully negotiated by default and the
4183 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4184 // We want to leave RTP data channels broken, so people won't try to use them.
4185 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4186 session_options->data_channel_type = data_channel_type();
4187 }
4188
Steve Antondcc3c022017-12-22 16:02:54 -08004189 // Apply ICE renomination flag.
4190 for (auto& options : session_options->media_description_options) {
4191 options.transport_options.enable_ice_renomination =
4192 configuration_.enable_ice_renomination;
4193 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004194
4195 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004196 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004197 session_options->pooled_ice_credentials =
4198 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4199 RTC_FROM_HERE,
4200 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4201 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004202}
4203
Steve Antondcc3c022017-12-22 16:02:54 -08004204void PeerConnection::GetOptionsForPlanBAnswer(
4205 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004206 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004207 // Figure out transceiver directional preferences.
4208 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4209 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4210
4211 // By default, generate sendrecv/recvonly m= sections. The direction is also
4212 // restricted by the direction in the offer.
4213 bool recv_audio = true;
4214 bool recv_video = true;
4215
4216 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004217 if (offer_answer_options.offer_to_receive_audio !=
4218 RTCOfferAnswerOptions::kUndefined) {
4219 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004220 }
Steve Antondcc3c022017-12-22 16:02:54 -08004221 if (offer_answer_options.offer_to_receive_video !=
4222 RTCOfferAnswerOptions::kUndefined) {
4223 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004224 }
4225
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004226 absl::optional<size_t> audio_index;
4227 absl::optional<size_t> video_index;
4228 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004229
4230 // Generate m= sections that match those in the offer.
4231 // Note that mediasession.cc will handle intersection our preferred
4232 // direction with the offered direction.
4233 GenerateMediaDescriptionOptions(
4234 remote_description(),
4235 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4236 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4237 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004238
4239 cricket::MediaDescriptionOptions* audio_media_description_options =
4240 !audio_index ? nullptr
4241 : &session_options->media_description_options[*audio_index];
4242 cricket::MediaDescriptionOptions* video_media_description_options =
4243 !video_index ? nullptr
4244 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004245
Amit Hilbuchc63ddb22019-01-02 10:13:58 -08004246 AddPlanBRtpSenderOptions(GetSendersInternal(),
4247 audio_media_description_options,
4248 video_media_description_options,
4249 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004250}
zhihuangaf388472016-11-02 16:49:48 -07004251
Steve Antondcc3c022017-12-22 16:02:54 -08004252void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4253 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4254 cricket::MediaSessionOptions* session_options) {
4255 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4256 // Answers) and 5.3.2 (Subsequent Answers).
4257 RTC_DCHECK(remote_description());
4258 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4259 for (const ContentInfo& content :
4260 remote_description()->description()->contents()) {
4261 cricket::MediaType media_type = content.media_description()->type();
4262 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4263 media_type == cricket::MEDIA_TYPE_VIDEO) {
4264 auto transceiver = GetAssociatedTransceiver(content.name);
4265 RTC_CHECK(transceiver);
4266 session_options->media_description_options.push_back(
4267 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4268 } else {
4269 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004270 // Reject all data sections if data channels are disabled.
4271 // Reject a data section if it has already been rejected.
4272 // Reject all data sections except for the first one.
4273 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4274 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004275 session_options->media_description_options.push_back(
4276 GetMediaDescriptionOptionsForRejectedData(content.name));
4277 } else {
4278 session_options->media_description_options.push_back(
4279 GetMediaDescriptionOptionsForActiveData(content.name));
4280 }
Steve Antondcc3c022017-12-22 16:02:54 -08004281 }
4282 }
htaa2a49d92016-03-04 02:51:39 -08004283}
4284
zhihuang1c378ed2017-08-17 14:10:50 -07004285void PeerConnection::GenerateMediaDescriptionOptions(
4286 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004287 RtpTransceiverDirection audio_direction,
4288 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004289 absl::optional<size_t>* audio_index,
4290 absl::optional<size_t>* video_index,
4291 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004292 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004293 for (const cricket::ContentInfo& content :
4294 session_desc->description()->contents()) {
4295 if (IsAudioContent(&content)) {
4296 // If we already have an audio m= section, reject this extra one.
4297 if (*audio_index) {
4298 session_options->media_description_options.push_back(
4299 cricket::MediaDescriptionOptions(
4300 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004301 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004302 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004303 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004304 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004305 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4306 content.name, audio_direction,
4307 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004308 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004309 }
4310 } else if (IsVideoContent(&content)) {
4311 // If we already have an video m= section, reject this extra one.
4312 if (*video_index) {
4313 session_options->media_description_options.push_back(
4314 cricket::MediaDescriptionOptions(
4315 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004316 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004317 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004318 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004319 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004320 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4321 content.name, video_direction,
4322 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004323 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004324 }
4325 } else {
4326 RTC_DCHECK(IsDataContent(&content));
4327 // If we already have an data m= section, reject this extra one.
4328 if (*data_index) {
4329 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004330 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004331 } else {
4332 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004333 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004334 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004335 }
4336 }
htaa2a49d92016-03-04 02:51:39 -08004337 }
deadbeefab9b2d12015-10-14 11:33:11 -07004338}
4339
Steve Antonfa2260d2017-12-28 16:38:23 -08004340cricket::MediaDescriptionOptions
4341PeerConnection::GetMediaDescriptionOptionsForActiveData(
4342 const std::string& mid) const {
4343 // Direction for data sections is meaningless, but legacy endpoints might
4344 // expect sendrecv.
4345 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4346 RtpTransceiverDirection::kSendRecv,
4347 /*stopped=*/false);
4348 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4349 return options;
4350}
4351
4352cricket::MediaDescriptionOptions
4353PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4354 const std::string& mid) const {
4355 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4356 RtpTransceiverDirection::kInactive,
4357 /*stopped=*/true);
4358 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4359 return options;
4360}
4361
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004362absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004363 switch (data_channel_type_) {
4364 case cricket::DCT_RTP:
4365 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004366 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004367 }
4368 return rtp_data_channel_->content_name();
4369 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004370 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004371 case cricket::DCT_MEDIA_TRANSPORT:
4372 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004373 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004374 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004375 }
4376}
4377
Steve Anton4171afb2017-11-20 10:20:22 -08004378void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4379 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4380 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004381 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004382}
4383
Steve Anton4171afb2017-11-20 10:20:22 -08004384void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004385 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004386 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004387 cricket::MediaType media_type,
4388 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004389 RTC_DCHECK(!IsUnifiedPlan());
4390
Steve Anton4171afb2017-11-20 10:20:22 -08004391 std::vector<RtpSenderInfo>* current_senders =
4392 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004393
Steve Anton4171afb2017-11-20 10:20:22 -08004394 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004395 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004396 for (auto sender_it = current_senders->begin();
4397 sender_it != current_senders->end();
4398 /* incremented manually */) {
4399 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004400 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004401 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004402 std::string params_stream_id;
4403 if (params) {
4404 params_stream_id =
4405 (!params->first_stream_id().empty() ? params->first_stream_id()
4406 : kDefaultStreamId);
4407 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004408 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004409 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004410 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004411 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004412 sender_exists) {
4413 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004414 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004415 OnRemoteSenderRemoved(info, media_type);
4416 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004417 }
4418 }
4419
Steve Anton4171afb2017-11-20 10:20:22 -08004420 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004421 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004422 if (!params.has_ssrcs()) {
4423 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4424 // sender, this means it is coming from a Unified Plan endpoint,so we just
4425 // create a default.
4426 default_sender_needed = true;
4427 break;
4428 }
4429
Seth Hampson845e8782018-03-02 11:34:10 -08004430 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004431 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004432 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4433 // not supported in Plan B, we just take the first here and create the
4434 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004435 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004436 (!params.first_stream_id().empty() ? params.first_stream_id()
4437 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004438 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004439 uint32_t ssrc = params.first_ssrc();
4440
4441 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004442 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004443 if (!stream) {
4444 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004445 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004446 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004447 remote_streams_->AddStream(stream);
4448 new_streams->AddStream(stream);
4449 }
4450
Steve Anton4171afb2017-11-20 10:20:22 -08004451 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004452 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004453 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004454 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004455 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004456 }
4457 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004458
Steve Anton4171afb2017-11-20 10:20:22 -08004459 // Add default sender if necessary.
4460 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004461 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004462 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004463 if (!default_stream) {
4464 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004465 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004466 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004467 remote_streams_->AddStream(default_stream);
4468 new_streams->AddStream(default_stream);
4469 }
Steve Anton4171afb2017-11-20 10:20:22 -08004470 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4471 ? kDefaultAudioSenderId
4472 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004473 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004474 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004475 if (!default_sender_info) {
4476 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004477 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004478 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004479 }
4480 }
deadbeefab9b2d12015-10-14 11:33:11 -07004481}
4482
Steve Anton4171afb2017-11-20 10:20:22 -08004483void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4484 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004485 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4486 << " receiver for track_id=" << sender_info.sender_id
4487 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004488
Steve Anton3d954a62018-04-02 11:27:23 -07004489 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004490 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004491 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004492 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004493 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004494 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004495 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004496 }
4497}
4498
Steve Anton4171afb2017-11-20 10:20:22 -08004499void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4500 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004501 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4502 << " receiver for track_id=" << sender_info.sender_id
4503 << " and stream_id=" << sender_info.stream_id;
4504
Seth Hampson845e8782018-03-02 11:34:10 -08004505 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004506
Henrik Boström933d8b02017-10-10 10:05:16 -07004507 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004508 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004509 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4510 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004511 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004512 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004513 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004514 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004515 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004516 }
4517 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004518 // Stopping or destroying a VideoRtpReceiver will end the
4519 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004520 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004521 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004522 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004523 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004524 // There's no guarantee the track is still available, e.g. the track may
4525 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004526 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004527 }
4528 } else {
nisseede5da42017-01-12 05:15:36 -08004529 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004530 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004531 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004532 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004533 }
deadbeefab9b2d12015-10-14 11:33:11 -07004534}
4535
4536void PeerConnection::UpdateEndedRemoteMediaStreams() {
4537 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4538 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4539 MediaStreamInterface* stream = remote_streams_->at(i);
4540 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4541 streams_to_remove.push_back(stream);
4542 }
4543 }
4544
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004545 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004546 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004547 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004548 }
4549}
4550
Steve Anton4171afb2017-11-20 10:20:22 -08004551void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004552 const std::vector<cricket::StreamParams>& streams,
4553 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004554 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004555
Seth Hampson845e8782018-03-02 11:34:10 -08004556 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004557 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004558 for (auto sender_it = current_senders->begin();
4559 sender_it != current_senders->end();
4560 /* incremented manually */) {
4561 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004562 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004563 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4564 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004565 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 OnLocalSenderRemoved(info, media_type);
4567 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004568 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004569 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004570 }
4571 }
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004574 for (const cricket::StreamParams& params : streams) {
4575 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004576 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004577 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004578 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004579 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004580 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004581 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004582 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004583 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004584 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004585 }
4586 }
4587}
4588
Steve Anton4171afb2017-11-20 10:20:22 -08004589void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4590 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004591 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004592 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004593 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004594 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4595 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004596 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004597 return;
4598 }
4599
deadbeeffac06552015-11-25 11:26:01 -08004600 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004601 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004602 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004603 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004604 }
deadbeeffac06552015-11-25 11:26:01 -08004605
Seth Hampson5b4f0752018-04-02 16:31:36 -07004606 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004607 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004608}
4609
Steve Anton4171afb2017-11-20 10:20:22 -08004610void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4611 cricket::MediaType media_type) {
4612 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004613 if (!sender) {
4614 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004615 // SessionDescriptions has been renegotiated.
4616 return;
4617 }
deadbeeffac06552015-11-25 11:26:01 -08004618
4619 // A sender has been removed from the SessionDescription but it's still
4620 // associated with the PeerConnection. This only occurs if the SDP doesn't
4621 // match with the calls to CreateSender, AddStream and RemoveStream.
4622 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004623 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004624 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004625 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004626 }
deadbeeffac06552015-11-25 11:26:01 -08004627
Steve Anton4171afb2017-11-20 10:20:22 -08004628 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004629}
4630
4631void PeerConnection::UpdateLocalRtpDataChannels(
4632 const cricket::StreamParamsVec& streams) {
4633 std::vector<std::string> existing_channels;
4634
4635 // Find new and active data channels.
4636 for (const cricket::StreamParams& params : streams) {
4637 // |it->sync_label| is actually the data channel label. The reason is that
4638 // we use the same naming of data channels as we do for
4639 // MediaStreams and Tracks.
4640 // For MediaStreams, the sync_label is the MediaStream label and the
4641 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004642 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004643 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004644 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004645 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004646 continue;
4647 }
4648 // Set the SSRC the data channel should use for sending.
4649 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4650 existing_channels.push_back(data_channel_it->first);
4651 }
4652
4653 UpdateClosingRtpDataChannels(existing_channels, true);
4654}
4655
4656void PeerConnection::UpdateRemoteRtpDataChannels(
4657 const cricket::StreamParamsVec& streams) {
4658 std::vector<std::string> existing_channels;
4659
4660 // Find new and active data channels.
4661 for (const cricket::StreamParams& params : streams) {
4662 // The data channel label is either the mslabel or the SSRC if the mslabel
4663 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004664 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004665 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004666 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004667 auto data_channel_it = rtp_data_channels_.find(label);
4668 if (data_channel_it == rtp_data_channels_.end()) {
4669 // This is a new data channel.
4670 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4671 } else {
4672 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4673 }
4674 existing_channels.push_back(label);
4675 }
4676
4677 UpdateClosingRtpDataChannels(existing_channels, false);
4678}
4679
4680void PeerConnection::UpdateClosingRtpDataChannels(
4681 const std::vector<std::string>& active_channels,
4682 bool is_local_update) {
4683 auto it = rtp_data_channels_.begin();
4684 while (it != rtp_data_channels_.end()) {
4685 DataChannel* data_channel = it->second;
4686 if (std::find(active_channels.begin(), active_channels.end(),
4687 data_channel->label()) != active_channels.end()) {
4688 ++it;
4689 continue;
4690 }
4691
4692 if (is_local_update) {
4693 data_channel->SetSendSsrc(0);
4694 } else {
4695 data_channel->RemotePeerRequestClose();
4696 }
4697
4698 if (data_channel->state() == DataChannel::kClosed) {
4699 rtp_data_channels_.erase(it);
4700 it = rtp_data_channels_.begin();
4701 } else {
4702 ++it;
4703 }
4704 }
4705}
4706
4707void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4708 uint32_t remote_ssrc) {
4709 rtc::scoped_refptr<DataChannel> channel(
4710 InternalCreateDataChannel(label, nullptr));
4711 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004712 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004713 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004714 return;
4715 }
4716 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004717 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4718 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004719 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004720}
4721
4722rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4723 const std::string& label,
4724 const InternalDataChannelInit* config) {
4725 if (IsClosed()) {
4726 return nullptr;
4727 }
Steve Anton75737c02017-11-06 10:37:17 -08004728 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004729 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004730 << "InternalCreateDataChannel: Data is not supported in this call.";
4731 return nullptr;
4732 }
4733 InternalDataChannelInit new_config =
4734 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004735 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004736 if (new_config.id < 0) {
4737 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004738 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004739 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004740 RTC_LOG(LS_ERROR)
4741 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004742 return nullptr;
4743 }
4744 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004745 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004746 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004747 return nullptr;
4748 }
4749 }
4750
Steve Anton75737c02017-11-06 10:37:17 -08004751 rtc::scoped_refptr<DataChannel> channel(
4752 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004753 if (!channel) {
4754 sid_allocator_.ReleaseSid(new_config.id);
4755 return nullptr;
4756 }
4757
4758 if (channel->data_channel_type() == cricket::DCT_RTP) {
4759 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004760 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4761 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004762 return nullptr;
4763 }
4764 rtp_data_channels_[channel->label()] = channel;
4765 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004766 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004767 sctp_data_channels_.push_back(channel);
4768 channel->SignalClosed.connect(this,
4769 &PeerConnection::OnSctpDataChannelClosed);
4770 }
4771
Steve Anton2d8609c2018-01-23 16:38:46 -08004772 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004773 return channel;
4774}
4775
4776bool PeerConnection::HasDataChannels() const {
4777 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4778}
4779
4780void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4781 for (const auto& channel : sctp_data_channels_) {
4782 if (channel->id() < 0) {
4783 int sid;
4784 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004785 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004786 continue;
4787 }
4788 channel->SetSctpSid(sid);
4789 }
4790 }
4791}
4792
4793void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004794 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004795 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4796 ++it) {
4797 if (it->get() == channel) {
4798 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004799 // After the closing procedure is done, it's safe to use this ID for
4800 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004801 sid_allocator_.ReleaseSid(channel->id());
4802 }
deadbeefbd292462015-12-14 18:15:29 -08004803 // Since this method is triggered by a signal from the DataChannel,
4804 // we can't free it directly here; we need to free it asynchronously.
4805 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004806 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004807 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4808 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004809 return;
4810 }
4811 }
4812}
4813
deadbeefab9b2d12015-10-14 11:33:11 -07004814void PeerConnection::OnDataChannelDestroyed() {
4815 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4816 // DataChannel may callback to us and try to modify the list.
4817 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4818 temp_rtp_dcs.swap(rtp_data_channels_);
4819 for (const auto& kv : temp_rtp_dcs) {
4820 kv.second->OnTransportChannelDestroyed();
4821 }
4822
4823 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4824 temp_sctp_dcs.swap(sctp_data_channels_);
4825 for (const auto& channel : temp_sctp_dcs) {
4826 channel->OnTransportChannelDestroyed();
4827 }
4828}
4829
4830void PeerConnection::OnDataChannelOpenMessage(
4831 const std::string& label,
4832 const InternalDataChannelInit& config) {
4833 rtc::scoped_refptr<DataChannel> channel(
4834 InternalCreateDataChannel(label, &config));
4835 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004836 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004837 return;
4838 }
4839
deadbeefa601f5c2016-06-06 14:27:39 -07004840 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4841 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004842 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004843 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004844}
4845
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004846bool PeerConnection::HandleOpenMessage_s(
4847 const cricket::ReceiveDataParams& params,
4848 const rtc::CopyOnWriteBuffer& buffer) {
4849 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4850 // Received OPEN message; parse and signal that a new data channel should
4851 // be created.
4852 std::string label;
4853 InternalDataChannelInit config;
4854 config.id = params.ssrc;
4855 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4856 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4857 << params.ssrc;
4858 return true;
4859 }
4860 config.open_handshake_role = InternalDataChannelInit::kAcker;
4861 OnDataChannelOpenMessage(label, config);
4862 return true;
4863 }
4864 return false;
4865}
4866
Steve Anton4171afb2017-11-20 10:20:22 -08004867rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4868PeerConnection::GetAudioTransceiver() const {
4869 // This method only works with Plan B SDP, where there is a single
4870 // audio/video transceiver.
4871 RTC_DCHECK(!IsUnifiedPlan());
4872 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004873 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004874 return transceiver;
4875 }
4876 }
4877 RTC_NOTREACHED();
4878 return nullptr;
4879}
4880
4881rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4882PeerConnection::GetVideoTransceiver() const {
4883 // This method only works with Plan B SDP, where there is a single
4884 // audio/video transceiver.
4885 RTC_DCHECK(!IsUnifiedPlan());
4886 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004887 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004888 return transceiver;
4889 }
4890 }
4891 RTC_NOTREACHED();
4892 return nullptr;
4893}
4894
4895// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4896// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004897bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004898 switch (type) {
4899 case cricket::MEDIA_TYPE_AUDIO:
4900 return !GetAudioTransceiver()->internal()->senders().empty();
4901 case cricket::MEDIA_TYPE_VIDEO:
4902 return !GetVideoTransceiver()->internal()->senders().empty();
4903 case cricket::MEDIA_TYPE_DATA:
4904 return false;
4905 }
4906 RTC_NOTREACHED();
4907 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004908}
4909
Steve Anton4171afb2017-11-20 10:20:22 -08004910rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4911PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4912 for (auto transceiver : transceivers_) {
4913 for (auto sender : transceiver->internal()->senders()) {
4914 if (sender->track() == track) {
4915 return sender;
4916 }
4917 }
4918 }
4919 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004920}
4921
Steve Anton4171afb2017-11-20 10:20:22 -08004922rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4923PeerConnection::FindSenderById(const std::string& sender_id) const {
4924 for (auto transceiver : transceivers_) {
4925 for (auto sender : transceiver->internal()->senders()) {
4926 if (sender->id() == sender_id) {
4927 return sender;
4928 }
4929 }
4930 }
4931 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004932}
4933
Steve Anton4171afb2017-11-20 10:20:22 -08004934rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4935PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4936 for (auto transceiver : transceivers_) {
4937 for (auto receiver : transceiver->internal()->receivers()) {
4938 if (receiver->id() == receiver_id) {
4939 return receiver;
4940 }
4941 }
4942 }
4943 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004944}
4945
Steve Anton4171afb2017-11-20 10:20:22 -08004946std::vector<PeerConnection::RtpSenderInfo>*
4947PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4948 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4949 media_type == cricket::MEDIA_TYPE_VIDEO);
4950 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4951 ? &remote_audio_sender_infos_
4952 : &remote_video_sender_infos_;
4953}
4954
4955std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004956 cricket::MediaType media_type) {
4957 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4958 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004959 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4960 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004961}
4962
Steve Anton4171afb2017-11-20 10:20:22 -08004963const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4964 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004965 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004966 const std::string sender_id) const {
4967 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004968 if (sender_info.stream_id == stream_id &&
4969 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004970 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004971 }
4972 }
4973 return nullptr;
4974}
4975
4976DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4977 for (const auto& channel : sctp_data_channels_) {
4978 if (channel->id() == sid) {
4979 return channel;
4980 }
4981 }
4982 return nullptr;
4983}
4984
deadbeef91dd5672016-05-18 16:55:30 -07004985bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004986 const cricket::ServerAddresses& stun_servers,
4987 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004988 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004989 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004990 // To handle both internal and externally created port allocator, we will
4991 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004992 port_allocator_flags_ = port_allocator_->flags();
4993 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4994 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4995 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004996 // If the disable-IPv6 flag was specified, we'll not override it
4997 // by experiment.
4998 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004999 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08005000 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
5001 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005002 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005003 }
5004
zhihuangb09b3f92017-03-07 14:40:51 -08005005 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005006 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005007 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005008 }
5009
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005010 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005011 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005012 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005013 }
5014
honghaiz60347052016-05-31 18:29:12 -07005015 if (configuration.candidate_network_policy ==
5016 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005017 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005019 }
5020
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005021 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005022 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005023 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5024 }
5025
Qingsi Wanga2d60672018-04-11 16:57:45 -07005026 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005027 // No step delay is used while allocating ports.
5028 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5029 port_allocator_->set_candidate_filter(
5030 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005031 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005032
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005033 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005034 for (auto& turn_server : turn_servers_copy) {
5035 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005036 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005037 // Call this last since it may create pooled allocator sessions using the
5038 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005039 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005040 stun_servers, std::move(turn_servers_copy),
5041 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5042 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005043 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005044 return true;
5045}
5046
deadbeef91dd5672016-05-18 16:55:30 -07005047bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005048 const cricket::ServerAddresses& stun_servers,
5049 const std::vector<cricket::RelayServerConfig>& turn_servers,
5050 IceTransportsType type,
5051 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005052 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005053 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005054 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005055 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005056 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005057 // According to JSEP, after setLocalDescription, changing the candidate pool
5058 // size is not allowed, and changing the set of ICE servers will not result
5059 // in new candidates being gathered.
5060 if (local_description()) {
5061 port_allocator_->FreezeCandidatePool();
5062 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005063 // Add the custom tls turn servers if they exist.
5064 auto turn_servers_copy = turn_servers;
5065 for (auto& turn_server : turn_servers_copy) {
5066 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5067 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005068 // Call this last since it may create pooled allocator sessions using the
5069 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005070 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005071 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5072 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005073}
5074
Steve Antonba818672017-11-06 10:21:57 -08005075cricket::ChannelManager* PeerConnection::channel_manager() const {
5076 return factory_->channel_manager();
5077}
5078
Elad Alon99c3fe52017-10-13 16:29:40 +02005079bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005080 std::unique_ptr<RtcEventLogOutput> output,
5081 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005082 if (!event_log_) {
5083 return false;
5084 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005085 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005086}
5087
5088void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005089 if (event_log_) {
5090 event_log_->StopLogging();
5091 }
ivoc14d5dbe2016-07-04 07:06:55 -07005092}
nisseeaabdf62017-05-05 02:23:02 -07005093
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005094cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005095 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005096 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005097 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005098 if (channel && channel->content_name() == content_name) {
5099 return channel;
5100 }
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
5102 if (rtp_data_channel() &&
5103 rtp_data_channel()->content_name() == content_name) {
5104 return rtp_data_channel();
5105 }
5106 return nullptr;
5107}
5108
5109bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005110 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005111 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_INFO)
5113 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005114 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005115 return false;
5116 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005117 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005118 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005119 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005120 return false;
5121 }
5122
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005123 absl::optional<rtc::SSLRole> dtls_role;
5124 if (sctp_mid_) {
5125 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5126 } else if (is_caller_) {
5127 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5128 }
Zhi Huange830e682018-03-30 10:48:35 -07005129 if (dtls_role) {
5130 *role = *dtls_role;
5131 return true;
5132 }
5133 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005134}
5135
5136bool PeerConnection::GetSslRole(const std::string& content_name,
5137 rtc::SSLRole* role) {
5138 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 RTC_LOG(LS_INFO)
5140 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005141 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005142 return false;
5143 }
5144
Zhi Huange830e682018-03-30 10:48:35 -07005145 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5146 if (dtls_role) {
5147 *role = *dtls_role;
5148 return true;
5149 }
5150 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005151}
5152
Steve Antonf8470812017-12-04 10:46:21 -08005153void PeerConnection::SetSessionError(SessionError error,
5154 const std::string& error_desc) {
5155 RTC_DCHECK_RUN_ON(signaling_thread());
5156 if (error != session_error_) {
5157 session_error_ = error;
5158 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005159 }
5160}
5161
Zhi Huange830e682018-03-30 10:48:35 -07005162RTCError PeerConnection::UpdateSessionState(
5163 SdpType type,
5164 cricket::ContentSource source,
5165 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005166 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005167
5168 // If there's already a pending error then no state transition should happen.
5169 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005170 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005171
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005172 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005173 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005174 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005175 }
5176
5177 // Update the signaling state according to the specified state machine (see
5178 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005179 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005180 ChangeSignalingState(source == cricket::CS_LOCAL
5181 ? PeerConnectionInterface::kHaveLocalOffer
5182 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005183 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005184 ChangeSignalingState(source == cricket::CS_LOCAL
5185 ? PeerConnectionInterface::kHaveLocalPrAnswer
5186 : PeerConnectionInterface::kHaveRemotePrAnswer);
5187 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005188 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005189 ChangeSignalingState(PeerConnectionInterface::kStable);
5190 }
5191
5192 // Update internal objects according to the session description's media
5193 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005194 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005195 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005196 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005197 }
5198
Steve Anton8a006912017-12-04 15:25:56 -08005199 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005200}
5201
Steve Anton8a006912017-12-04 15:25:56 -08005202RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005203 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005204 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005205 const SessionDescriptionInterface* sdesc =
5206 (source == cricket::CS_LOCAL ? local_description()
5207 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005208 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005209
5210 // Push down the new SDP media section for each audio/video transceiver.
5211 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005212 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005213 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005214 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005215 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005216 continue;
5217 }
5218 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005219 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005220 if (!content_desc) {
5221 continue;
5222 }
5223 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005224 bool success = (source == cricket::CS_LOCAL)
5225 ? channel->SetLocalContent(content_desc, type, &error)
5226 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005227 if (!success) {
5228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5229 }
5230 }
5231
5232 // If using the RtpDataChannel, push down the new SDP section for it too.
5233 if (rtp_data_channel_) {
5234 const ContentInfo* data_content =
5235 cricket::GetFirstDataContent(sdesc->description());
5236 if (data_content && !data_content->rejected) {
5237 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005238 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005239 if (data_desc) {
5240 std::string error;
5241 bool success =
5242 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005243 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005244 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005245 if (!success) {
5246 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5247 std::move(error));
5248 }
Steve Anton75737c02017-11-06 10:37:17 -08005249 }
5250 }
5251 }
Steve Antoned10bd92017-12-05 10:52:59 -08005252
Steve Anton75737c02017-11-06 10:37:17 -08005253 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5254 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5255 if (sctp_transport_ && local_description() && remote_description() &&
5256 cricket::GetFirstDataContent(local_description()->description()) &&
5257 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005258 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005259 RTC_FROM_HERE,
5260 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005261 if (!success) {
5262 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5263 "Failed to push down SCTP parameters.");
5264 }
Steve Anton75737c02017-11-06 10:37:17 -08005265 }
Steve Antoned10bd92017-12-05 10:52:59 -08005266
Steve Anton8a006912017-12-04 15:25:56 -08005267 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005268}
5269
5270bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5271 RTC_DCHECK(network_thread()->IsCurrent());
5272 RTC_DCHECK(local_description());
5273 RTC_DCHECK(remote_description());
5274 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5275 // When we support "max-message-size", that would also be pushed down here.
5276 return sctp_transport_->Start(
5277 GetSctpPort(local_description()->description()),
5278 GetSctpPort(remote_description()->description()));
5279}
5280
Steve Anton8a006912017-12-04 15:25:56 -08005281RTCError PeerConnection::PushdownTransportDescription(
5282 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005283 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005284 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005285
Zhi Huange830e682018-03-30 10:48:35 -07005286 if (source == cricket::CS_LOCAL) {
5287 const SessionDescriptionInterface* sdesc = local_description();
5288 RTC_DCHECK(sdesc);
5289 return transport_controller_->SetLocalDescription(type,
5290 sdesc->description());
5291 } else {
5292 const SessionDescriptionInterface* sdesc = remote_description();
5293 RTC_DCHECK(sdesc);
5294 return transport_controller_->SetRemoteDescription(type,
5295 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005296 }
Steve Anton75737c02017-11-06 10:37:17 -08005297}
5298
5299bool PeerConnection::GetTransportDescription(
5300 const SessionDescription* description,
5301 const std::string& content_name,
5302 cricket::TransportDescription* tdesc) {
5303 if (!description || !tdesc) {
5304 return false;
5305 }
5306 const TransportInfo* transport_info =
5307 description->GetTransportInfoByName(content_name);
5308 if (!transport_info) {
5309 return false;
5310 }
5311 *tdesc = transport_info->description;
5312 return true;
5313}
5314
Steve Anton75737c02017-11-06 10:37:17 -08005315cricket::IceConfig PeerConnection::ParseIceConfig(
5316 const PeerConnectionInterface::RTCConfiguration& config) const {
5317 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005318 switch (config.continual_gathering_policy) {
5319 case PeerConnectionInterface::GATHER_ONCE:
5320 gathering_policy = cricket::GATHER_ONCE;
5321 break;
5322 case PeerConnectionInterface::GATHER_CONTINUALLY:
5323 gathering_policy = cricket::GATHER_CONTINUALLY;
5324 break;
5325 default:
5326 RTC_NOTREACHED();
5327 gathering_policy = cricket::GATHER_ONCE;
5328 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005329
Steve Anton75737c02017-11-06 10:37:17 -08005330 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005331 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5332 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005333 ice_config.prioritize_most_likely_candidate_pairs =
5334 config.prioritize_most_likely_ice_candidate_pairs;
5335 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005336 RTCConfigurationToIceConfigOptionalInt(
5337 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005338 ice_config.continual_gathering_policy = gathering_policy;
5339 ice_config.presume_writable_when_fully_relayed =
5340 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005341 ice_config.ice_check_interval_strong_connectivity =
5342 config.ice_check_interval_strong_connectivity;
5343 ice_config.ice_check_interval_weak_connectivity =
5344 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005345 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005346 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5347 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005348 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005349 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005350 ice_config.regather_all_networks_interval_range =
5351 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005352 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005353 return ice_config;
5354}
5355
Steve Antona41959e2018-11-28 11:15:33 -08005356static absl::string_view GetTrackIdBySsrc(
5357 const SessionDescriptionInterface* session_description,
5358 uint32_t ssrc) {
5359 if (!session_description) {
5360 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005361 }
Steve Antona41959e2018-11-28 11:15:33 -08005362 for (const cricket::ContentInfo& content :
5363 session_description->description()->contents()) {
5364 const cricket::MediaContentDescription& media =
5365 *content.media_description();
5366 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5367 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5368 const cricket::StreamParams* stream_params =
5369 cricket::GetStreamBySsrc(media.streams(), ssrc);
5370 if (stream_params) {
5371 return stream_params->id;
5372 }
5373 }
5374 }
5375 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005376}
5377
Steve Antona41959e2018-11-28 11:15:33 -08005378absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5379 return GetTrackIdBySsrc(local_description(), ssrc);
5380}
5381
5382absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5383 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005384}
5385
5386bool PeerConnection::SendData(const cricket::SendDataParams& params,
5387 const rtc::CopyOnWriteBuffer& payload,
5388 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005389 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5390 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5391 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005392 return false;
5393 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005394 if (media_transport_) {
5395 SendDataParams send_params;
5396 send_params.type = ToWebrtcDataMessageType(params.type);
5397 send_params.ordered = params.ordered;
5398 if (params.max_rtx_count >= 0) {
5399 send_params.max_rtx_count = params.max_rtx_count;
5400 } else if (params.max_rtx_ms >= 0) {
5401 send_params.max_rtx_ms = params.max_rtx_ms;
5402 }
5403 return media_transport_->SendData(params.sid, send_params, payload).ok();
5404 }
Steve Anton75737c02017-11-06 10:37:17 -08005405 return rtp_data_channel_
5406 ? rtp_data_channel_->SendData(params, payload, result)
5407 : network_thread()->Invoke<bool>(
5408 RTC_FROM_HERE,
5409 Bind(&cricket::SctpTransportInternal::SendData,
5410 sctp_transport_.get(), params, payload, result));
5411}
5412
5413bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005414 RTC_DCHECK_RUN_ON(signaling_thread());
5415 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005416 // Don't log an error here, because DataChannels are expected to call
5417 // ConnectDataChannel in this state. It's the only way to initially tell
5418 // whether or not the underlying transport is ready.
5419 return false;
5420 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005421 if (media_transport_) {
5422 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5423 &DataChannel::OnChannelReady);
5424 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5425 &DataChannel::OnDataReceived);
5426 SignalMediaTransportChannelClosing_s.connect(
5427 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5428 SignalMediaTransportChannelClosed_s.connect(
5429 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5430 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005431 rtp_data_channel_->SignalReadyToSendData.connect(
5432 webrtc_data_channel, &DataChannel::OnChannelReady);
5433 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5434 &DataChannel::OnDataReceived);
5435 } else {
5436 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5437 &DataChannel::OnChannelReady);
5438 SignalSctpDataReceived.connect(webrtc_data_channel,
5439 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005440 SignalSctpClosingProcedureStartedRemotely.connect(
5441 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5442 SignalSctpClosingProcedureComplete.connect(
5443 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
5445 return true;
5446}
5447
5448void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005449 RTC_DCHECK_RUN_ON(signaling_thread());
5450 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005451 RTC_LOG(LS_ERROR)
5452 << "DisconnectDataChannel called when rtp_data_channel_ and "
5453 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005454 return;
5455 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005456 if (media_transport_) {
5457 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5458 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5459 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5460 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5461 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005462 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5463 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5464 } else {
5465 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5466 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005467 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5468 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005469 }
5470}
5471
5472void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005473 if (media_transport_) {
5474 // No-op. Media transport does not need to add streams.
5475 return;
5476 }
Steve Anton75737c02017-11-06 10:37:17 -08005477 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005478 RTC_LOG(LS_ERROR)
5479 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005480 return;
5481 }
5482 network_thread()->Invoke<void>(
5483 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5484 sctp_transport_.get(), sid));
5485}
5486
5487void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005488 if (media_transport_) {
5489 media_transport_->CloseChannel(sid);
5490 return;
5491 }
Steve Anton75737c02017-11-06 10:37:17 -08005492 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005493 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005494 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005495 return;
5496 }
5497 network_thread()->Invoke<void>(
5498 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5499 sctp_transport_.get(), sid));
5500}
5501
5502bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005503 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005504 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005505 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005506 sctp_ready_to_send_data_;
5507}
5508
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005509void PeerConnection::OnDataReceived(int channel_id,
5510 DataMessageType type,
5511 const rtc::CopyOnWriteBuffer& buffer) {
5512 cricket::ReceiveDataParams params;
5513 params.sid = channel_id;
5514 params.type = ToCricketDataMessageType(type);
5515 media_transport_invoker_->AsyncInvoke<void>(
5516 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5517 RTC_DCHECK_RUN_ON(signaling_thread());
5518 if (!HandleOpenMessage_s(params, buffer)) {
5519 SignalMediaTransportReceivedData_s(params, buffer);
5520 }
5521 });
5522}
5523
5524void PeerConnection::OnChannelClosing(int channel_id) {
5525 media_transport_invoker_->AsyncInvoke<void>(
5526 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5527 RTC_DCHECK_RUN_ON(signaling_thread());
5528 SignalMediaTransportChannelClosing_s(channel_id);
5529 });
5530}
5531
5532void PeerConnection::OnChannelClosed(int channel_id) {
5533 media_transport_invoker_->AsyncInvoke<void>(
5534 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5535 RTC_DCHECK_RUN_ON(signaling_thread());
5536 SignalMediaTransportChannelClosed_s(channel_id);
5537 });
5538}
5539
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005540absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005541 if (sctp_mid_ && transport_controller_) {
5542 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5543 if (dtls_transport) {
5544 return dtls_transport->transport_name();
5545 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005546 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005547 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005548 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005549}
5550
Qingsi Wang72a43a12018-02-20 16:03:18 -08005551cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5552 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005553 network_thread()->Invoke<void>(
5554 RTC_FROM_HERE,
5555 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5556 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005557 return candidate_states_list;
5558}
5559
Steve Anton5dfde182018-02-06 10:34:40 -08005560std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5561 const {
5562 std::map<std::string, std::string> transport_names_by_mid;
5563 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005564 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005565 if (channel) {
5566 transport_names_by_mid[channel->content_name()] =
5567 channel->transport_name();
5568 }
Steve Anton75737c02017-11-06 10:37:17 -08005569 }
Steve Anton5dfde182018-02-06 10:34:40 -08005570 if (rtp_data_channel_) {
5571 transport_names_by_mid[rtp_data_channel_->content_name()] =
5572 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005573 }
5574 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005575 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005576 RTC_DCHECK(transport_name);
5577 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005578 }
Steve Anton5dfde182018-02-06 10:34:40 -08005579 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005580}
5581
Steve Anton5dfde182018-02-06 10:34:40 -08005582std::map<std::string, cricket::TransportStats>
5583PeerConnection::GetTransportStatsByNames(
5584 const std::set<std::string>& transport_names) {
5585 if (!network_thread()->IsCurrent()) {
5586 return network_thread()
5587 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5588 RTC_FROM_HERE,
5589 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005590 }
Steve Anton5dfde182018-02-06 10:34:40 -08005591 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5592 for (const std::string& transport_name : transport_names) {
5593 cricket::TransportStats transport_stats;
5594 bool success =
5595 transport_controller_->GetStats(transport_name, &transport_stats);
5596 if (success) {
5597 transport_stats_by_name[transport_name] = std::move(transport_stats);
5598 } else {
5599 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5600 << transport_name;
5601 }
5602 }
5603 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005604}
5605
5606bool PeerConnection::GetLocalCertificate(
5607 const std::string& transport_name,
5608 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005609 if (!certificate) {
5610 return false;
5611 }
5612 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5613 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005614}
5615
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005616std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005617 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005618 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005619}
5620
5621cricket::DataChannelType PeerConnection::data_channel_type() const {
5622 return data_channel_type_;
5623}
5624
5625bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5626 return pending_ice_restarts_.find(content_name) !=
5627 pending_ice_restarts_.end();
5628}
5629
Steve Anton75737c02017-11-06 10:37:17 -08005630bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5631 return transport_controller_->NeedsIceRestart(content_name);
5632}
5633
5634void PeerConnection::OnCertificateReady(
5635 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5636 transport_controller_->SetLocalCertificate(certificate);
5637}
5638
5639void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005640 SetSessionError(SessionError::kTransport,
5641 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005642}
5643
Alex Loiko9289eda2018-11-23 16:18:59 +00005644void PeerConnection::OnTransportControllerConnectionState(
5645 cricket::IceConnectionState state) {
5646 switch (state) {
5647 case cricket::kIceConnectionConnecting:
5648 // If the current state is Connected or Completed, then there were
5649 // writable channels but now there are not, so the next state must
5650 // be Disconnected.
5651 // kIceConnectionConnecting is currently used as the default,
5652 // un-connected state by the TransportController, so its only use is
5653 // detecting disconnections.
5654 if (ice_connection_state_ ==
5655 PeerConnectionInterface::kIceConnectionConnected ||
5656 ice_connection_state_ ==
5657 PeerConnectionInterface::kIceConnectionCompleted) {
5658 SetIceConnectionState(
5659 PeerConnectionInterface::kIceConnectionDisconnected);
5660 }
5661 break;
5662 case cricket::kIceConnectionFailed:
5663 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5664 break;
5665 case cricket::kIceConnectionConnected:
5666 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5667 "all transports are writable.";
5668 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5669 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5670 break;
5671 case cricket::kIceConnectionCompleted:
5672 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5673 "all transports are complete.";
5674 if (ice_connection_state_ !=
5675 PeerConnectionInterface::kIceConnectionConnected) {
5676 // If jumping directly from "checking" to "connected",
5677 // signal "connected" first.
5678 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5679 }
5680 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5681 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5682 ReportTransportStats();
5683 break;
5684 default:
5685 RTC_NOTREACHED();
5686 }
5687}
5688
Steve Anton75737c02017-11-06 10:37:17 -08005689void PeerConnection::OnTransportControllerCandidatesGathered(
5690 const std::string& transport_name,
5691 const cricket::Candidates& candidates) {
5692 RTC_DCHECK(signaling_thread()->IsCurrent());
5693 int sdp_mline_index;
5694 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005695 RTC_LOG(LS_ERROR)
5696 << "OnTransportControllerCandidatesGathered: content name "
5697 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005698 return;
5699 }
5700
5701 for (cricket::Candidates::const_iterator citer = candidates.begin();
5702 citer != candidates.end(); ++citer) {
5703 // Use transport_name as the candidate media id.
5704 std::unique_ptr<JsepIceCandidate> candidate(
5705 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5706 if (local_description()) {
5707 mutable_local_description()->AddCandidate(candidate.get());
5708 }
5709 OnIceCandidate(std::move(candidate));
5710 }
5711}
5712
5713void PeerConnection::OnTransportControllerCandidatesRemoved(
5714 const std::vector<cricket::Candidate>& candidates) {
5715 RTC_DCHECK(signaling_thread()->IsCurrent());
5716 // Sanity check.
5717 for (const cricket::Candidate& candidate : candidates) {
5718 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005719 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005720 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005721 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005722 return;
5723 }
5724 }
5725
5726 if (local_description()) {
5727 mutable_local_description()->RemoveCandidates(candidates);
5728 }
5729 OnIceCandidatesRemoved(candidates);
5730}
5731
5732void PeerConnection::OnTransportControllerDtlsHandshakeError(
5733 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005734 RTC_HISTOGRAM_ENUMERATION(
5735 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5736 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005737}
5738
Steve Antoned10bd92017-12-05 10:52:59 -08005739void PeerConnection::EnableSending() {
5740 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005741 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005742 if (channel && !channel->enabled()) {
5743 channel->Enable(true);
5744 }
Steve Anton75737c02017-11-06 10:37:17 -08005745 }
5746
Steve Anton4171afb2017-11-20 10:20:22 -08005747 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005748 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005749 }
Steve Anton75737c02017-11-06 10:37:17 -08005750}
5751
5752// Returns the media index for a local ice candidate given the content name.
5753bool PeerConnection::GetLocalCandidateMediaIndex(
5754 const std::string& content_name,
5755 int* sdp_mline_index) {
5756 if (!local_description() || !sdp_mline_index) {
5757 return false;
5758 }
5759
5760 bool content_found = false;
5761 const ContentInfos& contents = local_description()->description()->contents();
5762 for (size_t index = 0; index < contents.size(); ++index) {
5763 if (contents[index].name == content_name) {
5764 *sdp_mline_index = static_cast<int>(index);
5765 content_found = true;
5766 break;
5767 }
5768 }
5769 return content_found;
5770}
5771
5772bool PeerConnection::UseCandidatesInSessionDescription(
5773 const SessionDescriptionInterface* remote_desc) {
5774 if (!remote_desc) {
5775 return true;
5776 }
5777 bool ret = true;
5778
5779 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5780 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5781 for (size_t n = 0; n < candidates->count(); ++n) {
5782 const IceCandidateInterface* candidate = candidates->at(n);
5783 bool valid = false;
5784 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5785 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005786 RTC_LOG(LS_INFO)
5787 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005788 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005789 }
5790 continue;
5791 }
5792 ret = UseCandidate(candidate);
5793 if (!ret) {
5794 break;
5795 }
5796 }
5797 }
5798 return ret;
5799}
5800
5801bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5802 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5803 size_t remote_content_size =
5804 remote_description()->description()->contents().size();
5805 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005806 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005807 return false;
5808 }
5809
5810 cricket::ContentInfo content =
5811 remote_description()->description()->contents()[mediacontent_index];
5812 std::vector<cricket::Candidate> candidates;
5813 candidates.push_back(candidate->candidate());
5814 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005815 RTCError error =
5816 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005817 if (error.ok()) {
5818 // Candidates successfully submitted for checking.
5819 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5820 ice_connection_state_ ==
5821 PeerConnectionInterface::kIceConnectionDisconnected) {
5822 // If state is New, then the session has just gotten its first remote ICE
5823 // candidates, so go to Checking.
5824 // If state is Disconnected, the session is re-using old candidates or
5825 // receiving additional ones, so go to Checking.
5826 // If state is Connected, stay Connected.
5827 // TODO(bemasc): If state is Connected, and the new candidates are for a
5828 // newly added transport, then the state actually _should_ move to
5829 // checking. Add a way to distinguish that case.
5830 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5831 }
5832 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005833 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005834 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005835 }
5836 return true;
5837}
5838
5839void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005840 // Destroy video channel first since it may have a pointer to the
5841 // voice channel.
5842 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005843 if (!video_info || video_info->rejected) {
5844 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005845 }
5846
Steve Anton6fec8802017-12-04 10:37:29 -08005847 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5848 if (!audio_info || audio_info->rejected) {
5849 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005850 }
5851
5852 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5853 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005854 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005855 }
5856}
5857
Steve Antondcc3c022017-12-22 16:02:54 -08005858RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5859 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005860 const cricket::ContentGroup* bundle_group = nullptr;
5861 if (configuration_.bundle_policy ==
5862 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005863 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005864 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5866 "max-bundle configured but session description "
5867 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005868 }
5869 }
Steve Antondcc3c022017-12-22 16:02:54 -08005870 return std::move(bundle_group);
5871}
5872
5873RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005874 // Creating the media channels. Transports should already have been created
5875 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005876 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005877 if (voice && !voice->rejected &&
5878 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005879 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005880 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005881 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5882 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005883 }
5884 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5885 }
5886
Steve Antondcc3c022017-12-22 16:02:54 -08005887 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005888 if (video && !video->rejected &&
5889 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005890 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005891 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005892 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5893 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005894 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005895 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005896 }
5897
Steve Antondcc3c022017-12-22 16:02:54 -08005898 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005899 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005900 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005901 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005902 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5903 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005904 }
5905 }
5906
Steve Anton8a006912017-12-04 15:25:56 -08005907 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005908}
5909
Steve Anton4171afb2017-11-20 10:20:22 -08005910// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005911cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005912 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005913 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005914 MediaTransportInterface* media_transport = nullptr;
5915 if (configuration_.use_media_transport) {
5916 media_transport = GetMediaTransport(mid);
5917 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005918
Steve Anton75737c02017-11-06 10:37:17 -08005919 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005920 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005921 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5922 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005923 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005924 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005925 }
Steve Anton75737c02017-11-06 10:37:17 -08005926 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5927 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005928 voice_channel->SignalSentPacket.connect(this,
5929 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005930 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005931
Steve Antoneda6ccd2017-12-04 10:21:55 -08005932 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005933}
5934
Steve Anton4171afb2017-11-20 10:20:22 -08005935// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005936cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005937 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005938 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5939
5940 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005941 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005942 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005943 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5944 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005945 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005946 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005947 }
Steve Anton75737c02017-11-06 10:37:17 -08005948 video_channel->SignalDtlsSrtpSetupFailure.connect(
5949 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005950 video_channel->SignalSentPacket.connect(this,
5951 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005952 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005953
Steve Antoneda6ccd2017-12-04 10:21:55 -08005954 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005955}
5956
Zhi Huange830e682018-03-30 10:48:35 -07005957bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005958 switch (data_channel_type_) {
5959 case cricket::DCT_MEDIA_TRANSPORT:
5960 if (network_thread()->Invoke<bool>(
5961 RTC_FROM_HERE,
5962 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5963 this, mid))) {
5964 for (const auto& channel : sctp_data_channels_) {
5965 channel->OnTransportChannelCreated();
5966 }
5967 return true;
5968 }
Steve Anton75737c02017-11-06 10:37:17 -08005969 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005970 case cricket::DCT_SCTP:
5971 if (!sctp_factory_) {
5972 RTC_LOG(LS_ERROR)
5973 << "Trying to create SCTP transport, but didn't compile with "
5974 "SCTP support (HAVE_SCTP)";
5975 return false;
5976 }
5977 if (!network_thread()->Invoke<bool>(
5978 RTC_FROM_HERE,
5979 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5980 return false;
5981 }
5982 for (const auto& channel : sctp_data_channels_) {
5983 channel->OnTransportChannelCreated();
5984 }
5985 return true;
5986 case cricket::DCT_RTP:
5987 default:
5988 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5989 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5990 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5991 SrtpRequired(), GetCryptoOptions());
5992 if (!rtp_data_channel_) {
5993 return false;
5994 }
5995 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5996 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5997 rtp_data_channel_->SignalSentPacket.connect(
5998 this, &PeerConnection::OnSentPacket_w);
5999 rtp_data_channel_->SetRtpTransport(rtp_transport);
6000 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006001 }
6002
Steve Anton75737c02017-11-06 10:37:17 -08006003 return true;
6004}
6005
6006Call::Stats PeerConnection::GetCallStats() {
6007 if (!worker_thread()->IsCurrent()) {
6008 return worker_thread()->Invoke<Call::Stats>(
6009 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6010 }
6011 if (call_) {
6012 return call_->GetStats();
6013 } else {
6014 return Call::Stats();
6015 }
6016}
6017
Zhi Huange830e682018-03-30 10:48:35 -07006018bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006019 RTC_DCHECK(network_thread()->IsCurrent());
6020 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006021 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006022 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006023 RTC_DCHECK(dtls_transport);
6024 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006025 RTC_DCHECK(sctp_transport_);
6026 sctp_invoker_.reset(new rtc::AsyncInvoker());
6027 sctp_transport_->SignalReadyToSendData.connect(
6028 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6029 sctp_transport_->SignalDataReceived.connect(
6030 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006031 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6032 // another thread. Would be nice if there was a helper class similar to
6033 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6034 // code.
6035 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6036 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6037 sctp_transport_->SignalClosingProcedureComplete.connect(
6038 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006039 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006040 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006041 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006042}
6043
6044void PeerConnection::DestroySctpTransport_n() {
6045 RTC_DCHECK(network_thread()->IsCurrent());
6046 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006047 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006048 sctp_invoker_.reset(nullptr);
6049 sctp_ready_to_send_data_ = false;
6050}
6051
6052void PeerConnection::OnSctpTransportReadyToSendData_n() {
6053 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6054 RTC_DCHECK(network_thread()->IsCurrent());
6055 // Note: Cannot use rtc::Bind here because it will grab a reference to
6056 // PeerConnection and potentially cause PeerConnection to live longer than
6057 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6058 // be destroyed before PeerConnection is destroyed, and at that point all
6059 // pending tasks will be cleared.
6060 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6061 OnSctpTransportReadyToSendData_s(true);
6062 });
6063}
6064
6065void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6066 RTC_DCHECK(signaling_thread()->IsCurrent());
6067 sctp_ready_to_send_data_ = ready;
6068 SignalSctpReadyToSendData(ready);
6069}
6070
6071void PeerConnection::OnSctpTransportDataReceived_n(
6072 const cricket::ReceiveDataParams& params,
6073 const rtc::CopyOnWriteBuffer& payload) {
6074 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6075 RTC_DCHECK(network_thread()->IsCurrent());
6076 // Note: Cannot use rtc::Bind here because it will grab a reference to
6077 // PeerConnection and potentially cause PeerConnection to live longer than
6078 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6079 // be destroyed before PeerConnection is destroyed, and at that point all
6080 // pending tasks will be cleared.
6081 sctp_invoker_->AsyncInvoke<void>(
6082 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6083 OnSctpTransportDataReceived_s(params, payload);
6084 });
6085}
6086
6087void PeerConnection::OnSctpTransportDataReceived_s(
6088 const cricket::ReceiveDataParams& params,
6089 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006090 RTC_DCHECK_RUN_ON(signaling_thread());
6091 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006092 SignalSctpDataReceived(params, payload);
6093 }
6094}
6095
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006096void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006097 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6098 RTC_DCHECK(network_thread()->IsCurrent());
6099 sctp_invoker_->AsyncInvoke<void>(
6100 RTC_FROM_HERE, signaling_thread(),
6101 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006102 &SignalSctpClosingProcedureStartedRemotely, sid));
6103}
6104
6105void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6106 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6107 RTC_DCHECK(network_thread()->IsCurrent());
6108 sctp_invoker_->AsyncInvoke<void>(
6109 RTC_FROM_HERE, signaling_thread(),
6110 rtc::Bind(&sigslot::signal1<int>::operator(),
6111 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006112}
6113
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006114bool PeerConnection::SetupMediaTransportForDataChannels_n(
6115 const std::string& mid) {
6116 media_transport_ = transport_controller_->GetMediaTransport(mid);
6117 if (!media_transport_) {
6118 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6119 return false;
6120 }
6121
6122 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6123 media_transport_->SetDataSink(this);
6124 media_transport_data_mid_ = mid;
6125 transport_controller_->SignalMediaTransportStateChanged.connect(
6126 this, &PeerConnection::OnMediaTransportStateChanged_n);
6127 // Check the initial state right away, in case transport is already writable.
6128 OnMediaTransportStateChanged_n();
6129 return true;
6130}
6131
6132void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6133 if (!media_transport_) {
6134 return;
6135 }
6136 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6137 media_transport_data_mid_.reset();
6138 media_transport_->SetDataSink(nullptr);
6139 media_transport_invoker_ = nullptr;
6140 media_transport_ = nullptr;
6141}
6142
6143void PeerConnection::OnMediaTransportStateChanged_n() {
6144 if (!media_transport_data_mid_ ||
6145 transport_controller_->GetMediaTransportState(
6146 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6147 return;
6148 }
6149 media_transport_invoker_->AsyncInvoke<void>(
6150 RTC_FROM_HERE, signaling_thread(), [this] {
6151 RTC_DCHECK_RUN_ON(signaling_thread());
6152 media_transport_ready_to_send_data_ = true;
6153 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6154 });
6155}
6156
Steve Anton75737c02017-11-06 10:37:17 -08006157// Returns false if bundle is enabled and rtcp_mux is disabled.
6158bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6159 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6160 if (!bundle_enabled)
6161 return true;
6162
6163 const cricket::ContentGroup* bundle_group =
6164 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6165 RTC_DCHECK(bundle_group != NULL);
6166
6167 const cricket::ContentInfos& contents = desc->contents();
6168 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6169 citer != contents.end(); ++citer) {
6170 const cricket::ContentInfo* content = (&*citer);
6171 RTC_DCHECK(content != NULL);
6172 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006173 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006174 if (!HasRtcpMuxEnabled(content))
6175 return false;
6176 }
6177 }
6178 // RTCP-MUX is enabled in all the contents.
6179 return true;
6180}
6181
6182bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006183 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006184}
6185
Steve Anton06817cd2018-12-18 15:55:30 -08006186static RTCError ValidateMids(const cricket::SessionDescription& description) {
6187 std::set<std::string> mids;
6188 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006189 if (content.name.empty()) {
6190 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6191 "A media section is missing a MID attribute.");
6192 }
Steve Anton06817cd2018-12-18 15:55:30 -08006193 if (!mids.insert(content.name).second) {
6194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6195 "Duplicate a=mid value '" + content.name + "'.");
6196 }
6197 }
6198 return RTCError::OK();
6199}
6200
Steve Anton8a006912017-12-04 15:25:56 -08006201RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006202 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006203 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006204 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006205 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006206 }
6207
6208 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006209 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006210 }
6211
Steve Anton3828c062017-12-06 10:34:51 -08006212 SdpType type = sdesc->GetType();
6213 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6214 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006215 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006216 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006217 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006218 }
6219
Steve Anton06817cd2018-12-18 15:55:30 -08006220 RTCError error = ValidateMids(*sdesc->description());
6221 if (!error.ok()) {
6222 return error;
6223 }
6224
Steve Anton75737c02017-11-06 10:37:17 -08006225 // Verify crypto settings.
6226 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006227 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6228 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006229 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006230 if (!crypto_error.ok()) {
6231 return crypto_error;
6232 }
Steve Anton75737c02017-11-06 10:37:17 -08006233 }
6234
6235 // Verify ice-ufrag and ice-pwd.
6236 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006237 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6238 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006239 }
6240
6241 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006242 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6243 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006244 }
6245
6246 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6247 // m-lines that do not rtcp-mux enabled.
6248
6249 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006250 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006251 // With an answer we want to compare the new answer session description with
6252 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006253 const cricket::SessionDescription* offer_desc =
6254 (source == cricket::CS_LOCAL) ? remote_description()->description()
6255 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006256 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6257 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6258 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6260 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006261 }
6262 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006263 // The re-offers should respect the order of m= sections in current
6264 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006265 // With a re-offer, either the current local or current remote descriptions
6266 // could be the most up to date, so we would like to check against both of
6267 // them if they exist. It could be the case that one of them has a 0 port
6268 // for a media section, but the other does not. This is important to check
6269 // against in the case that we are recycling an m= section.
6270 const cricket::SessionDescription* current_desc = nullptr;
6271 const cricket::SessionDescription* secondary_current_desc = nullptr;
6272 if (local_description()) {
6273 current_desc = local_description()->description();
6274 if (remote_description()) {
6275 secondary_current_desc = remote_description()->description();
6276 }
6277 } else if (remote_description()) {
6278 current_desc = remote_description()->description();
6279 }
Steve Anton75737c02017-11-06 10:37:17 -08006280 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006281 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6282 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006283 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6284 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006285 }
6286 }
6287
Steve Antonba42e992018-04-09 14:10:01 -07006288 if (IsUnifiedPlan()) {
6289 // Ensure that each audio and video media section has at most one
6290 // "StreamParams". This will return an error if receiving a session
6291 // description from a "Plan B" endpoint which adds multiple tracks of the
6292 // same type. With Unified Plan, there can only be at most one track per
6293 // media section.
6294 for (const ContentInfo& content : sdesc->description()->contents()) {
6295 const MediaContentDescription& desc = *content.description;
6296 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6297 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6298 desc.streams().size() > 1u) {
6299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6300 "Media section has more than one track specified "
6301 "with a=ssrc lines which is not supported with "
6302 "Unified Plan.");
6303 }
6304 }
6305 }
6306
Steve Anton8a006912017-12-04 15:25:56 -08006307 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006308}
6309
Steve Anton3828c062017-12-06 10:34:51 -08006310bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006311 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006312 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006313 return (state == PeerConnectionInterface::kStable) ||
6314 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006315 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006316 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006317 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6318 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6319 }
6320}
6321
Steve Anton3828c062017-12-06 10:34:51 -08006322bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006323 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006324 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006325 return (state == PeerConnectionInterface::kStable) ||
6326 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006327 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006328 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006329 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6330 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6331 }
6332}
6333
Steve Antonf8470812017-12-04 10:46:21 -08006334const char* PeerConnection::SessionErrorToString(SessionError error) const {
6335 switch (error) {
6336 case SessionError::kNone:
6337 return "ERROR_NONE";
6338 case SessionError::kContent:
6339 return "ERROR_CONTENT";
6340 case SessionError::kTransport:
6341 return "ERROR_TRANSPORT";
6342 }
6343 RTC_NOTREACHED();
6344 return "";
6345}
6346
Steve Anton75737c02017-11-06 10:37:17 -08006347std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006348 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006349 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6350 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006351 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006352}
6353
Steve Anton8e20f172018-03-06 10:55:04 -08006354void PeerConnection::ReportSdpFormatReceived(
6355 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006356 int num_audio_mlines = 0;
6357 int num_video_mlines = 0;
6358 int num_audio_tracks = 0;
6359 int num_video_tracks = 0;
6360 for (const ContentInfo& content : remote_offer.description()->contents()) {
6361 cricket::MediaType media_type = content.media_description()->type();
6362 int num_tracks = std::max(
6363 1, static_cast<int>(content.media_description()->streams().size()));
6364 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6365 num_audio_mlines += 1;
6366 num_audio_tracks += num_tracks;
6367 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6368 num_video_mlines += 1;
6369 num_video_tracks += num_tracks;
6370 }
6371 }
6372 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6373 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6374 format = kSdpFormatReceivedComplexUnifiedPlan;
6375 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6376 format = kSdpFormatReceivedComplexPlanB;
6377 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6378 format = kSdpFormatReceivedSimple;
6379 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006380 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6381 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006382}
6383
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006384void PeerConnection::NoteUsageEvent(UsageEvent event) {
6385 RTC_DCHECK_RUN_ON(signaling_thread());
6386 usage_event_accumulator_ |= static_cast<int>(event);
6387}
6388
6389void PeerConnection::ReportUsagePattern() const {
6390 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006391 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6392 usage_event_accumulator_,
6393 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006394 const int bad_bits =
6395 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6396 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6397 const int good_bits =
6398 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6399 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6400 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6401 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6402 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006403 // If called after close(), we can't report, because observer may have
6404 // been deallocated, and therefore pointer is null. Write to log instead.
6405 if (observer_) {
6406 Observer()->OnInterestingUsage(usage_event_accumulator_);
6407 } else {
6408 RTC_LOG(LS_INFO) << "Interesting usage signature "
6409 << usage_event_accumulator_
6410 << " observed after observer shutdown";
6411 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006412 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006413}
6414
Steve Anton0ffaaa22018-02-23 10:31:30 -08006415void PeerConnection::ReportNegotiatedSdpSemantics(
6416 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006417 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006418 switch (answer.description()->msid_signaling()) {
6419 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006420 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006421 break;
6422 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006423 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006424 break;
6425 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006426 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006427 break;
6428 case cricket::kMsidSignalingMediaSection |
6429 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006430 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006431 break;
6432 default:
6433 RTC_NOTREACHED();
6434 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006435 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6436 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006437}
6438
Steve Anton75737c02017-11-06 10:37:17 -08006439// We need to check the local/remote description for the Transport instead of
6440// the session, because a new Transport added during renegotiation may have
6441// them unset while the session has them set from the previous negotiation.
6442// Not doing so may trigger the auto generation of transport description and
6443// mess up DTLS identity information, ICE credential, etc.
6444bool PeerConnection::ReadyToUseRemoteCandidate(
6445 const IceCandidateInterface* candidate,
6446 const SessionDescriptionInterface* remote_desc,
6447 bool* valid) {
6448 *valid = true;
6449
6450 const SessionDescriptionInterface* current_remote_desc =
6451 remote_desc ? remote_desc : remote_description();
6452
6453 if (!current_remote_desc) {
6454 return false;
6455 }
6456
6457 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6458 size_t remote_content_size =
6459 current_remote_desc->description()->contents().size();
6460 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006461 RTC_LOG(LS_ERROR)
6462 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6463 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006464
6465 *valid = false;
6466 return false;
6467 }
6468
6469 cricket::ContentInfo content =
6470 current_remote_desc->description()->contents()[mediacontent_index];
6471
6472 const std::string transport_name = GetTransportName(content.name);
6473 if (transport_name.empty()) {
6474 return false;
6475 }
Zhi Huange830e682018-03-30 10:48:35 -07006476 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006477}
6478
6479bool PeerConnection::SrtpRequired() const {
6480 return dtls_enabled_ ||
6481 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6482}
6483
6484void PeerConnection::OnTransportControllerGatheringState(
6485 cricket::IceGatheringState state) {
6486 RTC_DCHECK(signaling_thread()->IsCurrent());
6487 if (state == cricket::kIceGatheringGathering) {
6488 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6489 } else if (state == cricket::kIceGatheringComplete) {
6490 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6491 }
6492}
6493
6494void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006495 std::map<std::string, std::set<cricket::MediaType>>
6496 media_types_by_transport_name;
6497 for (auto transceiver : transceivers_) {
6498 if (transceiver->internal()->channel()) {
6499 const std::string& transport_name =
6500 transceiver->internal()->channel()->transport_name();
6501 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006502 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006503 }
Steve Anton75737c02017-11-06 10:37:17 -08006504 }
6505 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006506 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6507 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006508 }
Zhi Huange830e682018-03-30 10:48:35 -07006509
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006510 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006511 if (transport_name) {
6512 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006513 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006514 }
Zhi Huange830e682018-03-30 10:48:35 -07006515
Steve Antonc7b964c2018-02-01 14:39:45 -08006516 for (const auto& entry : media_types_by_transport_name) {
6517 const std::string& transport_name = entry.first;
6518 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006519 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006520 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006521 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006522 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006523 }
6524 }
6525}
6526// Walk through the ConnectionInfos to gather best connection usage
6527// for IPv4 and IPv6.
6528void PeerConnection::ReportBestConnectionState(
6529 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006530 for (const cricket::TransportChannelStats& channel_stats :
6531 stats.channel_stats) {
6532 for (const cricket::ConnectionInfo& connection_info :
6533 channel_stats.connection_infos) {
6534 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006535 continue;
6536 }
6537
Steve Antonc7b964c2018-02-01 14:39:45 -08006538 const cricket::Candidate& local = connection_info.local_candidate;
6539 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006540
6541 // Increment the counter for IceCandidatePairType.
6542 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6543 (local.type() == RELAY_PORT_TYPE &&
6544 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006545 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6546 GetIceCandidatePairCounter(local, remote),
6547 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006548 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006549 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6550 GetIceCandidatePairCounter(local, remote),
6551 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006552 } else {
6553 RTC_CHECK(0);
6554 }
Steve Anton75737c02017-11-06 10:37:17 -08006555
6556 // Increment the counter for IP type.
6557 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006558 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6559 kBestConnections_IPv4,
6560 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006561 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006562 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6563 kBestConnections_IPv6,
6564 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006565 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006566 RTC_CHECK(!local.address().hostname().empty() &&
6567 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006568 }
6569
6570 return;
6571 }
6572 }
6573}
6574
6575void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006576 const cricket::TransportStats& stats,
6577 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006578 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6579 return;
6580 }
6581
6582 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6583 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6584 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6585 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6586 return;
6587 }
6588
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006589 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6590 for (cricket::MediaType media_type : media_types) {
6591 switch (media_type) {
6592 case cricket::MEDIA_TYPE_AUDIO:
6593 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6594 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6595 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6596 break;
6597 case cricket::MEDIA_TYPE_VIDEO:
6598 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6599 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6600 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6601 break;
6602 case cricket::MEDIA_TYPE_DATA:
6603 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6604 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6605 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6606 break;
6607 default:
6608 RTC_NOTREACHED();
6609 continue;
6610 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006611 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006612 }
6613
6614 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6615 for (cricket::MediaType media_type : media_types) {
6616 switch (media_type) {
6617 case cricket::MEDIA_TYPE_AUDIO:
6618 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6619 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6620 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6621 break;
6622 case cricket::MEDIA_TYPE_VIDEO:
6623 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6624 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6625 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6626 break;
6627 case cricket::MEDIA_TYPE_DATA:
6628 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6629 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6630 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6631 break;
6632 default:
6633 RTC_NOTREACHED();
6634 continue;
6635 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006636 }
Steve Anton75737c02017-11-06 10:37:17 -08006637 }
6638}
6639
6640void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6641 RTC_DCHECK(worker_thread()->IsCurrent());
6642 RTC_DCHECK(call_);
6643 call_->OnSentPacket(sent_packet);
6644}
6645
6646const std::string PeerConnection::GetTransportName(
6647 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006648 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006649 if (channel) {
6650 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006651 }
Steve Anton6fec8802017-12-04 10:37:29 -08006652 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006653 RTC_DCHECK(sctp_mid_);
6654 if (content_name == *sctp_mid_) {
6655 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006656 }
6657 }
6658 // Return an empty string if failed to retrieve the transport name.
6659 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006660}
6661
Steve Anton6fec8802017-12-04 10:37:29 -08006662void PeerConnection::DestroyTransceiverChannel(
6663 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6664 transceiver) {
6665 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006666
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006667 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006668 if (channel) {
6669 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006670 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006671 }
6672}
6673
6674void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006675 if (rtp_data_channel_) {
6676 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006677 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006678 rtp_data_channel_ = nullptr;
6679 }
6680
6681 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6682 // grab a reference to this PeerConnection. If this is called from the
6683 // PeerConnection destructor, the RefCountedObject vtable will have already
6684 // been destroyed (since it is a subclass of PeerConnection) and using
6685 // rtc::Bind will cause "Pure virtual function called" error to appear.
6686
6687 if (sctp_transport_) {
6688 OnDataChannelDestroyed();
6689 network_thread()->Invoke<void>(RTC_FROM_HERE,
6690 [this] { DestroySctpTransport_n(); });
6691 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006692
6693 if (media_transport_) {
6694 OnDataChannelDestroyed();
6695 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6696 RTC_DCHECK_RUN_ON(network_thread());
6697 TeardownMediaTransportForDataChannels_n();
6698 });
6699 }
Steve Anton6fec8802017-12-04 10:37:29 -08006700}
6701
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006702void PeerConnection::DestroyChannelInterface(
6703 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006704 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006705 switch (channel->media_type()) {
6706 case cricket::MEDIA_TYPE_AUDIO:
6707 channel_manager()->DestroyVoiceChannel(
6708 static_cast<cricket::VoiceChannel*>(channel));
6709 break;
6710 case cricket::MEDIA_TYPE_VIDEO:
6711 channel_manager()->DestroyVideoChannel(
6712 static_cast<cricket::VideoChannel*>(channel));
6713 break;
6714 case cricket::MEDIA_TYPE_DATA:
6715 channel_manager()->DestroyRtpDataChannel(
6716 static_cast<cricket::RtpDataChannel*>(channel));
6717 break;
6718 default:
6719 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6720 break;
6721 }
Zhi Huange830e682018-03-30 10:48:35 -07006722}
Steve Anton6fec8802017-12-04 10:37:29 -08006723
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006724bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006725 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006726 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006727 cricket::DtlsTransportInternal* dtls_transport,
6728 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006729 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006730 auto base_channel = GetChannel(mid);
6731 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006732 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006733 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006734 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006735 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006736 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006737
6738 call_->MediaTransportChange(media_transport);
6739
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006740 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006741}
6742
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006743PeerConnectionObserver* PeerConnection::Observer() const {
6744 // In earlier production code, the pointer was not cleared on close,
6745 // which might have led to undefined behavior if the observer was not
6746 // deallocated, or strange crashes if it was.
6747 // We use CHECK in order to catch such behavior if it exists.
6748 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6749 RTC_CHECK(observer_);
6750 return observer_;
6751}
6752
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006753CryptoOptions PeerConnection::GetCryptoOptions() {
6754 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6755 // after it has been removed.
6756 return configuration_.crypto_options.has_value()
6757 ? *configuration_.crypto_options
6758 : factory_->options().crypto_options;
6759}
6760
Harald Alvestrand89061872018-01-02 14:08:34 +01006761void PeerConnection::ClearStatsCache() {
6762 if (stats_collector_) {
6763 stats_collector_->ClearCachedStatsReport();
6764 }
6765}
6766
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006767void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006768 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6769 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006770}
6771
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006772} // namespace webrtc