blob: da34cc29353eea6402e47a439247b276ab7ed3c8 [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;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800280 bool local_hostname =
281 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
282 bool remote_hostname = !remote.address().hostname().empty() &&
283 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800284 bool local_private = IPIsPrivate(local.address().ipaddr());
285 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800286 if (local_hostname) {
287 if (remote_hostname) {
288 return kIceCandidatePairHostNameHostName;
289 } else if (remote_private) {
290 return kIceCandidatePairHostNameHostPrivate;
291 } else {
292 return kIceCandidatePairHostNameHostPublic;
293 }
294 } else if (local_private) {
295 if (remote_hostname) {
296 return kIceCandidatePairHostPrivateHostName;
297 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800298 return kIceCandidatePairHostPrivateHostPrivate;
299 } else {
300 return kIceCandidatePairHostPrivateHostPublic;
301 }
302 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800303 if (remote_hostname) {
304 return kIceCandidatePairHostPublicHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800306 return kIceCandidatePairHostPublicHostPrivate;
307 } else {
308 return kIceCandidatePairHostPublicHostPublic;
309 }
310 }
311 }
312 if (l == host && r == srflx)
313 return kIceCandidatePairHostSrflx;
314 if (l == host && r == relay)
315 return kIceCandidatePairHostRelay;
316 if (l == host && r == prflx)
317 return kIceCandidatePairHostPrflx;
318 if (l == srflx && r == host)
319 return kIceCandidatePairSrflxHost;
320 if (l == srflx && r == srflx)
321 return kIceCandidatePairSrflxSrflx;
322 if (l == srflx && r == relay)
323 return kIceCandidatePairSrflxRelay;
324 if (l == srflx && r == prflx)
325 return kIceCandidatePairSrflxPrflx;
326 if (l == relay && r == host)
327 return kIceCandidatePairRelayHost;
328 if (l == relay && r == srflx)
329 return kIceCandidatePairRelaySrflx;
330 if (l == relay && r == relay)
331 return kIceCandidatePairRelayRelay;
332 if (l == relay && r == prflx)
333 return kIceCandidatePairRelayPrflx;
334 if (l == prflx && r == host)
335 return kIceCandidatePairPrflxHost;
336 if (l == prflx && r == srflx)
337 return kIceCandidatePairPrflxSrflx;
338 if (l == prflx && r == relay)
339 return kIceCandidatePairPrflxRelay;
340 return kIceCandidatePairMax;
341}
342
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// Logic to decide if an m= section can be recycled. This means that the new
344// m= section is not rejected, but the old local or remote m= section is
345// rejected. |old_content_one| and |old_content_two| refer to the m= section
346// of the old remote and old local descriptions in no particular order.
347// We need to check both the old local and remote because either
348// could be the most current from the latest negotation.
349bool IsMediaSectionBeingRecycled(SdpType type,
350 const ContentInfo& content,
351 const ContentInfo* old_content_one,
352 const ContentInfo* old_content_two) {
353 return type == SdpType::kOffer && !content.rejected &&
354 ((old_content_one && old_content_one->rejected) ||
355 (old_content_two && old_content_two->rejected));
356}
357
Steve Anton75737c02017-11-06 10:37:17 -0800358// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359// |current_desc|. The number of m= sections in |new_desc| should be no
360// less than |current_desc|. In the case of checking an answer's
361// |new_desc|, the |current_desc| is the last offer that was set as the
362// local or remote. In the case of checking an offer's |new_desc| we
363// check against the local and remote descriptions stored from the last
364// negotiation, because either of these could be the most up to date for
365// possible rejected m sections. These are the |current_desc| and
366// |secondary_current_desc|.
367bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
368 const SessionDescription* secondary_current_desc,
369 const SessionDescription& new_desc,
370 const SdpType type) {
371 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800375 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
376 const cricket::ContentInfo* secondary_content_info = nullptr;
377 if (secondary_current_desc &&
378 i < secondary_current_desc->contents().size()) {
379 secondary_content_info = &secondary_current_desc->contents()[i];
380 }
381 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
382 &current_desc.contents()[i],
383 secondary_content_info)) {
384 // For new offer descriptions, if the media section can be recycled, it's
385 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800386 continue;
387 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800389 return false;
390 }
391 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800392 new_desc.contents()[i].media_description();
393 const MediaContentDescription* current_desc_mdesc =
394 current_desc.contents()[i].media_description();
395 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800396 return false;
397 }
398 }
399 return true;
400}
401
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800402bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
403 const SessionDescription& desc2) {
404 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800405}
406
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700407void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
408 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200409 // Array of structs needed to map {KeyExchangeProtocolType,
410 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
411 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
412 static constexpr struct {
413 KeyExchangeProtocolType protocol_type;
414 cricket::MediaType media_type;
415 KeyExchangeProtocolMedia protocol_media;
416 } kEnumCounterKeyProtocolMediaMap[] = {
417 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
418 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
419 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
420 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
421 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
422 kEnumCounterKeyProtocolMediaTypeDtlsData},
423 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
424 kEnumCounterKeyProtocolMediaTypeSdesAudio},
425 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
426 kEnumCounterKeyProtocolMediaTypeSdesVideo},
427 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
428 kEnumCounterKeyProtocolMediaTypeSdesData},
429 };
430
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700431 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
432 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100433
Mirko Bonadeiab499822018-09-11 10:43:20 +0200434 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
435 if (i.protocol_type == protocol_type && i.media_type == media_type) {
436 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
437 i.protocol_media,
438 kEnumCounterKeyProtocolMediaTypeMax);
439 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100440 }
441}
442
Harald Alvestrand76829d72018-07-18 23:24:36 +0200443void NoteAddIceCandidateResult(int result) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
445 kAddIceCandidateMax);
446}
447
Steve Anton75737c02017-11-06 10:37:17 -0800448// Checks that each non-rejected content has SDES crypto keys or a DTLS
449// fingerprint, unless it's in a BUNDLE group, in which case only the
450// BUNDLE-tag section (first media section/description in the BUNDLE group)
451// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
452// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
453// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700454RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800455 const cricket::ContentGroup* bundle =
456 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800457 for (const cricket::ContentInfo& content_info : desc->contents()) {
458 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800459 continue;
460 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100461 // Note what media is used with each crypto protocol, for all sections.
462 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
463 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700464 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800465 const std::string& mid = content_info.name;
466 if (bundle && bundle->HasContentName(mid) &&
467 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 // This isn't the first media section in the BUNDLE group, so it's not
469 // required to have crypto attributes, since only the crypto attributes
470 // from the first section actually get used.
471 continue;
472 }
473
474 // If the content isn't rejected or bundled into another m= section, crypto
475 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800477 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800478 if (!media || !tinfo) {
479 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800480 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800481 }
482 if (dtls_enabled) {
483 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100484 RTC_LOG(LS_WARNING)
485 << "Session description must have DTLS fingerprint if "
486 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800487 return RTCError(RTCErrorType::INVALID_PARAMETER,
488 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800489 }
490 } else {
491 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800493 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800494 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800495 }
496 }
497 }
Steve Anton8a006912017-12-04 15:25:56 -0800498 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800499}
500
501// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
502// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
503// media section/description in the BUNDLE group) needs a ufrag and pwd.
504bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
505 const cricket::ContentGroup* bundle =
506 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800507 for (const cricket::ContentInfo& content_info : desc->contents()) {
508 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800509 continue;
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 const std::string& mid = content_info.name;
512 if (bundle && bundle->HasContentName(mid) &&
513 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800514 // This isn't the first media section in the BUNDLE group, so it's not
515 // required to have ufrag/password, since only the ufrag/password from
516 // the first section actually get used.
517 continue;
518 }
519
520 // If the content isn't rejected or bundled into another m= section,
521 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800522 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800523 if (!tinfo) {
524 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100525 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800526 return false;
527 }
528 if (tinfo->description.ice_ufrag.empty() ||
529 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100530 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800531 return false;
532 }
533 }
534 return true;
535}
536
Steve Anton75737c02017-11-06 10:37:17 -0800537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200597 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200600 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200614absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200618 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700619 }
620 return rtc_configuration_parameter;
621}
622
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800623cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
624 switch (type) {
625 case DataMessageType::kText:
626 return cricket::DMT_TEXT;
627 case DataMessageType::kBinary:
628 return cricket::DMT_BINARY;
629 case DataMessageType::kControl:
630 return cricket::DMT_CONTROL;
631 default:
632 return cricket::DMT_NONE;
633 }
634 return cricket::DMT_NONE;
635}
636
637DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
638 switch (type) {
639 case cricket::DMT_TEXT:
640 return DataMessageType::kText;
641 case cricket::DMT_BINARY:
642 return DataMessageType::kBinary;
643 case cricket::DMT_CONTROL:
644 return DataMessageType::kControl;
645 case cricket::DMT_NONE:
646 default:
647 RTC_NOTREACHED();
648 }
649 return DataMessageType::kControl;
650}
651
Steve Anton06817cd2018-12-18 15:55:30 -0800652// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
653// and return a reference to it.
654// Generated MIDs should be no more than 3 bytes long to take up less space in
655// the RTP packet.
656const std::string& AllocateMid(std::set<std::string>* used_mids) {
657 RTC_DCHECK(used_mids);
658 // We're boring: just generate MIDs 0, 1, 2, ...
659 size_t i = 0;
660 std::set<std::string>::iterator it;
661 bool inserted;
662 do {
663 std::string mid = rtc::ToString(i++);
664 auto insert_result = used_mids->insert(mid);
665 it = insert_result.first;
666 inserted = insert_result.second;
667 } while (!inserted);
668 return *it;
669}
670
Steve Anton75737c02017-11-06 10:37:17 -0800671} // namespace
672
Henrik Boström31638672017-11-23 17:48:32 +0100673// Upon completion, posts a task to execute the callback of the
674// SetSessionDescriptionObserver asynchronously on the same thread. At this
675// point, the state of the peer connection might no longer reflect the effects
676// of the SetRemoteDescription operation, as the peer connection could have been
677// modified during the post.
678// TODO(hbos): Remove this class once we remove the version of
679// PeerConnectionInterface::SetRemoteDescription() that takes a
680// SetSessionDescriptionObserver as an argument.
681class PeerConnection::SetRemoteDescriptionObserverAdapter
682 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
683 public:
684 SetRemoteDescriptionObserverAdapter(
685 rtc::scoped_refptr<PeerConnection> pc,
686 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
687 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
688
689 // SetRemoteDescriptionObserverInterface implementation.
690 void OnSetRemoteDescriptionComplete(RTCError error) override {
691 if (error.ok())
692 pc_->PostSetSessionDescriptionSuccess(wrapper_);
693 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100694 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100695 }
696
697 private:
698 rtc::scoped_refptr<PeerConnection> pc_;
699 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
700};
701
deadbeef293e9262017-01-11 12:28:30 -0800702bool PeerConnectionInterface::RTCConfiguration::operator==(
703 const PeerConnectionInterface::RTCConfiguration& o) const {
704 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800706 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000707 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700708 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800709 BundlePolicy bundle_policy;
710 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700711 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
712 int ice_candidate_pool_size;
713 bool disable_ipv6;
714 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700715 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100716 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700717 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200718 absl::optional<int> screencast_min_bitrate;
719 absl::optional<bool> combined_audio_video_bwe;
720 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800721 TcpCandidatePolicy tcp_candidate_policy;
722 CandidateNetworkPolicy candidate_network_policy;
723 int audio_jitter_buffer_max_packets;
724 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100725 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800726 int ice_connection_receiving_timeout;
727 int ice_backup_candidate_pair_ping_interval;
728 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800729 bool prioritize_most_likely_ice_candidate_pairs;
730 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800731 bool prune_turn_ports;
732 bool presume_writable_when_fully_relayed;
733 bool enable_ice_renomination;
734 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<int> ice_check_interval_strong_connectivity;
736 absl::optional<int> ice_check_interval_weak_connectivity;
737 absl::optional<int> ice_check_min_interval;
738 absl::optional<int> ice_unwritable_timeout;
739 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800740 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200741 absl::optional<int> stun_candidate_keepalive_interval;
742 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200743 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800744 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200745 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700746 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700747 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700748 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700749 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100750 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800751 };
752 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
753 "Did you add something to RTCConfiguration and forget to "
754 "update operator==?");
755 return type == o.type && servers == o.servers &&
756 bundle_policy == o.bundle_policy &&
757 rtcp_mux_policy == o.rtcp_mux_policy &&
758 tcp_candidate_policy == o.tcp_candidate_policy &&
759 candidate_network_policy == o.candidate_network_policy &&
760 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
761 audio_jitter_buffer_fast_accelerate ==
762 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100763 audio_jitter_buffer_min_delay_ms ==
764 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800765 ice_connection_receiving_timeout ==
766 o.ice_connection_receiving_timeout &&
767 ice_backup_candidate_pair_ping_interval ==
768 o.ice_backup_candidate_pair_ping_interval &&
769 continual_gathering_policy == o.continual_gathering_policy &&
770 certificates == o.certificates &&
771 prioritize_most_likely_ice_candidate_pairs ==
772 o.prioritize_most_likely_ice_candidate_pairs &&
773 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800774 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700775 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100776 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800777 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800778 screencast_min_bitrate == o.screencast_min_bitrate &&
779 combined_audio_video_bwe == o.combined_audio_video_bwe &&
780 enable_dtls_srtp == o.enable_dtls_srtp &&
781 ice_candidate_pool_size == o.ice_candidate_pool_size &&
782 prune_turn_ports == o.prune_turn_ports &&
783 presume_writable_when_fully_relayed ==
784 o.presume_writable_when_fully_relayed &&
785 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800786 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800787 ice_check_interval_strong_connectivity ==
788 o.ice_check_interval_strong_connectivity &&
789 ice_check_interval_weak_connectivity ==
790 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700791 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700792 ice_unwritable_timeout == o.ice_unwritable_timeout &&
793 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800794 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800795 stun_candidate_keepalive_interval ==
796 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200797 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800798 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800799 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700800 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700801 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700802 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700803 use_media_transport_for_data_channels ==
804 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100805 crypto_options == o.crypto_options &&
806 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800807}
808
809bool PeerConnectionInterface::RTCConfiguration::operator!=(
810 const PeerConnectionInterface::RTCConfiguration& o) const {
811 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800812}
813
zhihuang8f65cdf2016-05-06 18:40:30 -0700814// Generate a RTCP CNAME when a PeerConnection is created.
815std::string GenerateRtcpCname() {
816 std::string cname;
817 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100818 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800819 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700820 }
821 return cname;
822}
823
zhihuang1c378ed2017-08-17 14:10:50 -0700824bool ValidateOfferAnswerOptions(
825 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
826 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
827 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700828}
829
zhihuang1c378ed2017-08-17 14:10:50 -0700830// From |rtc_options|, fill parts of |session_options| shared by all generated
831// m= sections (in other words, nothing that involves a map/array).
832void ExtractSharedMediaSessionOptions(
833 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
834 cricket::MediaSessionOptions* session_options) {
835 session_options->vad_enabled = rtc_options.voice_activity_detection;
836 session_options->bundle_enabled = rtc_options.use_rtp_mux;
837}
zhihuanga77e6bb2017-08-14 18:17:48 -0700838
zhihuang38ede132017-06-15 12:52:32 -0700839PeerConnection::PeerConnection(PeerConnectionFactory* factory,
840 std::unique_ptr<RtcEventLog> event_log,
841 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700843 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700844 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700845 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700846 remote_streams_(StreamCollection::Create()),
847 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848
849PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100850 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800851 RTC_DCHECK_RUN_ON(signaling_thread());
852
Steve Anton8af21862017-12-15 11:20:13 -0800853 // Need to stop transceivers before destroying the stats collector because
854 // AudioRtpSender has a reference to the StatsCollector it will update when
855 // stopping.
856 for (auto transceiver : transceivers_) {
857 transceiver->Stop();
858 }
Steve Anton4171afb2017-11-20 10:20:22 -0800859
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700860 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800861 if (stats_collector_) {
862 stats_collector_->WaitForPendingRequest();
863 stats_collector_ = nullptr;
864 }
Steve Anton75737c02017-11-06 10:37:17 -0800865
Steve Anton8af21862017-12-15 11:20:13 -0800866 // Don't destroy BaseChannels until after stats has been cleaned up so that
867 // the last stats request can still read from the channels.
868 DestroyAllChannels();
869
Mirko Bonadei675513b2017-11-09 11:09:25 +0100870 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800871
872 webrtc_session_desc_factory_.reset();
873 sctp_invoker_.reset();
874 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800875 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800876 transport_controller_.reset();
877
deadbeef91dd5672016-05-18 16:55:30 -0700878 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700879 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700880 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700881 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700882 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700883 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800884 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700885 event_log_.reset();
886 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887}
888
Steve Anton8af21862017-12-15 11:20:13 -0800889void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800890 // Destroy video channels first since they may have a pointer to a voice
891 // channel.
892 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800893 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800894 DestroyTransceiverChannel(transceiver);
895 }
896 }
897 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800898 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800899 DestroyTransceiverChannel(transceiver);
900 }
901 }
902 DestroyDataChannel();
903}
904
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000906 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700907 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100908 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700909
910 RTCError config_error = ValidateConfiguration(configuration);
911 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700913 return false;
914 }
915
Benjamin Wrightcab58882018-05-02 15:12:47 -0700916 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100917 RTC_LOG(LS_ERROR)
918 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100919 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800920 return false;
921 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200922
Benjamin Wrightcab58882018-05-02 15:12:47 -0700923 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800924 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100925 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100926 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800927 return false;
928 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700929
Benjamin Wrightcab58882018-05-02 15:12:47 -0700930 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700931 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700932 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700933 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800934
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200935 cricket::ServerAddresses stun_servers;
936 std::vector<cricket::RelayServerConfig> turn_servers;
937
938 RTCErrorType parse_error =
939 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
940 if (parse_error != RTCErrorType::NONE) {
941 return false;
942 }
943
deadbeef91dd5672016-05-18 16:55:30 -0700944 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700945 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700946 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200947 RTC_FROM_HERE,
948 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
949 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 return false;
951 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200952 // If initialization was successful, note if STUN or TURN servers
953 // were supplied.
954 if (!stun_servers.empty()) {
955 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
956 }
957 if (!turn_servers.empty()) {
958 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700961 // Send information about IPv4/IPv6 status.
962 PeerConnectionAddressFamilyCounter address_family;
963 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
964 address_family = kPeerConnection_IPv6;
965 } else {
966 address_family = kPeerConnection_IPv4;
967 }
968 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
969 kPeerConnectionAddressFamilyCounter_Max);
970
Zhi Huange830e682018-03-30 10:48:35 -0700971 const PeerConnectionFactoryInterface::Options& options = factory_->options();
972
Steve Anton75737c02017-11-06 10:37:17 -0800973 // RFC 3264: The numeric value of the session id and version in the
974 // o line MUST be representable with a "64 bit signed integer".
975 // Due to this constraint session id |session_id_| is max limited to
976 // LLONG_MAX.
977 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700978 JsepTransportController::Config config;
979 config.redetermine_role_on_ice_restart =
980 configuration.redetermine_role_on_ice_restart;
981 config.ssl_max_version = factory_->options().ssl_max_version;
982 config.disable_encryption = options.disable_encryption;
983 config.bundle_policy = configuration.bundle_policy;
984 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700985 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
986 // stub.
987 config.crypto_options = configuration.crypto_options.has_value()
988 ? *configuration.crypto_options
989 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700990 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700991 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700992#if defined(ENABLE_EXTERNAL_AUTH)
993 config.enable_external_auth = true;
994#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700995 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700996
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700997 if (configuration.use_media_transport ||
998 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700999 if (!factory_->media_transport_factory()) {
1000 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001001 << "PeerConnecton is initialized with use_media_transport = true or "
1002 << "use_media_transport_for_data_channels = true "
1003 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001004 return false;
1005 }
1006
1007 config.media_transport_factory = factory_->media_transport_factory();
1008 }
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001011 signaling_thread(), network_thread(), port_allocator_.get(),
1012 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001014 this, &PeerConnection::OnTransportControllerConnectionState);
1015 transport_controller_->SignalStandardizedIceConnectionState.connect(
1016 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001017 transport_controller_->SignalConnectionState.connect(
1018 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001021 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001022 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001023 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001024 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1025 transport_controller_->SignalDtlsHandshakeError.connect(
1026 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1027
1028 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001029
deadbeefab9b2d12015-10-14 11:33:11 -07001030 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001031 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032
Steve Antonba818672017-11-06 10:21:57 -08001033 configuration_ = configuration;
1034
Steve Anton75737c02017-11-06 10:37:17 -08001035 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1036 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1037 if (!configuration.certificates.empty()) {
1038 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1039 // just picking the first one. The decision should be made based on the DTLS
1040 // handshake. The DTLS negotiations need to know about all certificates.
1041 certificate = configuration.certificates[0];
1042 }
1043
Steve Antond25da372017-11-06 14:50:29 -08001044 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001045
1046 if (options.disable_encryption) {
1047 dtls_enabled_ = false;
1048 } else {
1049 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001050 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001051 // |configuration| can override the default |dtls_enabled_| value.
1052 if (configuration.enable_dtls_srtp) {
1053 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1054 }
1055 }
1056
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001057 if (configuration.use_media_transport_for_data_channels) {
1058 if (configuration.enable_rtp_data_channel) {
1059 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1060 "use_media_transport_for_data_channels are "
1061 "incompatible and cannot both be set to true";
1062 return false;
1063 }
1064 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1065 } else if (configuration.enable_rtp_data_channel) {
1066 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1067 // set. It takes precendence over the disable_sctp_data_channels
1068 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001069 data_channel_type_ = cricket::DCT_RTP;
1070 } else {
1071 // DTLS has to be enabled to use SCTP.
1072 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1073 data_channel_type_ = cricket::DCT_SCTP;
1074 }
1075 }
1076
1077 video_options_.screencast_min_bitrate_kbps =
1078 configuration.screencast_min_bitrate;
1079 audio_options_.combined_audio_video_bwe =
1080 configuration.combined_audio_video_bwe;
1081
1082 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001083 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001084
1085 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001086 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001087
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001088 audio_options_.audio_jitter_buffer_min_delay_ms =
1089 configuration.audio_jitter_buffer_min_delay_ms;
1090
Steve Anton75737c02017-11-06 10:37:17 -08001091 // Whether the certificate generator/certificate is null or not determines
1092 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1093 // the right instructions by clearing the variables if needed.
1094 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001095 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001096 certificate = nullptr;
1097 } else if (certificate) {
1098 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001099 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001100 }
1101
1102 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1103 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001104 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001105 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1106 this, &PeerConnection::OnCertificateReady);
1107
1108 if (options.disable_encryption) {
1109 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1110 }
1111
1112 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001113 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001114 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115
Steve Anton4171afb2017-11-20 10:20:22 -08001116 // Add default audio/video transceivers for Plan B SDP.
1117 if (!IsUnifiedPlan()) {
1118 transceivers_.push_back(
1119 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1120 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1121 transceivers_.push_back(
1122 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1123 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1124 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001125 int delay_ms =
1126 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001127 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1128 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129 return true;
1130}
1131
Steve Anton038834f2017-07-14 15:59:59 -07001132RTCError PeerConnection::ValidateConfiguration(
1133 const RTCConfiguration& config) const {
1134 if (config.ice_regather_interval_range &&
1135 config.continual_gathering_policy == GATHER_ONCE) {
1136 return RTCError(RTCErrorType::INVALID_PARAMETER,
1137 "ice_regather_interval_range specified but continual "
1138 "gathering policy is GATHER_ONCE");
1139 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001140 auto result =
1141 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1142 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001143}
1144
Yves Gerey665174f2018-06-19 15:03:05 +02001145rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001146 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1147 "Plan SdpSemantics. Please use GetSenders "
1148 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001149 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150}
1151
Yves Gerey665174f2018-06-19 15:03:05 +02001152rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001153 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1154 "Plan SdpSemantics. Please use GetReceivers "
1155 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001156 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001157}
1158
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001159bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001160 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1161 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001162 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 if (IsClosed()) {
1164 return false;
1165 }
deadbeefab9b2d12015-10-14 11:33:11 -07001166 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 return false;
1168 }
deadbeefab9b2d12015-10-14 11:33:11 -07001169
1170 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001171 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1172 observer->SignalAudioTrackAdded.connect(this,
1173 &PeerConnection::OnAudioTrackAdded);
1174 observer->SignalAudioTrackRemoved.connect(
1175 this, &PeerConnection::OnAudioTrackRemoved);
1176 observer->SignalVideoTrackAdded.connect(this,
1177 &PeerConnection::OnVideoTrackAdded);
1178 observer->SignalVideoTrackRemoved.connect(
1179 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001180 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001181
deadbeefab9b2d12015-10-14 11:33:11 -07001182 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001183 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001184 }
1185 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001186 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
1188
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001189 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001190 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return true;
1192}
1193
1194void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001195 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1196 "Plan SdpSemantics. Please use RemoveTrack "
1197 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001198 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001199 if (!IsClosed()) {
1200 for (const auto& track : local_stream->GetAudioTracks()) {
1201 RemoveAudioTrack(track.get(), local_stream);
1202 }
1203 for (const auto& track : local_stream->GetVideoTracks()) {
1204 RemoveVideoTrack(track.get(), local_stream);
1205 }
deadbeefab9b2d12015-10-14 11:33:11 -07001206 }
deadbeefab9b2d12015-10-14 11:33:11 -07001207 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001208 stream_observers_.erase(
1209 std::remove_if(
1210 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001211 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001212 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001213 }),
1214 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216 if (IsClosed()) {
1217 return;
1218 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001219 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220}
1221
Steve Anton2d6c76a2018-01-05 17:10:52 -08001222RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001223 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001224 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001225 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001226 if (!track) {
1227 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1228 }
1229 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1230 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1232 "Track has invalid kind: " + track->kind());
1233 }
Steve Antonf9381f02017-12-14 10:23:57 -08001234 if (IsClosed()) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1236 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001237 }
Steve Anton4171afb2017-11-20 10:20:22 -08001238 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001239 LOG_AND_RETURN_ERROR(
1240 RTCErrorType::INVALID_PARAMETER,
1241 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001242 }
Steve Antonf9381f02017-12-14 10:23:57 -08001243 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001244 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1245 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001246 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001247 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001248 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001249 }
1250 return sender_or_error;
1251}
deadbeefe1f9d832016-01-14 15:35:42 -08001252
Steve Antonf9381f02017-12-14 10:23:57 -08001253RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1254PeerConnection::AddTrackPlanB(
1255 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001256 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001257 if (stream_ids.size() > 1u) {
1258 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1259 "AddTrack with more than one stream is not "
1260 "supported with Plan B semantics.");
1261 }
1262 std::vector<std::string> adjusted_stream_ids = stream_ids;
1263 if (adjusted_stream_ids.empty()) {
1264 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1265 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001266 cricket::MediaType media_type =
1267 (track->kind() == MediaStreamTrackInterface::kAudioKind
1268 ? cricket::MEDIA_TYPE_AUDIO
1269 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001270 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001271 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001272 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001273 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001274 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001275 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001276 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001277 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001278 if (sender_info) {
1279 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001280 }
Steve Antonf9381f02017-12-14 10:23:57 -08001281 } else {
1282 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001283 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001284 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001285 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001286 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001287 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001288 if (sender_info) {
1289 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001290 }
deadbeefe1f9d832016-01-14 15:35:42 -08001291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001293}
deadbeefe1f9d832016-01-14 15:35:42 -08001294
Steve Antonf9381f02017-12-14 10:23:57 -08001295RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1296PeerConnection::AddTrackUnifiedPlan(
1297 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001298 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001299 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1300 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001301 RTC_LOG(LS_INFO) << "Reusing an existing "
1302 << cricket::MediaTypeToString(transceiver->media_type())
1303 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001304 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001308 transceiver->internal()->set_direction(
1309 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001311 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001312 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 } else {
1314 cricket::MediaType media_type =
1315 (track->kind() == MediaStreamTrackInterface::kAudioKind
1316 ? cricket::MEDIA_TYPE_AUDIO
1317 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001318 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1319 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001320 std::string sender_id = track->id();
1321 // Avoid creating a sender with an existing ID by generating a random ID.
1322 // This can happen if this is the second time AddTrack has created a sender
1323 // for this track.
1324 if (FindSenderById(sender_id)) {
1325 sender_id = rtc::CreateRandomUuid();
1326 }
Florent Castelli892acf02018-10-01 22:47:20 +02001327 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001328 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1329 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001330 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001331 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001332 }
Steve Antonf9381f02017-12-14 10:23:57 -08001333 return transceiver->sender();
1334}
1335
1336rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1337PeerConnection::FindFirstTransceiverForAddedTrack(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1339 RTC_DCHECK(track);
1340 for (auto transceiver : transceivers_) {
1341 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001342 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001343 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001344 !transceiver->internal()->has_ever_been_used_to_send() &&
1345 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001346 return transceiver;
1347 }
1348 }
1349 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001350}
1351
1352bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1353 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001354 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001355}
1356
Steve Anton24db5732018-07-23 10:27:33 -07001357RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001358 rtc::scoped_refptr<RtpSenderInterface> sender) {
1359 if (!sender) {
1360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1361 }
deadbeefe1f9d832016-01-14 15:35:42 -08001362 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1364 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001365 }
Steve Antonf9381f02017-12-14 10:23:57 -08001366 if (IsUnifiedPlan()) {
1367 auto transceiver = FindTransceiverBySender(sender);
1368 if (!transceiver || !sender->track()) {
1369 return RTCError::OK();
1370 }
1371 sender->SetTrack(nullptr);
1372 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 }
Steve Anton4171afb2017-11-20 10:20:22 -08001379 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001380 bool removed;
1381 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1382 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1383 } else {
1384 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1385 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1386 }
1387 if (!removed) {
1388 LOG_AND_RETURN_ERROR(
1389 RTCErrorType::INVALID_PARAMETER,
1390 "Couldn't find sender " + sender->id() + " to remove.");
1391 }
Steve Anton4171afb2017-11-20 10:20:22 -08001392 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001393 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001394 return RTCError::OK();
1395}
1396
1397rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1398PeerConnection::FindTransceiverBySender(
1399 rtc::scoped_refptr<RtpSenderInterface> sender) {
1400 for (auto transceiver : transceivers_) {
1401 if (transceiver->sender() == sender) {
1402 return transceiver;
1403 }
1404 }
1405 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001406}
1407
Steve Anton9158ef62017-11-27 13:01:52 -08001408RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1409PeerConnection::AddTransceiver(
1410 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1411 return AddTransceiver(track, RtpTransceiverInit());
1412}
1413
1414RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1415PeerConnection::AddTransceiver(
1416 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1417 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001418 RTC_CHECK(IsUnifiedPlan())
1419 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001420 if (!track) {
1421 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1422 }
1423 cricket::MediaType media_type;
1424 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1425 media_type = cricket::MEDIA_TYPE_AUDIO;
1426 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1427 media_type = cricket::MEDIA_TYPE_VIDEO;
1428 } else {
1429 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1430 "Track kind is not audio or video");
1431 }
1432 return AddTransceiver(media_type, track, init);
1433}
1434
1435RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1436PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1437 return AddTransceiver(media_type, RtpTransceiverInit());
1438}
1439
1440RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1441PeerConnection::AddTransceiver(cricket::MediaType media_type,
1442 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001443 RTC_CHECK(IsUnifiedPlan())
1444 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001445 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1446 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1447 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1448 "media type is not audio or video");
1449 }
1450 return AddTransceiver(media_type, nullptr, init);
1451}
1452
1453RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1454PeerConnection::AddTransceiver(
1455 cricket::MediaType media_type,
1456 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001457 const RtpTransceiverInit& init,
1458 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001459 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1460 media_type == cricket::MEDIA_TYPE_VIDEO));
1461 if (track) {
1462 RTC_DCHECK_EQ(media_type,
1463 (track->kind() == MediaStreamTrackInterface::kAudioKind
1464 ? cricket::MEDIA_TYPE_AUDIO
1465 : cricket::MEDIA_TYPE_VIDEO));
1466 }
1467
1468 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001469 if (init.send_encodings.size() > 1) {
1470 LOG_AND_RETURN_ERROR(
1471 RTCErrorType::UNSUPPORTED_PARAMETER,
1472 "Attempted to create an encoder with more than 1 encoding parameter.");
1473 }
1474
1475 for (const auto& encoding : init.send_encodings) {
1476 if (encoding.ssrc.has_value()) {
1477 LOG_AND_RETURN_ERROR(
1478 RTCErrorType::UNSUPPORTED_PARAMETER,
1479 "Attempted to set an unimplemented parameter of RtpParameters.");
1480 }
1481 }
1482
1483 RtpParameters parameters;
1484 parameters.encodings = init.send_encodings;
1485 if (UnimplementedRtpParameterHasValue(parameters)) {
1486 LOG_AND_RETURN_ERROR(
1487 RTCErrorType::UNSUPPORTED_PARAMETER,
1488 "Attempted to set an unimplemented parameter of RtpParameters.");
1489 }
Steve Anton9158ef62017-11-27 13:01:52 -08001490
Steve Anton3d954a62018-04-02 11:27:23 -07001491 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1492 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001493 // Set the sender ID equal to the track ID if the track is specified unless
1494 // that sender ID is already in use.
1495 std::string sender_id =
1496 (track && !FindSenderById(track->id()) ? track->id()
1497 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001498 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1499 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1501 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1502 transceiver->internal()->set_direction(init.direction);
1503
Steve Anton22da89f2018-01-25 13:58:07 -08001504 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001505 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001506 }
Steve Antonf9381f02017-12-14 10:23:57 -08001507
1508 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1509}
1510
Steve Anton02ee47c2018-01-10 16:26:06 -08001511rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1512PeerConnection::CreateSender(
1513 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001514 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001516 const std::vector<std::string>& stream_ids,
1517 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001518 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1520 RTC_DCHECK(!track ||
1521 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1522 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1523 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001524 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001525 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001526 } else {
1527 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1528 RTC_DCHECK(!track ||
1529 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1530 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001531 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001532 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001534 bool set_track_succeeded = sender->SetTrack(track);
1535 RTC_DCHECK(set_track_succeeded);
1536 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001537 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 return sender;
1539}
1540
1541rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1542PeerConnection::CreateReceiver(cricket::MediaType media_type,
1543 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001544 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1545 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001546 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001547 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001548 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1549 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001550 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001551 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001553 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001554 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1555 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001556 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001557 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 return receiver;
1559}
1560
1561rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1562PeerConnection::CreateAndAddTransceiver(
1563 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1564 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1565 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001566 // Ensure that the new sender does not have an ID that is already in use by
1567 // another sender.
1568 // Allow receiver IDs to conflict since those come from remote SDP (which
1569 // could be invalid, but should not cause a crash).
1570 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001571 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1572 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001573 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001574 transceiver->internal()->SignalNegotiationNeeded.connect(
1575 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001576 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001577}
1578
Steve Anton52d86772018-02-20 15:48:12 -08001579void PeerConnection::OnNegotiationNeeded() {
1580 RTC_DCHECK_RUN_ON(signaling_thread());
1581 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001582 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001583}
1584
deadbeeffac06552015-11-25 11:26:01 -08001585rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001586 const std::string& kind,
1587 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001588 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1589 "Plan SdpSemantics. Please use AddTransceiver "
1590 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001591 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001592 if (IsClosed()) {
1593 return nullptr;
1594 }
Steve Anton4171afb2017-11-20 10:20:22 -08001595
Seth Hampson5b4f0752018-04-02 16:31:36 -07001596 // Internally we need to have one stream with Plan B semantics, so we
1597 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001598 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001599 if (stream_id.empty()) {
1600 stream_ids.push_back(rtc::CreateRandomUuid());
1601 RTC_LOG(LS_INFO)
1602 << "No stream_id specified for sender. Generated stream ID: "
1603 << stream_ids[0];
1604 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001605 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001606 }
1607
Steve Anton4171afb2017-11-20 10:20:22 -08001608 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001609 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001610 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001611 auto* audio_sender = new AudioRtpSender(
1612 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001613 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001614 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001615 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001616 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001617 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001618 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001619 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001620 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001621 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001622 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001623 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001624 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001625 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001626 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001627 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001628 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001629
deadbeefe1f9d832016-01-14 15:35:42 -08001630 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001631}
1632
deadbeef70ab1a12015-09-28 16:53:55 -07001633std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1634 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001635 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001636 for (auto sender : GetSendersInternal()) {
1637 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001638 }
1639 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001640}
1641
Steve Anton4171afb2017-11-20 10:20:22 -08001642std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1643PeerConnection::GetSendersInternal() const {
1644 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1645 all_senders;
1646 for (auto transceiver : transceivers_) {
1647 auto senders = transceiver->internal()->senders();
1648 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1649 }
1650 return all_senders;
1651}
1652
deadbeef70ab1a12015-09-28 16:53:55 -07001653std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1654PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001655 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001656 for (const auto& receiver : GetReceiversInternal()) {
1657 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001658 }
1659 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001660}
1661
Steve Anton4171afb2017-11-20 10:20:22 -08001662std::vector<
1663 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1664PeerConnection::GetReceiversInternal() const {
1665 std::vector<
1666 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1667 all_receivers;
1668 for (auto transceiver : transceivers_) {
1669 auto receivers = transceiver->internal()->receivers();
1670 all_receivers.insert(all_receivers.end(), receivers.begin(),
1671 receivers.end());
1672 }
1673 return all_receivers;
1674}
1675
Steve Anton9158ef62017-11-27 13:01:52 -08001676std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1677PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001678 RTC_CHECK(IsUnifiedPlan())
1679 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001680 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1681 for (auto transceiver : transceivers_) {
1682 all_transceivers.push_back(transceiver);
1683 }
1684 return all_transceivers;
1685}
1686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001688 MediaStreamTrackInterface* track,
1689 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001690 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001691 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001692 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001693 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 return false;
1695 }
1696
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001697 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001698 // The StatsCollector is used to tell if a track is valid because it may
1699 // remember tracks that the PeerConnection previously removed.
1700 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001701 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1702 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001703 return false;
1704 }
Steve Antonad182762018-09-05 20:22:40 +00001705 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1706 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 return true;
1708}
1709
hbos74e1a4f2016-09-15 23:33:01 -07001710void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001711 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001712 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001713 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001714 stats_collector_->GetStatsReport(callback);
1715}
1716
Henrik Boström1df1bf82018-03-20 13:24:20 +01001717void PeerConnection::GetStats(
1718 rtc::scoped_refptr<RtpSenderInterface> selector,
1719 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1720 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1721 RTC_DCHECK(callback);
1722 RTC_DCHECK(stats_collector_);
1723 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1724 if (selector) {
1725 for (const auto& proxy_transceiver : transceivers_) {
1726 for (const auto& proxy_sender :
1727 proxy_transceiver->internal()->senders()) {
1728 if (proxy_sender == selector) {
1729 internal_sender = proxy_sender->internal();
1730 break;
1731 }
1732 }
1733 if (internal_sender)
1734 break;
1735 }
1736 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001737 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001738 // belong to the PeerConnection (in Plan B, senders can be removed from the
1739 // PeerConnection). This means that "all the stats objects representing the
1740 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1741 // produces an empty stats report.
1742 stats_collector_->GetStatsReport(internal_sender, callback);
1743}
1744
1745void PeerConnection::GetStats(
1746 rtc::scoped_refptr<RtpReceiverInterface> selector,
1747 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1748 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1749 RTC_DCHECK(callback);
1750 RTC_DCHECK(stats_collector_);
1751 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1752 if (selector) {
1753 for (const auto& proxy_transceiver : transceivers_) {
1754 for (const auto& proxy_receiver :
1755 proxy_transceiver->internal()->receivers()) {
1756 if (proxy_receiver == selector) {
1757 internal_receiver = proxy_receiver->internal();
1758 break;
1759 }
1760 }
1761 if (internal_receiver)
1762 break;
1763 }
1764 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001765 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001766 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1767 // the PeerConnection). This means that "all the stats objects representing
1768 // the selector" is an empty set. Invoking GetStatsReport() with a null
1769 // selector produces an empty stats report.
1770 stats_collector_->GetStatsReport(internal_receiver, callback);
1771}
1772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1774 return signaling_state_;
1775}
1776
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777PeerConnectionInterface::IceConnectionState
1778PeerConnection::ice_connection_state() {
1779 return ice_connection_state_;
1780}
1781
Alex Loiko9289eda2018-11-23 16:18:59 +00001782PeerConnectionInterface::IceConnectionState
1783PeerConnection::standardized_ice_connection_state() {
1784 return standardized_ice_connection_state_;
1785}
1786
Jonas Olsson635474e2018-10-18 15:58:17 +02001787PeerConnectionInterface::PeerConnectionState
1788PeerConnection::peer_connection_state() {
1789 return connection_state_;
1790}
1791
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792PeerConnectionInterface::IceGatheringState
1793PeerConnection::ice_gathering_state() {
1794 return ice_gathering_state_;
1795}
1796
Yves Gerey665174f2018-06-19 15:03:05 +02001797rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798 const std::string& label,
1799 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001800 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001801
deadbeefab9b2d12015-10-14 11:33:11 -07001802 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001803
kwibergd1fe2812016-04-27 06:47:29 -07001804 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001805 if (config) {
1806 internal_config.reset(new InternalDataChannelInit(*config));
1807 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001808 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001809 InternalCreateDataChannel(label, internal_config.get()));
1810 if (!channel.get()) {
1811 return nullptr;
1812 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001814 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1815 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001816 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001817 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001818 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001819 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return DataChannelProxy::Create(signaling_thread(), channel.get());
1821}
1822
1823void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001824 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001825 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001826
nisse7ce109a2017-01-31 00:57:56 -08001827 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001828 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001829 return;
1830 }
deadbeefab9b2d12015-10-14 11:33:11 -07001831
Steve Anton8d3444d2017-10-20 15:30:51 -07001832 if (IsClosed()) {
1833 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001834 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001835 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001836 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001837 return;
1838 }
1839
zhihuang1c378ed2017-08-17 14:10:50 -07001840 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001841 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001842 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001843 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001844 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001845 return;
1846 }
1847
Steve Anton22da89f2018-01-25 13:58:07 -08001848 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1849 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1850 if (IsUnifiedPlan()) {
1851 RTCError error = HandleLegacyOfferOptions(options);
1852 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001853 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001854 return;
1855 }
1856 }
1857
zhihuang1c378ed2017-08-17 14:10:50 -07001858 cricket::MediaSessionOptions session_options;
1859 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001860 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861}
1862
Steve Anton22da89f2018-01-25 13:58:07 -08001863RTCError PeerConnection::HandleLegacyOfferOptions(
1864 const RTCOfferAnswerOptions& options) {
1865 RTC_DCHECK(IsUnifiedPlan());
1866
1867 if (options.offer_to_receive_audio == 0) {
1868 RemoveRecvDirectionFromReceivingTransceiversOfType(
1869 cricket::MEDIA_TYPE_AUDIO);
1870 } else if (options.offer_to_receive_audio == 1) {
1871 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1872 } else if (options.offer_to_receive_audio > 1) {
1873 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1874 "offer_to_receive_audio > 1 is not supported.");
1875 }
1876
1877 if (options.offer_to_receive_video == 0) {
1878 RemoveRecvDirectionFromReceivingTransceiversOfType(
1879 cricket::MEDIA_TYPE_VIDEO);
1880 } else if (options.offer_to_receive_video == 1) {
1881 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1882 } else if (options.offer_to_receive_video > 1) {
1883 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1884 "offer_to_receive_video > 1 is not supported.");
1885 }
1886
1887 return RTCError::OK();
1888}
1889
1890void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1891 cricket::MediaType media_type) {
1892 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001893 RtpTransceiverDirection new_direction =
1894 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1895 if (new_direction != transceiver->direction()) {
1896 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1897 << " transceiver (MID="
1898 << transceiver->mid().value_or("<not set>") << ") from "
1899 << RtpTransceiverDirectionToString(
1900 transceiver->direction())
1901 << " to "
1902 << RtpTransceiverDirectionToString(new_direction)
1903 << " since CreateOffer specified offer_to_receive=0";
1904 transceiver->internal()->set_direction(new_direction);
1905 }
Steve Anton22da89f2018-01-25 13:58:07 -08001906 }
1907}
1908
1909void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1910 cricket::MediaType media_type) {
1911 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001912 RTC_LOG(LS_INFO)
1913 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1914 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001915 RtpTransceiverInit init;
1916 init.direction = RtpTransceiverDirection::kRecvOnly;
1917 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1918 }
1919}
1920
1921std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1922PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1923 std::vector<
1924 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1925 receiving_transceivers;
1926 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001927 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001928 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1929 receiving_transceivers.push_back(transceiver);
1930 }
1931 }
1932 return receiving_transceivers;
1933}
1934
htaa2a49d92016-03-04 02:51:39 -08001935void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1936 const RTCOfferAnswerOptions& options) {
1937 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001938 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001939 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001940 return;
1941 }
1942
Steve Antondffead82018-02-06 10:31:29 -08001943 if (!(signaling_state_ == kHaveRemoteOffer ||
1944 signaling_state_ == kHaveLocalPrAnswer)) {
1945 std::string error =
1946 "PeerConnection cannot create an answer in a state other than "
1947 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001948 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001949 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001950 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001951 return;
1952 }
1953
Steve Antondffead82018-02-06 10:31:29 -08001954 // The remote description should be set if we're in the right state.
1955 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
Steve Anton22da89f2018-01-25 13:58:07 -08001957 if (IsUnifiedPlan()) {
1958 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1959 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1960 "supported with Unified Plan semantics. Use the "
1961 "RtpTransceiver API instead.";
1962 }
1963 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1964 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1965 "supported with Unified Plan semantics. Use the "
1966 "RtpTransceiver API instead.";
1967 }
1968 }
1969
htaa2a49d92016-03-04 02:51:39 -08001970 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001971 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001972
Steve Antond25da372017-11-06 14:50:29 -08001973 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974}
1975
1976void PeerConnection::SetLocalDescription(
1977 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001978 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001979 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001980
Steve Anton80dd7b52018-02-16 17:08:42 -08001981 // The SetLocalDescription contract is that we take ownership of the session
1982 // description regardless of the outcome, so wrap it in a unique_ptr right
1983 // away. Ideally, SetLocalDescription's signature will be changed to take the
1984 // description as a unique_ptr argument to formalize this agreement.
1985 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1986
nisse7ce109a2017-01-31 00:57:56 -08001987 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001988 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989 return;
1990 }
Steve Anton8a006912017-12-04 15:25:56 -08001991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001993 PostSetSessionDescriptionFailure(
1994 observer,
1995 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 return;
1997 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001998
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 // If a session error has occurred the PeerConnection is in a possibly
2000 // inconsistent state so fail right away.
2001 if (session_error() != SessionError::kNone) {
2002 std::string error_message = GetSessionErrorMsg();
2003 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002004 PostSetSessionDescriptionFailure(
2005 observer,
2006 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002007 return;
2008 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002009
Steve Anton80dd7b52018-02-16 17:08:42 -08002010 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2011 if (!error.ok()) {
2012 std::string error_message = GetSetDescriptionErrorMessage(
2013 cricket::CS_LOCAL, desc->GetType(), error);
2014 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002015 PostSetSessionDescriptionFailure(
2016 observer,
2017 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002018 return;
2019 }
2020
2021 // Grab the description type before moving ownership to ApplyLocalDescription,
2022 // which may destroy it before returning.
2023 const SdpType type = desc->GetType();
2024
2025 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002026 // |desc| may be destroyed at this point.
2027
2028 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002029 // If ApplyLocalDescription fails, the PeerConnection could be in an
2030 // inconsistent state, so act conservatively here and set the session error
2031 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2032 SetSessionError(SessionError::kContent, error.message());
2033 std::string error_message =
2034 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2035 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002036 PostSetSessionDescriptionFailure(
2037 observer,
2038 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002039 return;
2040 }
Steve Anton8a006912017-12-04 15:25:56 -08002041 RTC_DCHECK(local_description());
2042
2043 PostSetSessionDescriptionSuccess(observer);
2044
Steve Antonad182762018-09-05 20:22:40 +00002045 // MaybeStartGathering needs to be called after posting
2046 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2047 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002048 transport_controller_->MaybeStartGathering();
2049
Steve Antona3a92c22017-12-07 10:27:41 -08002050 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002051 // TODO(deadbeef): We already had to hop to the network thread for
2052 // MaybeStartGathering...
2053 network_thread()->Invoke<void>(
2054 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2055 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002056 // Make UMA notes about what was agreed to.
2057 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002058 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002059 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002060}
2061
2062RTCError PeerConnection::ApplyLocalDescription(
2063 std::unique_ptr<SessionDescriptionInterface> desc) {
2064 RTC_DCHECK_RUN_ON(signaling_thread());
2065 RTC_DCHECK(desc);
2066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 // Update stats here so that we have the most recent stats for tracks and
2068 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002069 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002070
Steve Antondcc3c022017-12-22 16:02:54 -08002071 // Take a reference to the old local description since it's used below to
2072 // compare against the new local description. When setting the new local
2073 // description, grab ownership of the replaced session description in case it
2074 // is the same as |old_local_description|, to keep it alive for the duration
2075 // of the method.
2076 const SessionDescriptionInterface* old_local_description =
2077 local_description();
2078 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002079 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002080 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002081 replaced_local_description = pending_local_description_
2082 ? std::move(pending_local_description_)
2083 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002084 current_local_description_ = std::move(desc);
2085 pending_local_description_ = nullptr;
2086 current_remote_description_ = std::move(pending_remote_description_);
2087 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002088 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002089 pending_local_description_ = std::move(desc);
2090 }
2091 // The session description to apply now must be accessed by
2092 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002093 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002094
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002095 if (!is_caller_) {
2096 if (remote_description()) {
2097 // Remote description was applied first, so this PC is the callee.
2098 is_caller_ = false;
2099 } else {
2100 // Local description is applied first, so this PC is the caller.
2101 is_caller_ = true;
2102 }
2103 }
2104
Zhi Huange830e682018-03-30 10:48:35 -07002105 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2106 if (!error.ok()) {
2107 return error;
2108 }
2109
Steve Antondcc3c022017-12-22 16:02:54 -08002110 if (IsUnifiedPlan()) {
2111 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002112 cricket::CS_LOCAL, *local_description(), old_local_description,
2113 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002114 if (!error.ok()) {
2115 return error;
2116 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002117 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2118 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002119 for (auto transceiver : transceivers_) {
2120 const ContentInfo* content =
2121 FindMediaSectionForTransceiver(transceiver, local_description());
2122 if (!content) {
2123 continue;
2124 }
2125 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2127 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002128 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002129 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2130 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2131 // "recvonly", process the removal of a remote track for the media
2132 // description, given transceiver, removeList, and muteTracks.
2133 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2134 (transceiver->internal()->fired_direction() &&
2135 RtpTransceiverDirectionHasRecv(
2136 *transceiver->internal()->fired_direction()))) {
2137 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2138 &removed_streams);
2139 }
2140 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2141 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002142 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002143 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002144 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002145 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002146 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002147 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002148 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002149 }
2150 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002151 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002152 }
2153 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002154 // Media channels will be created only when offer is set. These may use new
2155 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002156 if (type == SdpType::kOffer) {
2157 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2158 // description is applied. Restore back to old description.
2159 RTCError error = CreateChannels(*local_description()->description());
2160 if (!error.ok()) {
2161 return error;
2162 }
2163 }
Steve Antondcc3c022017-12-22 16:02:54 -08002164 // Remove unused channels if MediaContentDescription is rejected.
2165 RemoveUnusedChannels(local_description()->description());
2166 }
Steve Anton8a006912017-12-04 15:25:56 -08002167
Zhi Huange830e682018-03-30 10:48:35 -07002168 error = UpdateSessionState(type, cricket::CS_LOCAL,
2169 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002170 if (!error.ok()) {
2171 return error;
2172 }
Steve Antondcc3c022017-12-22 16:02:54 -08002173
Steve Anton8a006912017-12-04 15:25:56 -08002174 if (remote_description()) {
2175 // Now that we have a local description, we can push down remote candidates.
2176 UseCandidatesInSessionDescription(remote_description());
2177 }
2178
2179 pending_ice_restarts_.clear();
2180 if (session_error() != SessionError::kNone) {
2181 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2182 }
2183
deadbeefab9b2d12015-10-14 11:33:11 -07002184 // If setting the description decided our SSL role, allocate any necessary
2185 // SCTP sids.
2186 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002187 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002188 AllocateSctpSids(role);
2189 }
2190
Steve Antond3679212018-01-17 17:41:02 -08002191 if (IsUnifiedPlan()) {
2192 for (auto transceiver : transceivers_) {
2193 const ContentInfo* content =
2194 FindMediaSectionForTransceiver(transceiver, local_description());
2195 if (!content) {
2196 continue;
2197 }
Steve Anton74255ff2018-01-24 18:32:57 -08002198 const auto& streams = content->media_description()->streams();
2199 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002200 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002201 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002202 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002203 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002204 } else {
2205 // 0 is a special value meaning "this sender has no associated send
2206 // stream". Need to call this so the sender won't attempt to configure
2207 // a no longer existing stream and run into DCHECKs in the lower
2208 // layers.
2209 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002210 }
2211 }
2212 } else {
2213 // Plan B semantics.
2214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Update state and SSRC of local MediaStreams and DataChannels based on the
2216 // local session description.
2217 const cricket::ContentInfo* audio_content =
2218 GetFirstAudioContent(local_description()->description());
2219 if (audio_content) {
2220 if (audio_content->rejected) {
2221 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2222 } else {
2223 const cricket::AudioContentDescription* audio_desc =
2224 audio_content->media_description()->as_audio();
2225 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2226 }
deadbeeffaac4972015-11-12 15:33:07 -08002227 }
deadbeefab9b2d12015-10-14 11:33:11 -07002228
Steve Antondcc3c022017-12-22 16:02:54 -08002229 const cricket::ContentInfo* video_content =
2230 GetFirstVideoContent(local_description()->description());
2231 if (video_content) {
2232 if (video_content->rejected) {
2233 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2234 } else {
2235 const cricket::VideoContentDescription* video_desc =
2236 video_content->media_description()->as_video();
2237 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2238 }
deadbeeffaac4972015-11-12 15:33:07 -08002239 }
deadbeefab9b2d12015-10-14 11:33:11 -07002240 }
2241
2242 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002243 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002244 if (data_content) {
2245 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002246 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002247 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002248 cricket::kMediaProtocolRtpPrefix)) {
2249 UpdateLocalRtpDataChannels(data_desc->streams());
2250 }
2251 }
2252
Steve Anton8a006912017-12-04 15:25:56 -08002253 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254}
2255
Steve Anton06817cd2018-12-18 15:55:30 -08002256// The SDP parser used to populate these values by default for the 'content
2257// name' if an a=mid line was absent.
2258static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2259 switch (media_type) {
2260 case cricket::MEDIA_TYPE_AUDIO:
2261 return cricket::CN_AUDIO;
2262 case cricket::MEDIA_TYPE_VIDEO:
2263 return cricket::CN_VIDEO;
2264 case cricket::MEDIA_TYPE_DATA:
2265 return cricket::CN_DATA;
2266 }
2267 RTC_NOTREACHED();
2268 return "";
2269}
2270
2271void PeerConnection::FillInMissingRemoteMids(
2272 cricket::SessionDescription* remote_description) {
2273 RTC_DCHECK(remote_description);
2274 const cricket::ContentInfos& local_contents =
2275 (local_description() ? local_description()->description()->contents()
2276 : cricket::ContentInfos());
2277 std::set<std::string> used_mids = seen_mids_;
2278 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2279 cricket::ContentInfo& content = remote_description->contents()[i];
2280 if (!content.name.empty()) {
2281 continue;
2282 }
2283 absl::string_view new_mid;
2284 absl::string_view source_explanation;
2285 if (IsUnifiedPlan()) {
2286 if (i < local_contents.size()) {
2287 new_mid = local_contents[i].name;
2288 source_explanation = "from the matching local media section";
2289 } else {
2290 new_mid = AllocateMid(&used_mids);
2291 source_explanation = "generated just now";
2292 }
2293 } else {
2294 new_mid = GetDefaultMidForPlanB(content.media_description()->type());
2295 source_explanation = "to match pre-existing behavior";
2296 }
2297 content.name = std::string(new_mid);
2298 remote_description->transport_infos()[i].content_name =
2299 std::string(new_mid);
2300 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2301 << " is missing an a=mid line. Filling in the value '"
2302 << new_mid << "' " << source_explanation << ".";
2303 }
2304}
2305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002307 SetSessionDescriptionObserver* observer,
2308 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002309 SetRemoteDescription(
2310 std::unique_ptr<SessionDescriptionInterface>(desc),
2311 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2312 new SetRemoteDescriptionObserverAdapter(this, observer)));
2313}
2314
2315void PeerConnection::SetRemoteDescription(
2316 std::unique_ptr<SessionDescriptionInterface> desc,
2317 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002318 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002319
nisse7ce109a2017-01-31 00:57:56 -08002320 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002321 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 return;
2323 }
Steve Anton8a006912017-12-04 15:25:56 -08002324
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002325 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002326 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002327 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 return;
2329 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002330
Steve Anton80dd7b52018-02-16 17:08:42 -08002331 // If a session error has occurred the PeerConnection is in a possibly
2332 // inconsistent state so fail right away.
2333 if (session_error() != SessionError::kNone) {
2334 std::string error_message = GetSessionErrorMsg();
2335 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2336 observer->OnSetRemoteDescriptionComplete(
2337 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2338 return;
2339 }
Steve Anton71439a62018-02-15 11:53:06 -08002340
Steve Antonba42e992018-04-09 14:10:01 -07002341 if (desc->GetType() == SdpType::kOffer) {
2342 // Report to UMA the format of the received offer.
2343 ReportSdpFormatReceived(*desc);
2344 }
2345
Steve Anton06817cd2018-12-18 15:55:30 -08002346 // Handle remote descriptions missing a=mid lines for interop with legacy end
2347 // points.
2348 FillInMissingRemoteMids(desc->description());
2349
Steve Anton80dd7b52018-02-16 17:08:42 -08002350 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002351 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002352 std::string error_message = GetSetDescriptionErrorMessage(
2353 cricket::CS_REMOTE, desc->GetType(), error);
2354 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002355 observer->OnSetRemoteDescriptionComplete(
2356 RTCError(error.type(), std::move(error_message)));
2357 return;
2358 }
Steve Anton71439a62018-02-15 11:53:06 -08002359
Steve Anton80dd7b52018-02-16 17:08:42 -08002360 // Grab the description type before moving ownership to
2361 // ApplyRemoteDescription, which may destroy it before returning.
2362 const SdpType type = desc->GetType();
2363
2364 error = ApplyRemoteDescription(std::move(desc));
2365 // |desc| may be destroyed at this point.
2366
2367 if (!error.ok()) {
2368 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2369 // inconsistent state, so act conservatively here and set the session error
2370 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2371 SetSessionError(SessionError::kContent, error.message());
2372 std::string error_message =
2373 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2374 RTC_LOG(LS_ERROR) << error_message;
2375 observer->OnSetRemoteDescriptionComplete(
2376 RTCError(error.type(), std::move(error_message)));
2377 return;
2378 }
2379 RTC_DCHECK(remote_description());
2380
2381 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002382 // TODO(deadbeef): We already had to hop to the network thread for
2383 // MaybeStartGathering...
2384 network_thread()->Invoke<void>(
2385 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2386 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002387 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002388 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002389 }
2390
2391 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002392 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002393}
2394
2395RTCError PeerConnection::ApplyRemoteDescription(
2396 std::unique_ptr<SessionDescriptionInterface> desc) {
2397 RTC_DCHECK_RUN_ON(signaling_thread());
2398 RTC_DCHECK(desc);
2399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 // Update stats here so that we have the most recent stats for tracks and
2401 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002402 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002403
Steve Antondcc3c022017-12-22 16:02:54 -08002404 // Take a reference to the old remote description since it's used below to
2405 // compare against the new remote description. When setting the new remote
2406 // description, grab ownership of the replaced session description in case it
2407 // is the same as |old_remote_description|, to keep it alive for the duration
2408 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002409 const SessionDescriptionInterface* old_remote_description =
2410 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002411 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002412 SdpType type = desc->GetType();
2413 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002414 replaced_remote_description = pending_remote_description_
2415 ? std::move(pending_remote_description_)
2416 : std::move(current_remote_description_);
2417 current_remote_description_ = std::move(desc);
2418 pending_remote_description_ = nullptr;
2419 current_local_description_ = std::move(pending_local_description_);
2420 } else {
2421 replaced_remote_description = std::move(pending_remote_description_);
2422 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 }
Steve Anton8a006912017-12-04 15:25:56 -08002424 // The session description to apply now must be accessed by
2425 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002426 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427
Zhi Huange830e682018-03-30 10:48:35 -07002428 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2429 if (!error.ok()) {
2430 return error;
2431 }
Steve Anton8a006912017-12-04 15:25:56 -08002432 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002433 if (IsUnifiedPlan()) {
2434 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002435 cricket::CS_REMOTE, *remote_description(), local_description(),
2436 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002437 if (!error.ok()) {
2438 return error;
2439 }
Steve Antondcc3c022017-12-22 16:02:54 -08002440 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002441 // Media channels will be created only when offer is set. These may use new
2442 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002443 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002444 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002445 // description is applied. Restore back to old description.
2446 RTCError error = CreateChannels(*remote_description()->description());
2447 if (!error.ok()) {
2448 return error;
2449 }
2450 }
Steve Antondcc3c022017-12-22 16:02:54 -08002451 // Remove unused channels if MediaContentDescription is rejected.
2452 RemoveUnusedChannels(remote_description()->description());
2453 }
Steve Anton8a006912017-12-04 15:25:56 -08002454
Zhi Huange830e682018-03-30 10:48:35 -07002455 // NOTE: Candidates allocation will be initiated only when
2456 // SetLocalDescription is called.
2457 error = UpdateSessionState(type, cricket::CS_REMOTE,
2458 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002459 if (!error.ok()) {
2460 return error;
2461 }
2462
2463 if (local_description() &&
2464 !UseCandidatesInSessionDescription(remote_description())) {
2465 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2466 }
2467
2468 if (old_remote_description) {
2469 for (const cricket::ContentInfo& content :
2470 old_remote_description->description()->contents()) {
2471 // Check if this new SessionDescription contains new ICE ufrag and
2472 // password that indicates the remote peer requests an ICE restart.
2473 // TODO(deadbeef): When we start storing both the current and pending
2474 // remote description, this should reset pending_ice_restarts and compare
2475 // against the current description.
2476 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2477 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002478 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002479 pending_ice_restarts_.insert(content.name);
2480 }
2481 } else {
2482 // We retain all received candidates only if ICE is not restarted.
2483 // When ICE is restarted, all previous candidates belong to an old
2484 // generation and should not be kept.
2485 // TODO(deadbeef): This goes against the W3C spec which says the remote
2486 // description should only contain candidates from the last set remote
2487 // description plus any candidates added since then. We should remove
2488 // this once we're sure it won't break anything.
2489 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2490 old_remote_description, content.name, mutable_remote_description());
2491 }
2492 }
2493 }
2494
2495 if (session_error() != SessionError::kNone) {
2496 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2497 }
2498
2499 // Set the the ICE connection state to connecting since the connection may
2500 // become writable with peer reflexive candidates before any remote candidate
2501 // is signaled.
2502 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2503 // is to have a new signal the indicates a change in checking state from the
2504 // transport and expose a new checking() member from transport that can be
2505 // read to determine the current checking state. The existing SignalConnecting
2506 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002507 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002508 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002509 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2510 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2511 }
2512
deadbeefab9b2d12015-10-14 11:33:11 -07002513 // If setting the description decided our SSL role, allocate any necessary
2514 // SCTP sids.
2515 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002516 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002517 AllocateSctpSids(role);
2518 }
2519
Steve Antondcc3c022017-12-22 16:02:54 -08002520 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002521 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002522 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002523 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002524 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002526 for (auto transceiver : transceivers_) {
2527 const ContentInfo* content =
2528 FindMediaSectionForTransceiver(transceiver, remote_description());
2529 if (!content) {
2530 continue;
2531 }
2532 const MediaContentDescription* media_desc = content->media_description();
2533 RtpTransceiverDirection local_direction =
2534 RtpTransceiverDirectionReversed(media_desc->direction());
2535 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2536 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2537 // transceiver's current direction is neither sendrecv nor recvonly,
2538 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002539 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002540 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002541 // The remote description has signaled the stream IDs.
2542 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002543 }
Steve Antondcc3c022017-12-22 16:02:54 -08002544 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002545 (!transceiver->fired_direction() ||
2546 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002547 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002548 << content->name << " (added to "
2549 << GetStreamIdsString(stream_ids) << ").";
2550
2551 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2552 for (const std::string& stream_id : stream_ids) {
2553 rtc::scoped_refptr<MediaStreamInterface> stream =
2554 remote_streams_->find(stream_id);
2555 if (!stream) {
2556 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2557 MediaStream::Create(stream_id));
2558 remote_streams_->AddStream(stream);
2559 added_streams.push_back(stream);
2560 }
2561 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002562 }
Henrik Boström5b147782018-12-04 11:25:05 +01002563 // Special case: "a=msid" missing, use random stream ID.
2564 if (media_streams.empty() &&
2565 !(remote_description()->description()->msid_signaling() &
2566 cricket::kMsidSignalingMediaSection)) {
2567 if (!missing_msid_default_stream_) {
2568 missing_msid_default_stream_ = MediaStreamProxy::Create(
2569 rtc::Thread::Current(),
2570 MediaStream::Create(rtc::CreateRandomUuid()));
2571 added_streams.push_back(missing_msid_default_stream_);
2572 }
2573 media_streams.push_back(missing_msid_default_stream_);
2574 }
Steve Anton3172c032018-05-03 15:30:18 -07002575 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002576 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2577 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002578 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002579 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002580 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002581 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2582 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2583 // removal of a remote track for the media description, given transceiver,
2584 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002585 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002586 (transceiver->fired_direction() &&
2587 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2588 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2589 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002590 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002591 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2592 transceiver->internal()->set_fired_direction(local_direction);
2593 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2594 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002595 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002596 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2597 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002598 transceiver->internal()->set_current_direction(local_direction);
2599 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002600 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2601 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002602 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002603 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2604 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002605 transceiver->Stop();
2606 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002607 if (!content->rejected &&
2608 RtpTransceiverDirectionHasRecv(local_direction)) {
2609 // Set ssrc to 0 in the case of an unsignalled ssrc.
2610 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002611 if (!media_desc->streams().empty() &&
2612 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002613 ssrc = media_desc->streams()[0].first_ssrc();
2614 }
2615 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002616 }
Steve Antondcc3c022017-12-22 16:02:54 -08002617 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002618 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002619 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002620 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002621 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002622 observer->OnTrack(transceiver);
2623 observer->OnAddTrack(transceiver->receiver(),
2624 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002625 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002626 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002627 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002628 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002629 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002630 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002631 }
2632 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002633 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002634 }
Steve Antondcc3c022017-12-22 16:02:54 -08002635 }
2636
Henrik Boströmfdb92012017-11-09 19:55:44 +01002637 const cricket::ContentInfo* audio_content =
2638 GetFirstAudioContent(remote_description()->description());
2639 const cricket::ContentInfo* video_content =
2640 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002641 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002642 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002643 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002644 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002645 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002646 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002647
2648 // Check if the descriptions include streams, just in case the peer supports
2649 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002650 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002651 (audio_desc && !audio_desc->streams().empty()) ||
2652 (video_desc && !video_desc->streams().empty())) {
2653 remote_peer_supports_msid_ = true;
2654 }
deadbeefab9b2d12015-10-14 11:33:11 -07002655
2656 // We wait to signal new streams until we finish processing the description,
2657 // since only at that point will new streams have all their tracks.
2658 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2659
Steve Antondcc3c022017-12-22 16:02:54 -08002660 if (!IsUnifiedPlan()) {
2661 // TODO(steveanton): When removing RTP senders/receivers in response to a
2662 // rejected media section, there is some cleanup logic that expects the
2663 // voice/ video channel to still be set. But in this method the voice/video
2664 // channel would have been destroyed by the SetRemoteDescription caller
2665 // above so the cleanup that relies on them fails to run. The RemoveSenders
2666 // calls should be moved to right before the DestroyChannel calls to fix
2667 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002668
Steve Antondcc3c022017-12-22 16:02:54 -08002669 // Find all audio rtp streams and create corresponding remote AudioTracks
2670 // and MediaStreams.
2671 if (audio_content) {
2672 if (audio_content->rejected) {
2673 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2674 } else {
2675 bool default_audio_track_needed =
2676 !remote_peer_supports_msid_ &&
2677 RtpTransceiverDirectionHasSend(audio_desc->direction());
2678 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2679 default_audio_track_needed, audio_desc->type(),
2680 new_streams);
2681 }
deadbeeffaac4972015-11-12 15:33:07 -08002682 }
deadbeefab9b2d12015-10-14 11:33:11 -07002683
Steve Antondcc3c022017-12-22 16:02:54 -08002684 // Find all video rtp streams and create corresponding remote VideoTracks
2685 // and MediaStreams.
2686 if (video_content) {
2687 if (video_content->rejected) {
2688 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2689 } else {
2690 bool default_video_track_needed =
2691 !remote_peer_supports_msid_ &&
2692 RtpTransceiverDirectionHasSend(video_desc->direction());
2693 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2694 default_video_track_needed, video_desc->type(),
2695 new_streams);
2696 }
deadbeeffaac4972015-11-12 15:33:07 -08002697 }
deadbeefab9b2d12015-10-14 11:33:11 -07002698
Steve Antondcc3c022017-12-22 16:02:54 -08002699 // Update the DataChannels with the information from the remote peer.
2700 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002701 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002702 cricket::kMediaProtocolRtpPrefix)) {
2703 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2704 }
deadbeefab9b2d12015-10-14 11:33:11 -07002705 }
deadbeefab9b2d12015-10-14 11:33:11 -07002706
Steve Antondcc3c022017-12-22 16:02:54 -08002707 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002708 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002709 for (size_t i = 0; i < new_streams->count(); ++i) {
2710 MediaStreamInterface* new_stream = new_streams->at(i);
2711 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002712 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002713 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2714 }
deadbeefab9b2d12015-10-14 11:33:11 -07002715
Steve Antondcc3c022017-12-22 16:02:54 -08002716 UpdateEndedRemoteMediaStreams();
2717 }
deadbeefab9b2d12015-10-14 11:33:11 -07002718
Steve Anton8a006912017-12-04 15:25:56 -08002719 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002720}
2721
Steve Anton0f5400a2018-07-17 14:25:36 -07002722void PeerConnection::ProcessRemovalOfRemoteTrack(
2723 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2724 transceiver,
2725 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2726 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2727 RTC_DCHECK(transceiver->mid());
2728 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2729 << *transceiver->mid();
2730 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2731 transceiver->internal()->receiver_internal()->streams();
2732 // This will remove the remote track from the streams.
2733 transceiver->internal()->receiver_internal()->set_stream_ids({});
2734 remove_list->push_back(transceiver);
2735 // Remove any streams that no longer have tracks.
2736 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2737 // of streams, see if the stream was removed by checking if this was the
2738 // last receiver with that stream ID.
2739 for (auto stream : media_streams) {
2740 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2741 remote_streams_->RemoveStream(stream);
2742 removed_streams->push_back(stream);
2743 }
2744 }
2745}
2746
Steve Antondcc3c022017-12-22 16:02:54 -08002747RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2748 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002749 const SessionDescriptionInterface& new_session,
2750 const SessionDescriptionInterface* old_local_description,
2751 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002752 RTC_DCHECK(IsUnifiedPlan());
2753
Steve Anton7464fca2018-01-19 11:10:37 -08002754 const cricket::ContentGroup* bundle_group = nullptr;
2755 if (new_session.GetType() == SdpType::kOffer) {
2756 auto bundle_group_or_error =
2757 GetEarlyBundleGroup(*new_session.description());
2758 if (!bundle_group_or_error.ok()) {
2759 return bundle_group_or_error.MoveError();
2760 }
2761 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002762 }
Steve Antondcc3c022017-12-22 16:02:54 -08002763
Steve Antondcc3c022017-12-22 16:02:54 -08002764 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002765 for (size_t i = 0; i < new_contents.size(); ++i) {
2766 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002767 cricket::MediaType media_type = new_content.media_description()->type();
2768 seen_mids_.insert(new_content.name);
2769 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2770 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002771 const cricket::ContentInfo* old_local_content = nullptr;
2772 if (old_local_description &&
2773 i < old_local_description->description()->contents().size()) {
2774 old_local_content =
2775 &old_local_description->description()->contents()[i];
2776 }
2777 const cricket::ContentInfo* old_remote_content = nullptr;
2778 if (old_remote_description &&
2779 i < old_remote_description->description()->contents().size()) {
2780 old_remote_content =
2781 &old_remote_description->description()->contents()[i];
2782 }
Steve Antondcc3c022017-12-22 16:02:54 -08002783 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002784 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2785 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002786 if (!transceiver_or_error.ok()) {
2787 return transceiver_or_error.MoveError();
2788 }
2789 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002790 RTCError error =
2791 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2792 if (!error.ok()) {
2793 return error;
2794 }
2795 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002796 if (GetDataMid() && new_content.name != *GetDataMid()) {
2797 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002798 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2799 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002800 continue;
2801 }
2802 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2803 if (!error.ok()) {
2804 return error;
2805 }
Steve Antondcc3c022017-12-22 16:02:54 -08002806 } else {
2807 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2808 "Unknown section type.");
2809 }
2810 }
2811
2812 return RTCError::OK();
2813}
2814
2815RTCError PeerConnection::UpdateTransceiverChannel(
2816 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2817 transceiver,
2818 const cricket::ContentInfo& content,
2819 const cricket::ContentGroup* bundle_group) {
2820 RTC_DCHECK(IsUnifiedPlan());
2821 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002822 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002823 if (content.rejected) {
2824 if (channel) {
2825 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002826 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002827 }
2828 } else {
2829 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002830 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002831 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002832 } else {
Steve Anton69470252018-02-09 11:43:08 -08002833 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002834 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002835 }
2836 if (!channel) {
2837 LOG_AND_RETURN_ERROR(
2838 RTCErrorType::INTERNAL_ERROR,
2839 "Failed to create channel for mid=" + content.name);
2840 }
2841 transceiver->internal()->SetChannel(channel);
2842 }
2843 }
2844 return RTCError::OK();
2845}
2846
Steve Antonfa2260d2017-12-28 16:38:23 -08002847RTCError PeerConnection::UpdateDataChannel(
2848 cricket::ContentSource source,
2849 const cricket::ContentInfo& content,
2850 const cricket::ContentGroup* bundle_group) {
2851 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002852 // If data channels are disabled, ignore this media section. CreateAnswer
2853 // will take care of rejecting it.
2854 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002855 }
2856 if (content.rejected) {
2857 DestroyDataChannel();
2858 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002859 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002860 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002861 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2862 "Failed to create data channel.");
2863 }
2864 }
2865 if (source == cricket::CS_REMOTE) {
2866 const MediaContentDescription* data_desc = content.media_description();
2867 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2868 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2869 }
2870 }
2871 }
2872 return RTCError::OK();
2873}
2874
Steve Antondcc3c022017-12-22 16:02:54 -08002875RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2876PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002877 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002878 size_t mline_index,
2879 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002880 const ContentInfo* old_local_content,
2881 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002882 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002883 // If this is an offer then the m= section might be recycled. If the m=
2884 // section is being recycled (defined as: rejected in the current local or
2885 // remote description and not rejected in new description), dissociate the
2886 // currently associated RtpTransceiver by setting its mid property to null,
2887 // and discard the mapping between the transceiver and its m= section index.
2888 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2889 old_remote_content)) {
2890 // We want to dissociate the transceiver that has the rejected mid.
2891 const std::string& old_mid =
2892 (old_local_content && old_local_content->rejected)
2893 ? old_local_content->name
2894 : old_remote_content->name;
2895 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002896 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002897 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2898 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002899 old_transceiver->internal()->set_mid(absl::nullopt);
2900 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002901 }
2902 }
2903 const MediaContentDescription* media_desc = content.media_description();
2904 auto transceiver = GetAssociatedTransceiver(content.name);
2905 if (source == cricket::CS_LOCAL) {
2906 // Find the RtpTransceiver that corresponds to this m= section, using the
2907 // mapping between transceivers and m= section indices established when
2908 // creating the offer.
2909 if (!transceiver) {
2910 transceiver = GetTransceiverByMLineIndex(mline_index);
2911 }
2912 if (!transceiver) {
2913 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2914 "Unknown transceiver");
2915 }
2916 } else {
2917 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2918 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2919 // of the same type...
2920 if (!transceiver &&
2921 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2922 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2923 }
2924 // If no RtpTransceiver was found in the previous step, create one with a
2925 // recvonly direction.
2926 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002927 RTC_LOG(LS_INFO) << "Adding "
2928 << cricket::MediaTypeToString(media_desc->type())
2929 << " transceiver for MID=" << content.name
2930 << " at i=" << mline_index
2931 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002932 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002933 auto sender =
2934 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002935 std::string receiver_id;
2936 if (!media_desc->streams().empty()) {
2937 receiver_id = media_desc->streams()[0].id;
2938 } else {
2939 receiver_id = rtc::CreateRandomUuid();
2940 }
2941 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002942 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002943 transceiver->internal()->set_direction(
2944 RtpTransceiverDirection::kRecvOnly);
2945 }
2946 }
2947 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002948 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002949 LOG_AND_RETURN_ERROR(
2950 RTCErrorType::INVALID_PARAMETER,
2951 "Transceiver type does not match media description type.");
2952 }
2953 // Associate the found or created RtpTransceiver with the m= section by
2954 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2955 // section, and establish a mapping between the transceiver and the index of
2956 // the m= section.
2957 transceiver->internal()->set_mid(content.name);
2958 transceiver->internal()->set_mline_index(mline_index);
2959 return std::move(transceiver);
2960}
2961
2962rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2963PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2964 RTC_DCHECK(IsUnifiedPlan());
2965 for (auto transceiver : transceivers_) {
2966 if (transceiver->mid() == mid) {
2967 return transceiver;
2968 }
2969 }
2970 return nullptr;
2971}
2972
2973rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2974PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2975 RTC_DCHECK(IsUnifiedPlan());
2976 for (auto transceiver : transceivers_) {
2977 if (transceiver->internal()->mline_index() == mline_index) {
2978 return transceiver;
2979 }
2980 }
2981 return nullptr;
2982}
2983
2984rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2985PeerConnection::FindAvailableTransceiverToReceive(
2986 cricket::MediaType media_type) const {
2987 RTC_DCHECK(IsUnifiedPlan());
2988 // From JSEP section 5.10 (Applying a Remote Description):
2989 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2990 // the same type that were added to the PeerConnection by addTrack and are not
2991 // associated with any m= section and are not stopped, find the first such
2992 // RtpTransceiver.
2993 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002994 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002995 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2996 !transceiver->stopped()) {
2997 return transceiver;
2998 }
2999 }
3000 return nullptr;
3001}
3002
Steve Antoned10bd92017-12-05 10:52:59 -08003003const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3004 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3005 transceiver,
3006 const SessionDescriptionInterface* sdesc) const {
3007 RTC_DCHECK(transceiver);
3008 RTC_DCHECK(sdesc);
3009 if (IsUnifiedPlan()) {
3010 if (!transceiver->internal()->mid()) {
3011 // This transceiver is not associated with a media section yet.
3012 return nullptr;
3013 }
3014 return sdesc->description()->GetContentByName(
3015 *transceiver->internal()->mid());
3016 } else {
3017 // Plan B only allows at most one audio and one video section, so use the
3018 // first media section of that type.
3019 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003020 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003021 }
3022}
3023
deadbeef46c73892016-11-16 19:42:04 -08003024PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3025 return configuration_;
3026}
3027
deadbeef293e9262017-01-11 12:28:30 -08003028bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3029 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003030 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003031 if (IsClosed()) {
3032 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3033 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3034 }
3035
Qingsi Wanga2d60672018-04-11 16:57:45 -07003036 // According to JSEP, after setLocalDescription, changing the candidate pool
3037 // size is not allowed, and changing the set of ICE servers will not result
3038 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003039 if (local_description() && configuration.ice_candidate_pool_size !=
3040 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003041 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3042 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003043 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003044 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003045
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003046 if (local_description() &&
3047 configuration.use_media_transport != configuration_.use_media_transport) {
3048 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3049 "SetLocalDescription.";
3050 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3051 }
3052
3053 if (remote_description() &&
3054 configuration.use_media_transport != configuration_.use_media_transport) {
3055 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3056 "SetRemoteDescription.";
3057 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3058 }
3059
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003060 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003061 configuration.use_media_transport_for_data_channels !=
3062 configuration_.use_media_transport_for_data_channels) {
3063 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3064 "after calling SetLocalDescription.";
3065 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3066 }
3067
3068 if (remote_description() &&
3069 configuration.use_media_transport_for_data_channels !=
3070 configuration_.use_media_transport_for_data_channels) {
3071 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3072 "after calling SetRemoteDescription.";
3073 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3074 }
3075
3076 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003077 configuration.crypto_options != configuration_.crypto_options) {
3078 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3079 "SetLocalDescription.";
3080 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3081 }
3082
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003083 if (configuration.use_media_transport_for_data_channels ||
3084 configuration.use_media_transport) {
3085 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3086 << "Media transport requires MaxBundle policy.";
3087 }
3088
deadbeef293e9262017-01-11 12:28:30 -08003089 // The simplest (and most future-compatible) way to tell if the config was
3090 // modified in an invalid way is to copy each property we do support
3091 // modifying, then use operator==. There are far more properties we don't
3092 // support modifying than those we do, and more could be added.
3093 RTCConfiguration modified_config = configuration_;
3094 modified_config.servers = configuration.servers;
3095 modified_config.type = configuration.type;
3096 modified_config.ice_candidate_pool_size =
3097 configuration.ice_candidate_pool_size;
3098 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003099 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003100 modified_config.ice_check_interval_strong_connectivity =
3101 configuration.ice_check_interval_strong_connectivity;
3102 modified_config.ice_check_interval_weak_connectivity =
3103 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003104 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3105 modified_config.ice_unwritable_min_checks =
3106 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003107 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003108 modified_config.stun_candidate_keepalive_interval =
3109 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003110 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003111 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003112 modified_config.active_reset_srtp_params =
3113 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003114 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003115 modified_config.use_media_transport_for_data_channels =
3116 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003117 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003118 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003119 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3120 }
3121
Steve Anton038834f2017-07-14 15:59:59 -07003122 // Validate the modified configuration.
3123 RTCError validate_error = ValidateConfiguration(modified_config);
3124 if (!validate_error.ok()) {
3125 return SafeSetError(std::move(validate_error), error);
3126 }
3127
deadbeef293e9262017-01-11 12:28:30 -08003128 // Note that this isn't possible through chromium, since it's an unsigned
3129 // short in WebIDL.
3130 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003131 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003132 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3133 }
3134
3135 // Parse ICE servers before hopping to network thread.
3136 cricket::ServerAddresses stun_servers;
3137 std::vector<cricket::RelayServerConfig> turn_servers;
3138 RTCErrorType parse_error =
3139 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3140 if (parse_error != RTCErrorType::NONE) {
3141 return SafeSetError(parse_error, error);
3142 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003143 // Note if STUN or TURN servers were supplied.
3144 if (!stun_servers.empty()) {
3145 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3146 }
3147 if (!turn_servers.empty()) {
3148 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3149 }
deadbeef293e9262017-01-11 12:28:30 -08003150
3151 // In theory this shouldn't fail.
3152 if (!network_thread()->Invoke<bool>(
3153 RTC_FROM_HERE,
3154 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3155 stun_servers, turn_servers, modified_config.type,
3156 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003157 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003158 modified_config.turn_customizer,
3159 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003160 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003161 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3162 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003163
deadbeefd1a38b52016-12-10 13:15:33 -08003164 // As described in JSEP, calling setConfiguration with new ICE servers or
3165 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3166 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003167 if (modified_config.servers != configuration_.servers ||
3168 modified_config.type != configuration_.type ||
3169 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003170 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003171 }
skvladd1f5fda2017-02-03 16:54:05 -08003172
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003173 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003174 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003175 modified_config.use_media_transport ||
3176 modified_config.use_media_transport_for_data_channels
3177 ? factory_->media_transport_factory()
3178 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003179
Zhi Huangb57e1692018-06-12 11:41:11 -07003180 if (configuration_.active_reset_srtp_params !=
3181 modified_config.active_reset_srtp_params) {
3182 transport_controller_->SetActiveResetSrtpParams(
3183 modified_config.active_reset_srtp_params);
3184 }
3185
deadbeef293e9262017-01-11 12:28:30 -08003186 configuration_ = modified_config;
3187 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003188}
3189
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190bool PeerConnection::AddIceCandidate(
3191 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003192 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003193 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003194 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003195 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003196 return false;
3197 }
Steve Antond25da372017-11-06 14:50:29 -08003198
3199 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003200 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003201 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003202 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003203 return false;
3204 }
3205
3206 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003207 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003208 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003209 return false;
3210 }
3211
3212 bool valid = false;
3213 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3214 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003215 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003216 return false;
3217 }
3218
3219 // Add this candidate to the remote session description.
3220 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003221 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003222 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003223 return false;
3224 }
3225
3226 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003227 bool result = UseCandidate(ice_candidate);
3228 if (result) {
3229 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3230 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3231 } else {
3232 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3233 }
3234 return result;
Steve Antond25da372017-11-06 14:50:29 -08003235 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003236 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003237 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003238 return true;
3239 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240}
3241
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003242bool PeerConnection::RemoveIceCandidates(
3243 const std::vector<cricket::Candidate>& candidates) {
3244 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003245 if (IsClosed()) {
3246 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3247 return false;
3248 }
3249
Steve Antond25da372017-11-06 14:50:29 -08003250 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003251 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3252 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003253 return false;
3254 }
3255
3256 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003257 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003258 return false;
3259 }
3260
3261 size_t number_removed =
3262 mutable_remote_description()->RemoveCandidates(candidates);
3263 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003264 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003265 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003266 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003267 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003268 }
3269
3270 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003271 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3272 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003273 RTC_LOG(LS_ERROR)
3274 << "RemoveIceCandidates: Error when removing remote candidates: "
3275 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003276 }
3277 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003278}
3279
Niels Möller0c4f7be2018-05-07 14:01:37 +02003280RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003281 if (!worker_thread()->IsCurrent()) {
3282 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003283 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003284 }
3285
Niels Möller0c4f7be2018-05-07 14:01:37 +02003286 const bool has_min = bitrate.min_bitrate_bps.has_value();
3287 const bool has_start = bitrate.start_bitrate_bps.has_value();
3288 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003289 if (has_min && *bitrate.min_bitrate_bps < 0) {
3290 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3291 "min_bitrate_bps <= 0");
3292 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003293 if (has_start) {
3294 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003296 "start_bitrate_bps < min_bitrate_bps");
3297 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003298 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3299 "curent_bitrate_bps < 0");
3300 }
3301 }
3302 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003303 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003305 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003306 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3308 "max_bitrate_bps < min_bitrate_bps");
3309 } else if (*bitrate.max_bitrate_bps < 0) {
3310 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3311 "max_bitrate_bps < 0");
3312 }
3313 }
3314
zstein4b979802017-06-02 14:37:37 -07003315 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003316 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003317
3318 return RTCError::OK();
3319}
3320
Alex Narest78609d52017-10-20 10:37:47 +02003321void PeerConnection::SetBitrateAllocationStrategy(
3322 std::unique_ptr<rtc::BitrateAllocationStrategy>
3323 bitrate_allocation_strategy) {
3324 rtc::Thread* worker_thread = factory_->worker_thread();
3325 if (!worker_thread->IsCurrent()) {
3326 rtc::BitrateAllocationStrategy* strategy_raw =
3327 bitrate_allocation_strategy.release();
3328 auto functor = [this, strategy_raw]() {
3329 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003330 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003331 };
3332 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3333 return;
3334 }
3335 RTC_DCHECK(call_.get());
3336 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3337}
3338
henrika5f6bf242017-11-01 11:06:56 +01003339void PeerConnection::SetAudioPlayout(bool playout) {
3340 if (!worker_thread()->IsCurrent()) {
3341 worker_thread()->Invoke<void>(
3342 RTC_FROM_HERE,
3343 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3344 return;
3345 }
3346 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003347 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003348 audio_state->SetPlayout(playout);
3349}
3350
3351void PeerConnection::SetAudioRecording(bool recording) {
3352 if (!worker_thread()->IsCurrent()) {
3353 worker_thread()->Invoke<void>(
3354 RTC_FROM_HERE,
3355 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3356 return;
3357 }
3358 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003359 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003360 audio_state->SetRecording(recording);
3361}
3362
Steve Anton8c0f7a72017-10-03 10:03:10 -07003363std::unique_ptr<rtc::SSLCertificate>
3364PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003365 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3366 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003367 return nullptr;
3368 }
Steve Antonf25303e2018-10-16 15:23:31 -07003369 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003370}
3371
Zhi Huang70b820f2018-01-27 14:16:15 -08003372std::unique_ptr<rtc::SSLCertChain>
3373PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003374 auto audio_transceiver = GetFirstAudioTransceiver();
3375 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003376 return nullptr;
3377 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003378 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003379 audio_transceiver->internal()->channel()->transport_name());
3380}
3381
3382rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3383PeerConnection::GetFirstAudioTransceiver() const {
3384 for (auto transceiver : transceivers_) {
3385 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3386 return transceiver;
3387 }
3388 }
3389 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003390}
3391
ivoc14d5dbe2016-07-04 07:06:55 -07003392bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3393 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003394 // TODO(eladalon): It would be better to not allow negative values into PC.
3395 const size_t max_size = (max_size_bytes < 0)
3396 ? RtcEventLog::kUnlimitedOutput
3397 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003398 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3399 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3400 output_period_ms = 5000;
3401 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003402 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003403 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003404 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003405}
3406
Bjorn Tereliusde939432017-11-20 17:38:14 +01003407bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3408 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003409 // TODO(eladalon): In C++14, this can be done with a lambda.
3410 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003411 bool operator()() {
3412 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3413 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003414 PeerConnection* const pc;
3415 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003416 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003417 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003418 return worker_thread()->Invoke<bool>(
3419 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003420}
3421
3422void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003423 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003424 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3425}
3426
Harald Alvestrandad88c882018-11-28 16:47:46 +01003427rtc::scoped_refptr<DtlsTransportInterface>
3428PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3429 return transport_controller_->LookupDtlsTransportByMid(mid);
3430}
3431
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003433 return pending_local_description_ ? pending_local_description_.get()
3434 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435}
3436
3437const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003438 return pending_remote_description_ ? pending_remote_description_.get()
3439 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003440}
3441
deadbeeffe4a8a42016-12-20 17:56:17 -08003442const SessionDescriptionInterface* PeerConnection::current_local_description()
3443 const {
Steve Anton75737c02017-11-06 10:37:17 -08003444 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003445}
3446
3447const SessionDescriptionInterface* PeerConnection::current_remote_description()
3448 const {
Steve Anton75737c02017-11-06 10:37:17 -08003449 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003450}
3451
3452const SessionDescriptionInterface* PeerConnection::pending_local_description()
3453 const {
Steve Anton75737c02017-11-06 10:37:17 -08003454 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003455}
3456
3457const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3458 const {
Steve Anton75737c02017-11-06 10:37:17 -08003459 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003460}
3461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003463 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003464 // Update stats here so that we have the most recent stats for tracks and
3465 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003466 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467
Steve Anton75737c02017-11-06 10:37:17 -08003468 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003469 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003470
Steve Anton8af21862017-12-15 11:20:13 -08003471 for (auto transceiver : transceivers_) {
3472 transceiver->Stop();
3473 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003474
3475 // Ensure that all asynchronous stats requests are completed before destroying
3476 // the transport controller below.
3477 if (stats_collector_) {
3478 stats_collector_->WaitForPendingRequest();
3479 }
3480
3481 // Don't destroy BaseChannels until after stats has been cleaned up so that
3482 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003483 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003484
Qingsi Wang93a84392018-01-30 17:13:09 -08003485 // The event log is used in the transport controller, which must be outlived
3486 // by the former. CreateOffer by the peer connection is implemented
3487 // asynchronously and if the peer connection is closed without resetting the
3488 // WebRTC session description factory, the session description factory would
3489 // call the transport controller.
3490 webrtc_session_desc_factory_.reset();
3491 transport_controller_.reset();
3492
deadbeef42a42632017-03-10 15:18:00 -08003493 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003494 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3495 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003496
Steve Anton978b8762017-09-29 12:15:02 -07003497 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003498 call_.reset();
3499 // The event log must outlive call (and any other object that uses it).
3500 event_log_.reset();
3501 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003502 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003503 // The .h file says that observer can be discarded after close() returns.
3504 // Make sure this is true.
3505 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506}
3507
Steve Antonad182762018-09-05 20:22:40 +00003508void PeerConnection::OnMessage(rtc::Message* msg) {
3509 switch (msg->message_id) {
3510 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3511 SetSessionDescriptionMsg* param =
3512 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3513 param->observer->OnSuccess();
3514 delete param;
3515 break;
3516 }
3517 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3518 SetSessionDescriptionMsg* param =
3519 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3520 param->observer->OnFailure(std::move(param->error));
3521 delete param;
3522 break;
3523 }
3524 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3525 CreateSessionDescriptionMsg* param =
3526 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3527 param->observer->OnFailure(std::move(param->error));
3528 delete param;
3529 break;
3530 }
3531 case MSG_GETSTATS: {
3532 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3533 StatsReports reports;
3534 stats_->GetStats(param->track, &reports);
3535 param->observer->OnComplete(reports);
3536 delete param;
3537 break;
3538 }
3539 case MSG_FREE_DATACHANNELS: {
3540 sctp_data_channels_to_free_.clear();
3541 break;
3542 }
3543 case MSG_REPORT_USAGE_PATTERN: {
3544 ReportUsagePattern();
3545 break;
3546 }
3547 default:
3548 RTC_NOTREACHED() << "Not implemented";
3549 break;
3550 }
3551}
3552
Steve Antonafb0bb72018-02-20 11:35:37 -08003553cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3554 RTC_DCHECK(!IsUnifiedPlan());
3555 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3556 GetAudioTransceiver()->internal()->channel());
3557 if (voice_channel) {
3558 return voice_channel->media_channel();
3559 } else {
3560 return nullptr;
3561 }
3562}
3563
3564cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3565 RTC_DCHECK(!IsUnifiedPlan());
3566 auto* video_channel = static_cast<cricket::VideoChannel*>(
3567 GetVideoTransceiver()->internal()->channel());
3568 if (video_channel) {
3569 return video_channel->media_channel();
3570 } else {
3571 return nullptr;
3572 }
3573}
3574
Steve Anton4171afb2017-11-20 10:20:22 -08003575void PeerConnection::CreateAudioReceiver(
3576 MediaStreamInterface* stream,
3577 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003578 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3579 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003580 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3581 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003582 auto* audio_receiver = new AudioRtpReceiver(
3583 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003584 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003585 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3586 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3587 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003588 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003589 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003590 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003591}
3592
Steve Anton4171afb2017-11-20 10:20:22 -08003593void PeerConnection::CreateVideoReceiver(
3594 MediaStreamInterface* stream,
3595 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003596 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3597 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003598 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3599 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003600 auto* video_receiver = new VideoRtpReceiver(
3601 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003602 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003603 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3604 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3605 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003606 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003607 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003608 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003609}
3610
deadbeef70ab1a12015-09-28 16:53:55 -07003611// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3612// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003613rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003614 const RtpSenderInfo& remote_sender_info) {
3615 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3616 if (!receiver) {
3617 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3618 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003619 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003620 }
Steve Anton4171afb2017-11-20 10:20:22 -08003621 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3622 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3623 } else {
3624 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3625 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003626 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003627}
3628
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003629void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3630 MediaStreamInterface* stream) {
3631 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003632 RTC_DCHECK(track);
3633 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003634 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003635 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003636 // We already have a sender for this track, so just change the stream_id
3637 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003638 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003639 return;
3640 }
3641
3642 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003643 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003644 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003645 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003646 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003647 // If the sender has already been configured in SDP, we call SetSsrc,
3648 // which will connect the sender to the underlying transport. This can
3649 // occur if a local session description that contains the ID of the sender
3650 // is set before AddStream is called. It can also occur if the local
3651 // session description is not changed and RemoveStream is called, and
3652 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003653 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003654 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003655 if (sender_info) {
3656 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003657 }
3658}
3659
3660// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3661// indefinitely, when we have unified plan SDP.
3662void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3663 MediaStreamInterface* stream) {
3664 RTC_DCHECK(!IsClosed());
3665 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003666 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003667 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3668 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003669 return;
3670 }
Steve Anton4171afb2017-11-20 10:20:22 -08003671 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003672}
3673
3674void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3675 MediaStreamInterface* stream) {
3676 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003677 RTC_DCHECK(track);
3678 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003679 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003680 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003681 // We already have a sender for this track, so just change the stream_id
3682 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003683 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003684 return;
3685 }
3686
3687 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003688 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003689 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003690 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003691 GetVideoTransceiver()->internal()->AddSender(new_sender);
3692 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003693 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003694 if (sender_info) {
3695 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003696 }
3697}
3698
3699void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3700 MediaStreamInterface* stream) {
3701 RTC_DCHECK(!IsClosed());
3702 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003703 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003704 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3705 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003706 return;
3707 }
Steve Anton4171afb2017-11-20 10:20:22 -08003708 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003709}
3710
Steve Antonba818672017-11-06 10:21:57 -08003711void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003712 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003713 if (ice_connection_state_ == new_state) {
3714 return;
3715 }
3716
deadbeefcbecd352015-09-23 11:50:27 -07003717 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003718 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003719 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003720 return;
3721 }
Steve Antonba818672017-11-06 10:21:57 -08003722
Mirko Bonadei675513b2017-11-09 11:09:25 +01003723 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3724 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003725 RTC_DCHECK(ice_connection_state_ !=
3726 PeerConnectionInterface::kIceConnectionClosed);
3727
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003728 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003729 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003730}
3731
Alex Loiko9289eda2018-11-23 16:18:59 +00003732void PeerConnection::SetStandardizedIceConnectionState(
3733 PeerConnectionInterface::IceConnectionState new_state) {
3734 RTC_DCHECK(signaling_thread()->IsCurrent());
3735 if (standardized_ice_connection_state_ == new_state)
3736 return;
3737 if (IsClosed())
3738 return;
3739 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003740 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003741}
3742
Jonas Olsson635474e2018-10-18 15:58:17 +02003743void PeerConnection::SetConnectionState(
3744 PeerConnectionInterface::PeerConnectionState new_state) {
3745 RTC_DCHECK(signaling_thread()->IsCurrent());
3746 if (connection_state_ == new_state)
3747 return;
3748 if (IsClosed())
3749 return;
3750 connection_state_ = new_state;
3751 Observer()->OnConnectionChange(new_state);
3752}
3753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003754void PeerConnection::OnIceGatheringChange(
3755 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003756 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003757 if (IsClosed()) {
3758 return;
3759 }
3760 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003761 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003762}
3763
jbauch81bf7b02017-03-25 08:31:12 -07003764void PeerConnection::OnIceCandidate(
3765 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003766 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003767 if (IsClosed()) {
3768 return;
3769 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003770 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003771 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3772 candidate->candidate().address().IsPrivateIP()) {
3773 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3774 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003775 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003776}
3777
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003778void PeerConnection::OnIceCandidatesRemoved(
3779 const std::vector<cricket::Candidate>& candidates) {
3780 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003781 if (IsClosed()) {
3782 return;
3783 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003784 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003785}
3786
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003787void PeerConnection::ChangeSignalingState(
3788 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003789 RTC_DCHECK(signaling_thread()->IsCurrent());
3790 if (signaling_state_ == signaling_state) {
3791 return;
3792 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003793 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3794 << GetSignalingStateString(signaling_state_)
3795 << " New state: "
3796 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003797 signaling_state_ = signaling_state;
3798 if (signaling_state == kClosed) {
3799 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003800 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003801 standardized_ice_connection_state_ =
3802 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003803 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3804 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003805 if (ice_gathering_state_ != kIceGatheringComplete) {
3806 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003807 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003808 }
3809 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003810 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003811}
3812
deadbeefeb459812015-12-15 19:24:43 -08003813void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3814 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003815 if (IsClosed()) {
3816 return;
3817 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003818 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003819 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003820}
3821
deadbeefeb459812015-12-15 19:24:43 -08003822void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3823 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003824 if (IsClosed()) {
3825 return;
3826 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003827 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003828 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003829}
3830
3831void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3832 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003833 if (IsClosed()) {
3834 return;
3835 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003836 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003837 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003838}
3839
3840void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3841 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003842 if (IsClosed()) {
3843 return;
3844 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003845 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003846 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003847}
3848
Henrik Boström31638672017-11-23 17:48:32 +01003849void PeerConnection::PostSetSessionDescriptionSuccess(
3850 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003851 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3852 signaling_thread()->Post(RTC_FROM_HERE, this,
3853 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003854}
3855
deadbeefab9b2d12015-10-14 11:33:11 -07003856void PeerConnection::PostSetSessionDescriptionFailure(
3857 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003858 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003859 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003860 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3861 msg->error = std::move(error);
3862 signaling_thread()->Post(RTC_FROM_HERE, this,
3863 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003864}
3865
3866void PeerConnection::PostCreateSessionDescriptionFailure(
3867 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003868 RTCError error) {
3869 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003870 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3871 msg->error = std::move(error);
3872 signaling_thread()->Post(RTC_FROM_HERE, this,
3873 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003874}
3875
zhihuang1c378ed2017-08-17 14:10:50 -07003876void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003877 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003878 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003879 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003880
Steve Antondcc3c022017-12-22 16:02:54 -08003881 if (IsUnifiedPlan()) {
3882 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3883 } else {
3884 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3885 }
3886
Steve Antonfa2260d2017-12-28 16:38:23 -08003887 // Intentionally unset the data channel type for RTP data channel with the
3888 // second condition. Otherwise the RTP data channels would be successfully
3889 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3890 // when building with chromium. We want to leave RTP data channels broken, so
3891 // people won't try to use them.
3892 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3893 session_options->data_channel_type = data_channel_type();
3894 }
3895
Steve Antondcc3c022017-12-22 16:02:54 -08003896 // Apply ICE restart flag and renomination flag.
3897 for (auto& options : session_options->media_description_options) {
3898 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3899 options.transport_options.enable_ice_renomination =
3900 configuration_.enable_ice_renomination;
3901 }
3902
3903 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003904 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003905 session_options->pooled_ice_credentials =
3906 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3907 RTC_FROM_HERE,
3908 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3909 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003910 session_options->offer_extmap_allow_mixed =
3911 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003912}
3913
3914void PeerConnection::GetOptionsForPlanBOffer(
3915 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3916 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003917 // Figure out transceiver directional preferences.
3918 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3919 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3920
3921 // By default, generate sendrecv/recvonly m= sections.
3922 bool recv_audio = true;
3923 bool recv_video = true;
3924
3925 // By default, only offer a new m= section if we have media to send with it.
3926 bool offer_new_audio_description = send_audio;
3927 bool offer_new_video_description = send_video;
3928 bool offer_new_data_description = HasDataChannels();
3929
3930 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003931 if (offer_answer_options.offer_to_receive_audio !=
3932 RTCOfferAnswerOptions::kUndefined) {
3933 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003934 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003935 offer_new_audio_description ||
3936 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003937 }
Steve Antondcc3c022017-12-22 16:02:54 -08003938 if (offer_answer_options.offer_to_receive_video !=
3939 RTCOfferAnswerOptions::kUndefined) {
3940 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003941 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003942 offer_new_video_description ||
3943 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003944 }
3945
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003946 absl::optional<size_t> audio_index;
3947 absl::optional<size_t> video_index;
3948 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003949 // If a current description exists, generate m= sections in the same order,
3950 // using the first audio/video/data section that appears and rejecting
3951 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003952 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003953 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003954 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003955 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3956 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3957 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003958 }
3959
zhihuang1c378ed2017-08-17 14:10:50 -07003960 // Add audio/video/data m= sections to the end if needed.
3961 if (!audio_index && offer_new_audio_description) {
3962 session_options->media_description_options.push_back(
3963 cricket::MediaDescriptionOptions(
3964 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003965 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3966 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003967 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003968 }
zhihuang1c378ed2017-08-17 14:10:50 -07003969 if (!video_index && offer_new_video_description) {
3970 session_options->media_description_options.push_back(
3971 cricket::MediaDescriptionOptions(
3972 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003973 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3974 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003975 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003976 }
zhihuang1c378ed2017-08-17 14:10:50 -07003977 if (!data_index && offer_new_data_description) {
3978 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003979 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003980 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003981 }
3982
3983 cricket::MediaDescriptionOptions* audio_media_description_options =
3984 !audio_index ? nullptr
3985 : &session_options->media_description_options[*audio_index];
3986 cricket::MediaDescriptionOptions* video_media_description_options =
3987 !video_index ? nullptr
3988 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003989
Steve Anton4171afb2017-11-20 10:20:22 -08003990 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003991 video_media_description_options,
3992 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003993}
3994
Steve Antondcc3c022017-12-22 16:02:54 -08003995static cricket::MediaDescriptionOptions
3996GetMediaDescriptionOptionsForTransceiver(
3997 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3998 transceiver,
3999 const std::string& mid) {
4000 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004001 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004002 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004003 // This behavior is specified in JSEP. The gist is that:
4004 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4005 // sendrecv.
4006 // 2. If the MSID is included, then it must be included in any subsequent
4007 // offer/answer exactly the same until the RtpTransceiver is stopped.
4008 if (!transceiver->stopped() &&
4009 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4010 transceiver->internal()->has_ever_been_used_to_send())) {
4011 cricket::SenderOptions sender_options;
4012 sender_options.track_id = transceiver->sender()->id();
4013 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004014 int num_send_encoding_layers =
4015 transceiver->sender()->init_send_encodings().size();
4016 sender_options.num_sim_layers =
4017 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004018 media_description_options.sender_options.push_back(sender_options);
4019 }
Steve Antondcc3c022017-12-22 16:02:54 -08004020 return media_description_options;
4021}
4022
Steve Anton5c72e712018-12-10 14:25:30 -08004023// Returns the ContentInfo at mline index |i|, or null if none exists.
4024static const ContentInfo* GetContentByIndex(
4025 const SessionDescriptionInterface* sdesc,
4026 size_t i) {
4027 if (!sdesc) {
4028 return nullptr;
4029 }
4030 const ContentInfos& contents = sdesc->description()->contents();
4031 return (i < contents.size() ? &contents[i] : nullptr);
4032}
4033
Steve Antondcc3c022017-12-22 16:02:54 -08004034void PeerConnection::GetOptionsForUnifiedPlanOffer(
4035 const RTCOfferAnswerOptions& offer_answer_options,
4036 cricket::MediaSessionOptions* session_options) {
4037 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4038 // Offers) and 5.2.2 (Subsequent Offers).
4039 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4040 const ContentInfos& local_contents =
4041 (local_description() ? local_description()->description()->contents()
4042 : ContentInfos());
4043 const ContentInfos& remote_contents =
4044 (remote_description() ? remote_description()->description()->contents()
4045 : ContentInfos());
4046 // The mline indices that can be recycled. New transceivers should reuse these
4047 // slots first.
4048 std::queue<size_t> recycleable_mline_indices;
4049 // Track the MIDs used in previous offer/answer exchanges and the current
4050 // offer so that new, unique MIDs are generated.
4051 std::set<std::string> used_mids = seen_mids_;
4052 // First, go through each media section that exists in either the local or
4053 // remote description and generate a media section in this offer for the
4054 // associated transceiver. If a media section can be recycled, generate a
4055 // default, rejected media section here that can be later overwritten.
4056 for (size_t i = 0;
4057 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4058 // Either |local_content| or |remote_content| is non-null.
4059 const ContentInfo* local_content =
4060 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004061 const ContentInfo* current_local_content =
4062 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004063 const ContentInfo* remote_content =
4064 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004065 const ContentInfo* current_remote_content =
4066 GetContentByIndex(current_remote_description(), i);
4067 bool had_been_rejected =
4068 (current_local_content && current_local_content->rejected) ||
4069 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004070 const std::string& mid =
4071 (local_content ? local_content->name : remote_content->name);
4072 cricket::MediaType media_type =
4073 (local_content ? local_content->media_description()->type()
4074 : remote_content->media_description()->type());
4075 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4076 media_type == cricket::MEDIA_TYPE_VIDEO) {
4077 auto transceiver = GetAssociatedTransceiver(mid);
4078 RTC_CHECK(transceiver);
4079 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004080 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004081 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004082 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004083 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4084 RtpTransceiverDirection::kInactive,
4085 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004086 recycleable_mline_indices.push(i);
4087 } else {
4088 session_options->media_description_options.push_back(
4089 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4090 // CreateOffer shouldn't really cause any state changes in
4091 // PeerConnection, but we need a way to match new transceivers to new
4092 // media sections in SetLocalDescription and JSEP specifies this is done
4093 // by recording the index of the media section generated for the
4094 // transceiver in the offer.
4095 transceiver->internal()->set_mline_index(i);
4096 }
4097 } else {
4098 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004099 RTC_CHECK(GetDataMid());
4100 if (had_been_rejected || mid != *GetDataMid()) {
4101 session_options->media_description_options.push_back(
4102 GetMediaDescriptionOptionsForRejectedData(mid));
4103 } else {
4104 session_options->media_description_options.push_back(
4105 GetMediaDescriptionOptionsForActiveData(mid));
4106 }
Steve Antondcc3c022017-12-22 16:02:54 -08004107 }
4108 }
4109 // Next, look for transceivers that are newly added (that is, are not stopped
4110 // and not associated). Reuse media sections marked as recyclable first,
4111 // otherwise append to the end of the offer. New media sections should be
4112 // added in the order they were added to the PeerConnection.
4113 for (auto transceiver : transceivers_) {
4114 if (transceiver->mid() || transceiver->stopped()) {
4115 continue;
4116 }
4117 size_t mline_index;
4118 if (!recycleable_mline_indices.empty()) {
4119 mline_index = recycleable_mline_indices.front();
4120 recycleable_mline_indices.pop();
4121 session_options->media_description_options[mline_index] =
4122 GetMediaDescriptionOptionsForTransceiver(transceiver,
4123 AllocateMid(&used_mids));
4124 } else {
4125 mline_index = session_options->media_description_options.size();
4126 session_options->media_description_options.push_back(
4127 GetMediaDescriptionOptionsForTransceiver(transceiver,
4128 AllocateMid(&used_mids)));
4129 }
4130 // See comment above for why CreateOffer changes the transceiver's state.
4131 transceiver->internal()->set_mline_index(mline_index);
4132 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004133 // Lastly, add a m-section if we have local data channels and an m section
4134 // does not already exist.
4135 if (!GetDataMid() && HasDataChannels()) {
4136 session_options->media_description_options.push_back(
4137 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4138 }
Steve Antondcc3c022017-12-22 16:02:54 -08004139}
4140
4141void PeerConnection::GetOptionsForAnswer(
4142 const RTCOfferAnswerOptions& offer_answer_options,
4143 cricket::MediaSessionOptions* session_options) {
4144 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4145
4146 if (IsUnifiedPlan()) {
4147 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4148 } else {
4149 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4150 }
4151
Steve Antonfa2260d2017-12-28 16:38:23 -08004152 // Intentionally unset the data channel type for RTP data channel. Otherwise
4153 // the RTP data channels would be successfully negotiated by default and the
4154 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4155 // We want to leave RTP data channels broken, so people won't try to use them.
4156 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4157 session_options->data_channel_type = data_channel_type();
4158 }
4159
Steve Antondcc3c022017-12-22 16:02:54 -08004160 // Apply ICE renomination flag.
4161 for (auto& options : session_options->media_description_options) {
4162 options.transport_options.enable_ice_renomination =
4163 configuration_.enable_ice_renomination;
4164 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004165
4166 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004167 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004168 session_options->pooled_ice_credentials =
4169 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4170 RTC_FROM_HERE,
4171 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4172 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004173}
4174
Steve Antondcc3c022017-12-22 16:02:54 -08004175void PeerConnection::GetOptionsForPlanBAnswer(
4176 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004177 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004178 // Figure out transceiver directional preferences.
4179 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4180 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4181
4182 // By default, generate sendrecv/recvonly m= sections. The direction is also
4183 // restricted by the direction in the offer.
4184 bool recv_audio = true;
4185 bool recv_video = true;
4186
4187 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004188 if (offer_answer_options.offer_to_receive_audio !=
4189 RTCOfferAnswerOptions::kUndefined) {
4190 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004191 }
Steve Antondcc3c022017-12-22 16:02:54 -08004192 if (offer_answer_options.offer_to_receive_video !=
4193 RTCOfferAnswerOptions::kUndefined) {
4194 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004195 }
4196
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004197 absl::optional<size_t> audio_index;
4198 absl::optional<size_t> video_index;
4199 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004200
4201 // Generate m= sections that match those in the offer.
4202 // Note that mediasession.cc will handle intersection our preferred
4203 // direction with the offered direction.
4204 GenerateMediaDescriptionOptions(
4205 remote_description(),
4206 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4207 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4208 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004209
4210 cricket::MediaDescriptionOptions* audio_media_description_options =
4211 !audio_index ? nullptr
4212 : &session_options->media_description_options[*audio_index];
4213 cricket::MediaDescriptionOptions* video_media_description_options =
4214 !video_index ? nullptr
4215 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004216
Steve Anton4171afb2017-11-20 10:20:22 -08004217 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004218 video_media_description_options,
4219 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004220}
zhihuangaf388472016-11-02 16:49:48 -07004221
Steve Antondcc3c022017-12-22 16:02:54 -08004222void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4223 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4224 cricket::MediaSessionOptions* session_options) {
4225 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4226 // Answers) and 5.3.2 (Subsequent Answers).
4227 RTC_DCHECK(remote_description());
4228 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4229 for (const ContentInfo& content :
4230 remote_description()->description()->contents()) {
4231 cricket::MediaType media_type = content.media_description()->type();
4232 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4233 media_type == cricket::MEDIA_TYPE_VIDEO) {
4234 auto transceiver = GetAssociatedTransceiver(content.name);
4235 RTC_CHECK(transceiver);
4236 session_options->media_description_options.push_back(
4237 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4238 } else {
4239 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004240 // Reject all data sections if data channels are disabled.
4241 // Reject a data section if it has already been rejected.
4242 // Reject all data sections except for the first one.
4243 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4244 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004245 session_options->media_description_options.push_back(
4246 GetMediaDescriptionOptionsForRejectedData(content.name));
4247 } else {
4248 session_options->media_description_options.push_back(
4249 GetMediaDescriptionOptionsForActiveData(content.name));
4250 }
Steve Antondcc3c022017-12-22 16:02:54 -08004251 }
4252 }
htaa2a49d92016-03-04 02:51:39 -08004253}
4254
zhihuang1c378ed2017-08-17 14:10:50 -07004255void PeerConnection::GenerateMediaDescriptionOptions(
4256 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004257 RtpTransceiverDirection audio_direction,
4258 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004259 absl::optional<size_t>* audio_index,
4260 absl::optional<size_t>* video_index,
4261 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004262 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004263 for (const cricket::ContentInfo& content :
4264 session_desc->description()->contents()) {
4265 if (IsAudioContent(&content)) {
4266 // If we already have an audio m= section, reject this extra one.
4267 if (*audio_index) {
4268 session_options->media_description_options.push_back(
4269 cricket::MediaDescriptionOptions(
4270 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004271 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004272 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004273 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004274 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004275 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4276 content.name, audio_direction,
4277 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004278 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004279 }
4280 } else if (IsVideoContent(&content)) {
4281 // If we already have an video m= section, reject this extra one.
4282 if (*video_index) {
4283 session_options->media_description_options.push_back(
4284 cricket::MediaDescriptionOptions(
4285 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004286 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004287 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004288 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004289 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004290 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4291 content.name, video_direction,
4292 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004293 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004294 }
4295 } else {
4296 RTC_DCHECK(IsDataContent(&content));
4297 // If we already have an data m= section, reject this extra one.
4298 if (*data_index) {
4299 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004300 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004301 } else {
4302 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004303 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004304 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004305 }
4306 }
htaa2a49d92016-03-04 02:51:39 -08004307 }
deadbeefab9b2d12015-10-14 11:33:11 -07004308}
4309
Steve Antonfa2260d2017-12-28 16:38:23 -08004310cricket::MediaDescriptionOptions
4311PeerConnection::GetMediaDescriptionOptionsForActiveData(
4312 const std::string& mid) const {
4313 // Direction for data sections is meaningless, but legacy endpoints might
4314 // expect sendrecv.
4315 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4316 RtpTransceiverDirection::kSendRecv,
4317 /*stopped=*/false);
4318 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4319 return options;
4320}
4321
4322cricket::MediaDescriptionOptions
4323PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4324 const std::string& mid) const {
4325 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4326 RtpTransceiverDirection::kInactive,
4327 /*stopped=*/true);
4328 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4329 return options;
4330}
4331
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004332absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004333 switch (data_channel_type_) {
4334 case cricket::DCT_RTP:
4335 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004336 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004337 }
4338 return rtp_data_channel_->content_name();
4339 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004340 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004341 case cricket::DCT_MEDIA_TRANSPORT:
4342 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004343 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004344 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004345 }
4346}
4347
Steve Anton4171afb2017-11-20 10:20:22 -08004348void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4349 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4350 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004351 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004352}
4353
Steve Anton4171afb2017-11-20 10:20:22 -08004354void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004355 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004356 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004357 cricket::MediaType media_type,
4358 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004359 RTC_DCHECK(!IsUnifiedPlan());
4360
Steve Anton4171afb2017-11-20 10:20:22 -08004361 std::vector<RtpSenderInfo>* current_senders =
4362 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004363
Steve Anton4171afb2017-11-20 10:20:22 -08004364 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004365 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004366 for (auto sender_it = current_senders->begin();
4367 sender_it != current_senders->end();
4368 /* incremented manually */) {
4369 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004370 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004371 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004372 std::string params_stream_id;
4373 if (params) {
4374 params_stream_id =
4375 (!params->first_stream_id().empty() ? params->first_stream_id()
4376 : kDefaultStreamId);
4377 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004378 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004379 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004380 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004381 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004382 sender_exists) {
4383 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004384 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004385 OnRemoteSenderRemoved(info, media_type);
4386 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004387 }
4388 }
4389
Steve Anton4171afb2017-11-20 10:20:22 -08004390 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004391 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004392 if (!params.has_ssrcs()) {
4393 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4394 // sender, this means it is coming from a Unified Plan endpoint,so we just
4395 // create a default.
4396 default_sender_needed = true;
4397 break;
4398 }
4399
Seth Hampson845e8782018-03-02 11:34:10 -08004400 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004401 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004402 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4403 // not supported in Plan B, we just take the first here and create the
4404 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004405 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004406 (!params.first_stream_id().empty() ? params.first_stream_id()
4407 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004408 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004409 uint32_t ssrc = params.first_ssrc();
4410
4411 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004412 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004413 if (!stream) {
4414 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004415 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004416 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004417 remote_streams_->AddStream(stream);
4418 new_streams->AddStream(stream);
4419 }
4420
Steve Anton4171afb2017-11-20 10:20:22 -08004421 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004422 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004423 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004424 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004425 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004426 }
4427 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004428
Steve Anton4171afb2017-11-20 10:20:22 -08004429 // Add default sender if necessary.
4430 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004431 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004432 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004433 if (!default_stream) {
4434 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004435 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004436 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004437 remote_streams_->AddStream(default_stream);
4438 new_streams->AddStream(default_stream);
4439 }
Steve Anton4171afb2017-11-20 10:20:22 -08004440 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4441 ? kDefaultAudioSenderId
4442 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004443 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004444 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004445 if (!default_sender_info) {
4446 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004447 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004448 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004449 }
4450 }
deadbeefab9b2d12015-10-14 11:33:11 -07004451}
4452
Steve Anton4171afb2017-11-20 10:20:22 -08004453void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4454 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004455 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4456 << " receiver for track_id=" << sender_info.sender_id
4457 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004458
Steve Anton3d954a62018-04-02 11:27:23 -07004459 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004460 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004461 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004462 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004463 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004464 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004465 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004466 }
4467}
4468
Steve Anton4171afb2017-11-20 10:20:22 -08004469void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4470 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004471 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4472 << " receiver for track_id=" << sender_info.sender_id
4473 << " and stream_id=" << sender_info.stream_id;
4474
Seth Hampson845e8782018-03-02 11:34:10 -08004475 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004476
Henrik Boström933d8b02017-10-10 10:05:16 -07004477 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004478 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004479 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4480 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004481 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004482 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004483 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004484 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004485 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004486 }
4487 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004488 // Stopping or destroying a VideoRtpReceiver will end the
4489 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004490 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004491 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004492 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004493 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004494 // There's no guarantee the track is still available, e.g. the track may
4495 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004496 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004497 }
4498 } else {
nisseede5da42017-01-12 05:15:36 -08004499 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004500 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004501 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004502 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004503 }
deadbeefab9b2d12015-10-14 11:33:11 -07004504}
4505
4506void PeerConnection::UpdateEndedRemoteMediaStreams() {
4507 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4508 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4509 MediaStreamInterface* stream = remote_streams_->at(i);
4510 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4511 streams_to_remove.push_back(stream);
4512 }
4513 }
4514
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004515 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004516 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004517 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004518 }
4519}
4520
Steve Anton4171afb2017-11-20 10:20:22 -08004521void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004522 const std::vector<cricket::StreamParams>& streams,
4523 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004524 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004525
Seth Hampson845e8782018-03-02 11:34:10 -08004526 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004527 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004528 for (auto sender_it = current_senders->begin();
4529 sender_it != current_senders->end();
4530 /* incremented manually */) {
4531 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004532 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004533 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4534 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004535 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004536 OnLocalSenderRemoved(info, media_type);
4537 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004538 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004539 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004540 }
4541 }
4542
Steve Anton4171afb2017-11-20 10:20:22 -08004543 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004544 for (const cricket::StreamParams& params : streams) {
4545 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004546 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004547 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004548 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004549 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004550 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004551 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004552 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004553 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004554 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004555 }
4556 }
4557}
4558
Steve Anton4171afb2017-11-20 10:20:22 -08004559void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4560 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004561 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004562 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004563 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004564 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4565 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004566 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004567 return;
4568 }
4569
deadbeeffac06552015-11-25 11:26:01 -08004570 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004571 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004572 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004573 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004574 }
deadbeeffac06552015-11-25 11:26:01 -08004575
Seth Hampson5b4f0752018-04-02 16:31:36 -07004576 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004577 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4581 cricket::MediaType media_type) {
4582 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004583 if (!sender) {
4584 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004585 // SessionDescriptions has been renegotiated.
4586 return;
4587 }
deadbeeffac06552015-11-25 11:26:01 -08004588
4589 // A sender has been removed from the SessionDescription but it's still
4590 // associated with the PeerConnection. This only occurs if the SDP doesn't
4591 // match with the calls to CreateSender, AddStream and RemoveStream.
4592 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004593 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004594 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004595 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004596 }
deadbeeffac06552015-11-25 11:26:01 -08004597
Steve Anton4171afb2017-11-20 10:20:22 -08004598 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004599}
4600
4601void PeerConnection::UpdateLocalRtpDataChannels(
4602 const cricket::StreamParamsVec& streams) {
4603 std::vector<std::string> existing_channels;
4604
4605 // Find new and active data channels.
4606 for (const cricket::StreamParams& params : streams) {
4607 // |it->sync_label| is actually the data channel label. The reason is that
4608 // we use the same naming of data channels as we do for
4609 // MediaStreams and Tracks.
4610 // For MediaStreams, the sync_label is the MediaStream label and the
4611 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004612 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004613 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004614 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004615 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004616 continue;
4617 }
4618 // Set the SSRC the data channel should use for sending.
4619 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4620 existing_channels.push_back(data_channel_it->first);
4621 }
4622
4623 UpdateClosingRtpDataChannels(existing_channels, true);
4624}
4625
4626void PeerConnection::UpdateRemoteRtpDataChannels(
4627 const cricket::StreamParamsVec& streams) {
4628 std::vector<std::string> existing_channels;
4629
4630 // Find new and active data channels.
4631 for (const cricket::StreamParams& params : streams) {
4632 // The data channel label is either the mslabel or the SSRC if the mslabel
4633 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004634 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004635 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004636 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004637 auto data_channel_it = rtp_data_channels_.find(label);
4638 if (data_channel_it == rtp_data_channels_.end()) {
4639 // This is a new data channel.
4640 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4641 } else {
4642 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4643 }
4644 existing_channels.push_back(label);
4645 }
4646
4647 UpdateClosingRtpDataChannels(existing_channels, false);
4648}
4649
4650void PeerConnection::UpdateClosingRtpDataChannels(
4651 const std::vector<std::string>& active_channels,
4652 bool is_local_update) {
4653 auto it = rtp_data_channels_.begin();
4654 while (it != rtp_data_channels_.end()) {
4655 DataChannel* data_channel = it->second;
4656 if (std::find(active_channels.begin(), active_channels.end(),
4657 data_channel->label()) != active_channels.end()) {
4658 ++it;
4659 continue;
4660 }
4661
4662 if (is_local_update) {
4663 data_channel->SetSendSsrc(0);
4664 } else {
4665 data_channel->RemotePeerRequestClose();
4666 }
4667
4668 if (data_channel->state() == DataChannel::kClosed) {
4669 rtp_data_channels_.erase(it);
4670 it = rtp_data_channels_.begin();
4671 } else {
4672 ++it;
4673 }
4674 }
4675}
4676
4677void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4678 uint32_t remote_ssrc) {
4679 rtc::scoped_refptr<DataChannel> channel(
4680 InternalCreateDataChannel(label, nullptr));
4681 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004682 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004683 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004684 return;
4685 }
4686 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004687 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4688 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004689 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004690}
4691
4692rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4693 const std::string& label,
4694 const InternalDataChannelInit* config) {
4695 if (IsClosed()) {
4696 return nullptr;
4697 }
Steve Anton75737c02017-11-06 10:37:17 -08004698 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004699 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004700 << "InternalCreateDataChannel: Data is not supported in this call.";
4701 return nullptr;
4702 }
4703 InternalDataChannelInit new_config =
4704 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004705 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004706 if (new_config.id < 0) {
4707 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004708 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004709 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004710 RTC_LOG(LS_ERROR)
4711 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004712 return nullptr;
4713 }
4714 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004715 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004716 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004717 return nullptr;
4718 }
4719 }
4720
Steve Anton75737c02017-11-06 10:37:17 -08004721 rtc::scoped_refptr<DataChannel> channel(
4722 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004723 if (!channel) {
4724 sid_allocator_.ReleaseSid(new_config.id);
4725 return nullptr;
4726 }
4727
4728 if (channel->data_channel_type() == cricket::DCT_RTP) {
4729 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004730 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4731 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004732 return nullptr;
4733 }
4734 rtp_data_channels_[channel->label()] = channel;
4735 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004736 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004737 sctp_data_channels_.push_back(channel);
4738 channel->SignalClosed.connect(this,
4739 &PeerConnection::OnSctpDataChannelClosed);
4740 }
4741
Steve Anton2d8609c2018-01-23 16:38:46 -08004742 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004743 return channel;
4744}
4745
4746bool PeerConnection::HasDataChannels() const {
4747 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4748}
4749
4750void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4751 for (const auto& channel : sctp_data_channels_) {
4752 if (channel->id() < 0) {
4753 int sid;
4754 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004755 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004756 continue;
4757 }
4758 channel->SetSctpSid(sid);
4759 }
4760 }
4761}
4762
4763void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004764 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004765 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4766 ++it) {
4767 if (it->get() == channel) {
4768 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004769 // After the closing procedure is done, it's safe to use this ID for
4770 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004771 sid_allocator_.ReleaseSid(channel->id());
4772 }
deadbeefbd292462015-12-14 18:15:29 -08004773 // Since this method is triggered by a signal from the DataChannel,
4774 // we can't free it directly here; we need to free it asynchronously.
4775 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004776 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004777 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4778 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004779 return;
4780 }
4781 }
4782}
4783
deadbeefab9b2d12015-10-14 11:33:11 -07004784void PeerConnection::OnDataChannelDestroyed() {
4785 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4786 // DataChannel may callback to us and try to modify the list.
4787 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4788 temp_rtp_dcs.swap(rtp_data_channels_);
4789 for (const auto& kv : temp_rtp_dcs) {
4790 kv.second->OnTransportChannelDestroyed();
4791 }
4792
4793 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4794 temp_sctp_dcs.swap(sctp_data_channels_);
4795 for (const auto& channel : temp_sctp_dcs) {
4796 channel->OnTransportChannelDestroyed();
4797 }
4798}
4799
4800void PeerConnection::OnDataChannelOpenMessage(
4801 const std::string& label,
4802 const InternalDataChannelInit& config) {
4803 rtc::scoped_refptr<DataChannel> channel(
4804 InternalCreateDataChannel(label, &config));
4805 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004806 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004807 return;
4808 }
4809
deadbeefa601f5c2016-06-06 14:27:39 -07004810 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4811 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004812 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004813 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004814}
4815
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004816bool PeerConnection::HandleOpenMessage_s(
4817 const cricket::ReceiveDataParams& params,
4818 const rtc::CopyOnWriteBuffer& buffer) {
4819 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4820 // Received OPEN message; parse and signal that a new data channel should
4821 // be created.
4822 std::string label;
4823 InternalDataChannelInit config;
4824 config.id = params.ssrc;
4825 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4826 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4827 << params.ssrc;
4828 return true;
4829 }
4830 config.open_handshake_role = InternalDataChannelInit::kAcker;
4831 OnDataChannelOpenMessage(label, config);
4832 return true;
4833 }
4834 return false;
4835}
4836
Steve Anton4171afb2017-11-20 10:20:22 -08004837rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4838PeerConnection::GetAudioTransceiver() const {
4839 // This method only works with Plan B SDP, where there is a single
4840 // audio/video transceiver.
4841 RTC_DCHECK(!IsUnifiedPlan());
4842 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004843 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004844 return transceiver;
4845 }
4846 }
4847 RTC_NOTREACHED();
4848 return nullptr;
4849}
4850
4851rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4852PeerConnection::GetVideoTransceiver() const {
4853 // This method only works with Plan B SDP, where there is a single
4854 // audio/video transceiver.
4855 RTC_DCHECK(!IsUnifiedPlan());
4856 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004857 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004858 return transceiver;
4859 }
4860 }
4861 RTC_NOTREACHED();
4862 return nullptr;
4863}
4864
4865// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4866// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004867bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004868 switch (type) {
4869 case cricket::MEDIA_TYPE_AUDIO:
4870 return !GetAudioTransceiver()->internal()->senders().empty();
4871 case cricket::MEDIA_TYPE_VIDEO:
4872 return !GetVideoTransceiver()->internal()->senders().empty();
4873 case cricket::MEDIA_TYPE_DATA:
4874 return false;
4875 }
4876 RTC_NOTREACHED();
4877 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004878}
4879
Steve Anton4171afb2017-11-20 10:20:22 -08004880rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4881PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4882 for (auto transceiver : transceivers_) {
4883 for (auto sender : transceiver->internal()->senders()) {
4884 if (sender->track() == track) {
4885 return sender;
4886 }
4887 }
4888 }
4889 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004890}
4891
Steve Anton4171afb2017-11-20 10:20:22 -08004892rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4893PeerConnection::FindSenderById(const std::string& sender_id) const {
4894 for (auto transceiver : transceivers_) {
4895 for (auto sender : transceiver->internal()->senders()) {
4896 if (sender->id() == sender_id) {
4897 return sender;
4898 }
4899 }
4900 }
4901 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004902}
4903
Steve Anton4171afb2017-11-20 10:20:22 -08004904rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4905PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4906 for (auto transceiver : transceivers_) {
4907 for (auto receiver : transceiver->internal()->receivers()) {
4908 if (receiver->id() == receiver_id) {
4909 return receiver;
4910 }
4911 }
4912 }
4913 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004914}
4915
Steve Anton4171afb2017-11-20 10:20:22 -08004916std::vector<PeerConnection::RtpSenderInfo>*
4917PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4918 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4919 media_type == cricket::MEDIA_TYPE_VIDEO);
4920 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4921 ? &remote_audio_sender_infos_
4922 : &remote_video_sender_infos_;
4923}
4924
4925std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004926 cricket::MediaType media_type) {
4927 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4928 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004929 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4930 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004931}
4932
Steve Anton4171afb2017-11-20 10:20:22 -08004933const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4934 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004935 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004936 const std::string sender_id) const {
4937 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004938 if (sender_info.stream_id == stream_id &&
4939 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004940 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004941 }
4942 }
4943 return nullptr;
4944}
4945
4946DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4947 for (const auto& channel : sctp_data_channels_) {
4948 if (channel->id() == sid) {
4949 return channel;
4950 }
4951 }
4952 return nullptr;
4953}
4954
deadbeef91dd5672016-05-18 16:55:30 -07004955bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004956 const cricket::ServerAddresses& stun_servers,
4957 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004958 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004959 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004960 // To handle both internal and externally created port allocator, we will
4961 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004962 port_allocator_flags_ = port_allocator_->flags();
4963 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4964 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4965 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004966 // If the disable-IPv6 flag was specified, we'll not override it
4967 // by experiment.
4968 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004969 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004970 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4971 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004972 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004973 }
4974
zhihuangb09b3f92017-03-07 14:40:51 -08004975 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004976 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004977 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004978 }
4979
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004980 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004981 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004982 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004983 }
4984
honghaiz60347052016-05-31 18:29:12 -07004985 if (configuration.candidate_network_policy ==
4986 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004987 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004988 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004989 }
4990
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004991 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004992 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004993 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4994 }
4995
Qingsi Wanga2d60672018-04-11 16:57:45 -07004996 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004997 // No step delay is used while allocating ports.
4998 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4999 port_allocator_->set_candidate_filter(
5000 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005001 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005002
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005003 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005004 for (auto& turn_server : turn_servers_copy) {
5005 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005006 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005007 // Call this last since it may create pooled allocator sessions using the
5008 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005009 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005010 stun_servers, std::move(turn_servers_copy),
5011 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5012 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005013 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005014 return true;
5015}
5016
deadbeef91dd5672016-05-18 16:55:30 -07005017bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005018 const cricket::ServerAddresses& stun_servers,
5019 const std::vector<cricket::RelayServerConfig>& turn_servers,
5020 IceTransportsType type,
5021 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005022 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005023 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005024 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005025 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005026 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005027 // According to JSEP, after setLocalDescription, changing the candidate pool
5028 // size is not allowed, and changing the set of ICE servers will not result
5029 // in new candidates being gathered.
5030 if (local_description()) {
5031 port_allocator_->FreezeCandidatePool();
5032 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005033 // Add the custom tls turn servers if they exist.
5034 auto turn_servers_copy = turn_servers;
5035 for (auto& turn_server : turn_servers_copy) {
5036 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5037 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005038 // Call this last since it may create pooled allocator sessions using the
5039 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005040 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005041 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5042 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005043}
5044
Steve Antonba818672017-11-06 10:21:57 -08005045cricket::ChannelManager* PeerConnection::channel_manager() const {
5046 return factory_->channel_manager();
5047}
5048
Elad Alon99c3fe52017-10-13 16:29:40 +02005049bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005050 std::unique_ptr<RtcEventLogOutput> output,
5051 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005052 if (!event_log_) {
5053 return false;
5054 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005055 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005056}
5057
5058void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005059 if (event_log_) {
5060 event_log_->StopLogging();
5061 }
ivoc14d5dbe2016-07-04 07:06:55 -07005062}
nisseeaabdf62017-05-05 02:23:02 -07005063
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005064cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005065 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005066 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005067 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005068 if (channel && channel->content_name() == content_name) {
5069 return channel;
5070 }
Steve Anton75737c02017-11-06 10:37:17 -08005071 }
5072 if (rtp_data_channel() &&
5073 rtp_data_channel()->content_name() == content_name) {
5074 return rtp_data_channel();
5075 }
5076 return nullptr;
5077}
5078
5079bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005080 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005081 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005082 RTC_LOG(LS_INFO)
5083 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005084 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005085 return false;
5086 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005087 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005088 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005089 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005090 return false;
5091 }
5092
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005093 absl::optional<rtc::SSLRole> dtls_role;
5094 if (sctp_mid_) {
5095 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5096 } else if (is_caller_) {
5097 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5098 }
Zhi Huange830e682018-03-30 10:48:35 -07005099 if (dtls_role) {
5100 *role = *dtls_role;
5101 return true;
5102 }
5103 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005104}
5105
5106bool PeerConnection::GetSslRole(const std::string& content_name,
5107 rtc::SSLRole* role) {
5108 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005109 RTC_LOG(LS_INFO)
5110 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005111 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005112 return false;
5113 }
5114
Zhi Huange830e682018-03-30 10:48:35 -07005115 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5116 if (dtls_role) {
5117 *role = *dtls_role;
5118 return true;
5119 }
5120 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005121}
5122
Steve Antonf8470812017-12-04 10:46:21 -08005123void PeerConnection::SetSessionError(SessionError error,
5124 const std::string& error_desc) {
5125 RTC_DCHECK_RUN_ON(signaling_thread());
5126 if (error != session_error_) {
5127 session_error_ = error;
5128 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005129 }
5130}
5131
Zhi Huange830e682018-03-30 10:48:35 -07005132RTCError PeerConnection::UpdateSessionState(
5133 SdpType type,
5134 cricket::ContentSource source,
5135 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005136 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005137
5138 // If there's already a pending error then no state transition should happen.
5139 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005140 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005141
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005142 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005143 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005144 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005145 }
5146
5147 // Update the signaling state according to the specified state machine (see
5148 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005149 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005150 ChangeSignalingState(source == cricket::CS_LOCAL
5151 ? PeerConnectionInterface::kHaveLocalOffer
5152 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005153 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005154 ChangeSignalingState(source == cricket::CS_LOCAL
5155 ? PeerConnectionInterface::kHaveLocalPrAnswer
5156 : PeerConnectionInterface::kHaveRemotePrAnswer);
5157 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005158 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005159 ChangeSignalingState(PeerConnectionInterface::kStable);
5160 }
5161
5162 // Update internal objects according to the session description's media
5163 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005164 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005165 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005166 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005167 }
5168
Steve Anton8a006912017-12-04 15:25:56 -08005169 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005170}
5171
Steve Anton8a006912017-12-04 15:25:56 -08005172RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005173 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005174 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005175 const SessionDescriptionInterface* sdesc =
5176 (source == cricket::CS_LOCAL ? local_description()
5177 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005178 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005179
5180 // Push down the new SDP media section for each audio/video transceiver.
5181 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005182 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005183 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005184 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005185 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005186 continue;
5187 }
5188 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005189 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005190 if (!content_desc) {
5191 continue;
5192 }
5193 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005194 bool success = (source == cricket::CS_LOCAL)
5195 ? channel->SetLocalContent(content_desc, type, &error)
5196 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005197 if (!success) {
5198 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5199 }
5200 }
5201
5202 // If using the RtpDataChannel, push down the new SDP section for it too.
5203 if (rtp_data_channel_) {
5204 const ContentInfo* data_content =
5205 cricket::GetFirstDataContent(sdesc->description());
5206 if (data_content && !data_content->rejected) {
5207 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005208 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005209 if (data_desc) {
5210 std::string error;
5211 bool success =
5212 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005213 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005214 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005215 if (!success) {
5216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5217 std::move(error));
5218 }
Steve Anton75737c02017-11-06 10:37:17 -08005219 }
5220 }
5221 }
Steve Antoned10bd92017-12-05 10:52:59 -08005222
Steve Anton75737c02017-11-06 10:37:17 -08005223 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5224 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5225 if (sctp_transport_ && local_description() && remote_description() &&
5226 cricket::GetFirstDataContent(local_description()->description()) &&
5227 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005228 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005229 RTC_FROM_HERE,
5230 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005231 if (!success) {
5232 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5233 "Failed to push down SCTP parameters.");
5234 }
Steve Anton75737c02017-11-06 10:37:17 -08005235 }
Steve Antoned10bd92017-12-05 10:52:59 -08005236
Steve Anton8a006912017-12-04 15:25:56 -08005237 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005238}
5239
5240bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5241 RTC_DCHECK(network_thread()->IsCurrent());
5242 RTC_DCHECK(local_description());
5243 RTC_DCHECK(remote_description());
5244 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5245 // When we support "max-message-size", that would also be pushed down here.
5246 return sctp_transport_->Start(
5247 GetSctpPort(local_description()->description()),
5248 GetSctpPort(remote_description()->description()));
5249}
5250
Steve Anton8a006912017-12-04 15:25:56 -08005251RTCError PeerConnection::PushdownTransportDescription(
5252 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005253 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005254 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005255
Zhi Huange830e682018-03-30 10:48:35 -07005256 if (source == cricket::CS_LOCAL) {
5257 const SessionDescriptionInterface* sdesc = local_description();
5258 RTC_DCHECK(sdesc);
5259 return transport_controller_->SetLocalDescription(type,
5260 sdesc->description());
5261 } else {
5262 const SessionDescriptionInterface* sdesc = remote_description();
5263 RTC_DCHECK(sdesc);
5264 return transport_controller_->SetRemoteDescription(type,
5265 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005266 }
Steve Anton75737c02017-11-06 10:37:17 -08005267}
5268
5269bool PeerConnection::GetTransportDescription(
5270 const SessionDescription* description,
5271 const std::string& content_name,
5272 cricket::TransportDescription* tdesc) {
5273 if (!description || !tdesc) {
5274 return false;
5275 }
5276 const TransportInfo* transport_info =
5277 description->GetTransportInfoByName(content_name);
5278 if (!transport_info) {
5279 return false;
5280 }
5281 *tdesc = transport_info->description;
5282 return true;
5283}
5284
Steve Anton75737c02017-11-06 10:37:17 -08005285cricket::IceConfig PeerConnection::ParseIceConfig(
5286 const PeerConnectionInterface::RTCConfiguration& config) const {
5287 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005288 switch (config.continual_gathering_policy) {
5289 case PeerConnectionInterface::GATHER_ONCE:
5290 gathering_policy = cricket::GATHER_ONCE;
5291 break;
5292 case PeerConnectionInterface::GATHER_CONTINUALLY:
5293 gathering_policy = cricket::GATHER_CONTINUALLY;
5294 break;
5295 default:
5296 RTC_NOTREACHED();
5297 gathering_policy = cricket::GATHER_ONCE;
5298 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005299
Steve Anton75737c02017-11-06 10:37:17 -08005300 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005301 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5302 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005303 ice_config.prioritize_most_likely_candidate_pairs =
5304 config.prioritize_most_likely_ice_candidate_pairs;
5305 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005306 RTCConfigurationToIceConfigOptionalInt(
5307 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005308 ice_config.continual_gathering_policy = gathering_policy;
5309 ice_config.presume_writable_when_fully_relayed =
5310 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005311 ice_config.ice_check_interval_strong_connectivity =
5312 config.ice_check_interval_strong_connectivity;
5313 ice_config.ice_check_interval_weak_connectivity =
5314 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005315 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005316 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5317 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005318 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005319 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005320 ice_config.regather_all_networks_interval_range =
5321 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005322 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005323 return ice_config;
5324}
5325
Steve Antona41959e2018-11-28 11:15:33 -08005326static absl::string_view GetTrackIdBySsrc(
5327 const SessionDescriptionInterface* session_description,
5328 uint32_t ssrc) {
5329 if (!session_description) {
5330 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005331 }
Steve Antona41959e2018-11-28 11:15:33 -08005332 for (const cricket::ContentInfo& content :
5333 session_description->description()->contents()) {
5334 const cricket::MediaContentDescription& media =
5335 *content.media_description();
5336 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5337 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5338 const cricket::StreamParams* stream_params =
5339 cricket::GetStreamBySsrc(media.streams(), ssrc);
5340 if (stream_params) {
5341 return stream_params->id;
5342 }
5343 }
5344 }
5345 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005346}
5347
Steve Antona41959e2018-11-28 11:15:33 -08005348absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5349 return GetTrackIdBySsrc(local_description(), ssrc);
5350}
5351
5352absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5353 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005354}
5355
5356bool PeerConnection::SendData(const cricket::SendDataParams& params,
5357 const rtc::CopyOnWriteBuffer& payload,
5358 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005359 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5360 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5361 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005362 return false;
5363 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005364 if (media_transport_) {
5365 SendDataParams send_params;
5366 send_params.type = ToWebrtcDataMessageType(params.type);
5367 send_params.ordered = params.ordered;
5368 if (params.max_rtx_count >= 0) {
5369 send_params.max_rtx_count = params.max_rtx_count;
5370 } else if (params.max_rtx_ms >= 0) {
5371 send_params.max_rtx_ms = params.max_rtx_ms;
5372 }
5373 return media_transport_->SendData(params.sid, send_params, payload).ok();
5374 }
Steve Anton75737c02017-11-06 10:37:17 -08005375 return rtp_data_channel_
5376 ? rtp_data_channel_->SendData(params, payload, result)
5377 : network_thread()->Invoke<bool>(
5378 RTC_FROM_HERE,
5379 Bind(&cricket::SctpTransportInternal::SendData,
5380 sctp_transport_.get(), params, payload, result));
5381}
5382
5383bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005384 RTC_DCHECK_RUN_ON(signaling_thread());
5385 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005386 // Don't log an error here, because DataChannels are expected to call
5387 // ConnectDataChannel in this state. It's the only way to initially tell
5388 // whether or not the underlying transport is ready.
5389 return false;
5390 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005391 if (media_transport_) {
5392 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5393 &DataChannel::OnChannelReady);
5394 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5395 &DataChannel::OnDataReceived);
5396 SignalMediaTransportChannelClosing_s.connect(
5397 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5398 SignalMediaTransportChannelClosed_s.connect(
5399 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5400 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005401 rtp_data_channel_->SignalReadyToSendData.connect(
5402 webrtc_data_channel, &DataChannel::OnChannelReady);
5403 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5404 &DataChannel::OnDataReceived);
5405 } else {
5406 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5407 &DataChannel::OnChannelReady);
5408 SignalSctpDataReceived.connect(webrtc_data_channel,
5409 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005410 SignalSctpClosingProcedureStartedRemotely.connect(
5411 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5412 SignalSctpClosingProcedureComplete.connect(
5413 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
5415 return true;
5416}
5417
5418void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005419 RTC_DCHECK_RUN_ON(signaling_thread());
5420 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005421 RTC_LOG(LS_ERROR)
5422 << "DisconnectDataChannel called when rtp_data_channel_ and "
5423 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005424 return;
5425 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005426 if (media_transport_) {
5427 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5428 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5429 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5430 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5431 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005432 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5433 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5434 } else {
5435 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5436 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005437 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5438 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440}
5441
5442void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005443 if (media_transport_) {
5444 // No-op. Media transport does not need to add streams.
5445 return;
5446 }
Steve Anton75737c02017-11-06 10:37:17 -08005447 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005448 RTC_LOG(LS_ERROR)
5449 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005450 return;
5451 }
5452 network_thread()->Invoke<void>(
5453 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5454 sctp_transport_.get(), sid));
5455}
5456
5457void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005458 if (media_transport_) {
5459 media_transport_->CloseChannel(sid);
5460 return;
5461 }
Steve Anton75737c02017-11-06 10:37:17 -08005462 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005463 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005464 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005465 return;
5466 }
5467 network_thread()->Invoke<void>(
5468 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5469 sctp_transport_.get(), sid));
5470}
5471
5472bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005473 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005474 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005475 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005476 sctp_ready_to_send_data_;
5477}
5478
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005479void PeerConnection::OnDataReceived(int channel_id,
5480 DataMessageType type,
5481 const rtc::CopyOnWriteBuffer& buffer) {
5482 cricket::ReceiveDataParams params;
5483 params.sid = channel_id;
5484 params.type = ToCricketDataMessageType(type);
5485 media_transport_invoker_->AsyncInvoke<void>(
5486 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5487 RTC_DCHECK_RUN_ON(signaling_thread());
5488 if (!HandleOpenMessage_s(params, buffer)) {
5489 SignalMediaTransportReceivedData_s(params, buffer);
5490 }
5491 });
5492}
5493
5494void PeerConnection::OnChannelClosing(int channel_id) {
5495 media_transport_invoker_->AsyncInvoke<void>(
5496 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5497 RTC_DCHECK_RUN_ON(signaling_thread());
5498 SignalMediaTransportChannelClosing_s(channel_id);
5499 });
5500}
5501
5502void PeerConnection::OnChannelClosed(int channel_id) {
5503 media_transport_invoker_->AsyncInvoke<void>(
5504 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5505 RTC_DCHECK_RUN_ON(signaling_thread());
5506 SignalMediaTransportChannelClosed_s(channel_id);
5507 });
5508}
5509
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005510absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005511 if (sctp_mid_ && transport_controller_) {
5512 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5513 if (dtls_transport) {
5514 return dtls_transport->transport_name();
5515 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005516 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005517 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005518 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005519}
5520
Qingsi Wang72a43a12018-02-20 16:03:18 -08005521cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5522 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005523 network_thread()->Invoke<void>(
5524 RTC_FROM_HERE,
5525 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5526 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005527 return candidate_states_list;
5528}
5529
Steve Anton5dfde182018-02-06 10:34:40 -08005530std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5531 const {
5532 std::map<std::string, std::string> transport_names_by_mid;
5533 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005534 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005535 if (channel) {
5536 transport_names_by_mid[channel->content_name()] =
5537 channel->transport_name();
5538 }
Steve Anton75737c02017-11-06 10:37:17 -08005539 }
Steve Anton5dfde182018-02-06 10:34:40 -08005540 if (rtp_data_channel_) {
5541 transport_names_by_mid[rtp_data_channel_->content_name()] =
5542 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005543 }
5544 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005545 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005546 RTC_DCHECK(transport_name);
5547 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005548 }
Steve Anton5dfde182018-02-06 10:34:40 -08005549 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005550}
5551
Steve Anton5dfde182018-02-06 10:34:40 -08005552std::map<std::string, cricket::TransportStats>
5553PeerConnection::GetTransportStatsByNames(
5554 const std::set<std::string>& transport_names) {
5555 if (!network_thread()->IsCurrent()) {
5556 return network_thread()
5557 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5558 RTC_FROM_HERE,
5559 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005560 }
Steve Anton5dfde182018-02-06 10:34:40 -08005561 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5562 for (const std::string& transport_name : transport_names) {
5563 cricket::TransportStats transport_stats;
5564 bool success =
5565 transport_controller_->GetStats(transport_name, &transport_stats);
5566 if (success) {
5567 transport_stats_by_name[transport_name] = std::move(transport_stats);
5568 } else {
5569 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5570 << transport_name;
5571 }
5572 }
5573 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005574}
5575
5576bool PeerConnection::GetLocalCertificate(
5577 const std::string& transport_name,
5578 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005579 if (!certificate) {
5580 return false;
5581 }
5582 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5583 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005584}
5585
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005586std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005587 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005588 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005589}
5590
5591cricket::DataChannelType PeerConnection::data_channel_type() const {
5592 return data_channel_type_;
5593}
5594
5595bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5596 return pending_ice_restarts_.find(content_name) !=
5597 pending_ice_restarts_.end();
5598}
5599
Steve Anton75737c02017-11-06 10:37:17 -08005600bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5601 return transport_controller_->NeedsIceRestart(content_name);
5602}
5603
5604void PeerConnection::OnCertificateReady(
5605 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5606 transport_controller_->SetLocalCertificate(certificate);
5607}
5608
5609void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005610 SetSessionError(SessionError::kTransport,
5611 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005612}
5613
Alex Loiko9289eda2018-11-23 16:18:59 +00005614void PeerConnection::OnTransportControllerConnectionState(
5615 cricket::IceConnectionState state) {
5616 switch (state) {
5617 case cricket::kIceConnectionConnecting:
5618 // If the current state is Connected or Completed, then there were
5619 // writable channels but now there are not, so the next state must
5620 // be Disconnected.
5621 // kIceConnectionConnecting is currently used as the default,
5622 // un-connected state by the TransportController, so its only use is
5623 // detecting disconnections.
5624 if (ice_connection_state_ ==
5625 PeerConnectionInterface::kIceConnectionConnected ||
5626 ice_connection_state_ ==
5627 PeerConnectionInterface::kIceConnectionCompleted) {
5628 SetIceConnectionState(
5629 PeerConnectionInterface::kIceConnectionDisconnected);
5630 }
5631 break;
5632 case cricket::kIceConnectionFailed:
5633 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5634 break;
5635 case cricket::kIceConnectionConnected:
5636 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5637 "all transports are writable.";
5638 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5639 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5640 break;
5641 case cricket::kIceConnectionCompleted:
5642 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5643 "all transports are complete.";
5644 if (ice_connection_state_ !=
5645 PeerConnectionInterface::kIceConnectionConnected) {
5646 // If jumping directly from "checking" to "connected",
5647 // signal "connected" first.
5648 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5649 }
5650 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5651 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5652 ReportTransportStats();
5653 break;
5654 default:
5655 RTC_NOTREACHED();
5656 }
5657}
5658
Steve Anton75737c02017-11-06 10:37:17 -08005659void PeerConnection::OnTransportControllerCandidatesGathered(
5660 const std::string& transport_name,
5661 const cricket::Candidates& candidates) {
5662 RTC_DCHECK(signaling_thread()->IsCurrent());
5663 int sdp_mline_index;
5664 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005665 RTC_LOG(LS_ERROR)
5666 << "OnTransportControllerCandidatesGathered: content name "
5667 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005668 return;
5669 }
5670
5671 for (cricket::Candidates::const_iterator citer = candidates.begin();
5672 citer != candidates.end(); ++citer) {
5673 // Use transport_name as the candidate media id.
5674 std::unique_ptr<JsepIceCandidate> candidate(
5675 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5676 if (local_description()) {
5677 mutable_local_description()->AddCandidate(candidate.get());
5678 }
5679 OnIceCandidate(std::move(candidate));
5680 }
5681}
5682
5683void PeerConnection::OnTransportControllerCandidatesRemoved(
5684 const std::vector<cricket::Candidate>& candidates) {
5685 RTC_DCHECK(signaling_thread()->IsCurrent());
5686 // Sanity check.
5687 for (const cricket::Candidate& candidate : candidates) {
5688 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005689 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005690 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005691 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005692 return;
5693 }
5694 }
5695
5696 if (local_description()) {
5697 mutable_local_description()->RemoveCandidates(candidates);
5698 }
5699 OnIceCandidatesRemoved(candidates);
5700}
5701
5702void PeerConnection::OnTransportControllerDtlsHandshakeError(
5703 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005704 RTC_HISTOGRAM_ENUMERATION(
5705 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5706 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005707}
5708
Steve Antoned10bd92017-12-05 10:52:59 -08005709void PeerConnection::EnableSending() {
5710 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005711 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005712 if (channel && !channel->enabled()) {
5713 channel->Enable(true);
5714 }
Steve Anton75737c02017-11-06 10:37:17 -08005715 }
5716
Steve Anton4171afb2017-11-20 10:20:22 -08005717 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005718 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005719 }
Steve Anton75737c02017-11-06 10:37:17 -08005720}
5721
5722// Returns the media index for a local ice candidate given the content name.
5723bool PeerConnection::GetLocalCandidateMediaIndex(
5724 const std::string& content_name,
5725 int* sdp_mline_index) {
5726 if (!local_description() || !sdp_mline_index) {
5727 return false;
5728 }
5729
5730 bool content_found = false;
5731 const ContentInfos& contents = local_description()->description()->contents();
5732 for (size_t index = 0; index < contents.size(); ++index) {
5733 if (contents[index].name == content_name) {
5734 *sdp_mline_index = static_cast<int>(index);
5735 content_found = true;
5736 break;
5737 }
5738 }
5739 return content_found;
5740}
5741
5742bool PeerConnection::UseCandidatesInSessionDescription(
5743 const SessionDescriptionInterface* remote_desc) {
5744 if (!remote_desc) {
5745 return true;
5746 }
5747 bool ret = true;
5748
5749 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5750 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5751 for (size_t n = 0; n < candidates->count(); ++n) {
5752 const IceCandidateInterface* candidate = candidates->at(n);
5753 bool valid = false;
5754 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5755 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005756 RTC_LOG(LS_INFO)
5757 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005758 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005759 }
5760 continue;
5761 }
5762 ret = UseCandidate(candidate);
5763 if (!ret) {
5764 break;
5765 }
5766 }
5767 }
5768 return ret;
5769}
5770
5771bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5772 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5773 size_t remote_content_size =
5774 remote_description()->description()->contents().size();
5775 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005776 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005777 return false;
5778 }
5779
5780 cricket::ContentInfo content =
5781 remote_description()->description()->contents()[mediacontent_index];
5782 std::vector<cricket::Candidate> candidates;
5783 candidates.push_back(candidate->candidate());
5784 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005785 RTCError error =
5786 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005787 if (error.ok()) {
5788 // Candidates successfully submitted for checking.
5789 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5790 ice_connection_state_ ==
5791 PeerConnectionInterface::kIceConnectionDisconnected) {
5792 // If state is New, then the session has just gotten its first remote ICE
5793 // candidates, so go to Checking.
5794 // If state is Disconnected, the session is re-using old candidates or
5795 // receiving additional ones, so go to Checking.
5796 // If state is Connected, stay Connected.
5797 // TODO(bemasc): If state is Connected, and the new candidates are for a
5798 // newly added transport, then the state actually _should_ move to
5799 // checking. Add a way to distinguish that case.
5800 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5801 }
5802 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005803 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005804 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005805 }
5806 return true;
5807}
5808
5809void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005810 // Destroy video channel first since it may have a pointer to the
5811 // voice channel.
5812 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005813 if (!video_info || video_info->rejected) {
5814 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005815 }
5816
Steve Anton6fec8802017-12-04 10:37:29 -08005817 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5818 if (!audio_info || audio_info->rejected) {
5819 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005820 }
5821
5822 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5823 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005824 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005825 }
5826}
5827
Steve Antondcc3c022017-12-22 16:02:54 -08005828RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5829 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005830 const cricket::ContentGroup* bundle_group = nullptr;
5831 if (configuration_.bundle_policy ==
5832 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005833 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005834 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005835 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5836 "max-bundle configured but session description "
5837 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005838 }
5839 }
Steve Antondcc3c022017-12-22 16:02:54 -08005840 return std::move(bundle_group);
5841}
5842
5843RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005844 // Creating the media channels. Transports should already have been created
5845 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005846 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005847 if (voice && !voice->rejected &&
5848 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005849 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005850 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005851 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5852 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005853 }
5854 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5855 }
5856
Steve Antondcc3c022017-12-22 16:02:54 -08005857 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005858 if (video && !video->rejected &&
5859 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005860 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005861 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005862 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5863 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005864 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005865 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005866 }
5867
Steve Antondcc3c022017-12-22 16:02:54 -08005868 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005869 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005870 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005871 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005872 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5873 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005874 }
5875 }
5876
Steve Anton8a006912017-12-04 15:25:56 -08005877 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005878}
5879
Steve Anton4171afb2017-11-20 10:20:22 -08005880// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005881cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005882 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005883 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005884 MediaTransportInterface* media_transport = nullptr;
5885 if (configuration_.use_media_transport) {
5886 media_transport = GetMediaTransport(mid);
5887 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005888
Steve Anton75737c02017-11-06 10:37:17 -08005889 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005890 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005891 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5892 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005893 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005894 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005895 }
Steve Anton75737c02017-11-06 10:37:17 -08005896 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5897 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005898 voice_channel->SignalSentPacket.connect(this,
5899 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005900 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005901
Steve Antoneda6ccd2017-12-04 10:21:55 -08005902 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005903}
5904
Steve Anton4171afb2017-11-20 10:20:22 -08005905// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005906cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005907 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005908 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5909
5910 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005911 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005912 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005913 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5914 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005915 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005916 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005917 }
Steve Anton75737c02017-11-06 10:37:17 -08005918 video_channel->SignalDtlsSrtpSetupFailure.connect(
5919 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005920 video_channel->SignalSentPacket.connect(this,
5921 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005922 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005923
Steve Antoneda6ccd2017-12-04 10:21:55 -08005924 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005925}
5926
Zhi Huange830e682018-03-30 10:48:35 -07005927bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005928 switch (data_channel_type_) {
5929 case cricket::DCT_MEDIA_TRANSPORT:
5930 if (network_thread()->Invoke<bool>(
5931 RTC_FROM_HERE,
5932 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5933 this, mid))) {
5934 for (const auto& channel : sctp_data_channels_) {
5935 channel->OnTransportChannelCreated();
5936 }
5937 return true;
5938 }
Steve Anton75737c02017-11-06 10:37:17 -08005939 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005940 case cricket::DCT_SCTP:
5941 if (!sctp_factory_) {
5942 RTC_LOG(LS_ERROR)
5943 << "Trying to create SCTP transport, but didn't compile with "
5944 "SCTP support (HAVE_SCTP)";
5945 return false;
5946 }
5947 if (!network_thread()->Invoke<bool>(
5948 RTC_FROM_HERE,
5949 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5950 return false;
5951 }
5952 for (const auto& channel : sctp_data_channels_) {
5953 channel->OnTransportChannelCreated();
5954 }
5955 return true;
5956 case cricket::DCT_RTP:
5957 default:
5958 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5959 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5960 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5961 SrtpRequired(), GetCryptoOptions());
5962 if (!rtp_data_channel_) {
5963 return false;
5964 }
5965 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5966 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5967 rtp_data_channel_->SignalSentPacket.connect(
5968 this, &PeerConnection::OnSentPacket_w);
5969 rtp_data_channel_->SetRtpTransport(rtp_transport);
5970 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005971 }
5972
Steve Anton75737c02017-11-06 10:37:17 -08005973 return true;
5974}
5975
5976Call::Stats PeerConnection::GetCallStats() {
5977 if (!worker_thread()->IsCurrent()) {
5978 return worker_thread()->Invoke<Call::Stats>(
5979 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5980 }
5981 if (call_) {
5982 return call_->GetStats();
5983 } else {
5984 return Call::Stats();
5985 }
5986}
5987
Zhi Huange830e682018-03-30 10:48:35 -07005988bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005989 RTC_DCHECK(network_thread()->IsCurrent());
5990 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005991 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005992 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005993 RTC_DCHECK(dtls_transport);
5994 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005995 RTC_DCHECK(sctp_transport_);
5996 sctp_invoker_.reset(new rtc::AsyncInvoker());
5997 sctp_transport_->SignalReadyToSendData.connect(
5998 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5999 sctp_transport_->SignalDataReceived.connect(
6000 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006001 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6002 // another thread. Would be nice if there was a helper class similar to
6003 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6004 // code.
6005 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6006 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6007 sctp_transport_->SignalClosingProcedureComplete.connect(
6008 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006009 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006010 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006011 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006012}
6013
6014void PeerConnection::DestroySctpTransport_n() {
6015 RTC_DCHECK(network_thread()->IsCurrent());
6016 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006017 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006018 sctp_invoker_.reset(nullptr);
6019 sctp_ready_to_send_data_ = false;
6020}
6021
6022void PeerConnection::OnSctpTransportReadyToSendData_n() {
6023 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6024 RTC_DCHECK(network_thread()->IsCurrent());
6025 // Note: Cannot use rtc::Bind here because it will grab a reference to
6026 // PeerConnection and potentially cause PeerConnection to live longer than
6027 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6028 // be destroyed before PeerConnection is destroyed, and at that point all
6029 // pending tasks will be cleared.
6030 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6031 OnSctpTransportReadyToSendData_s(true);
6032 });
6033}
6034
6035void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6036 RTC_DCHECK(signaling_thread()->IsCurrent());
6037 sctp_ready_to_send_data_ = ready;
6038 SignalSctpReadyToSendData(ready);
6039}
6040
6041void PeerConnection::OnSctpTransportDataReceived_n(
6042 const cricket::ReceiveDataParams& params,
6043 const rtc::CopyOnWriteBuffer& payload) {
6044 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6045 RTC_DCHECK(network_thread()->IsCurrent());
6046 // Note: Cannot use rtc::Bind here because it will grab a reference to
6047 // PeerConnection and potentially cause PeerConnection to live longer than
6048 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6049 // be destroyed before PeerConnection is destroyed, and at that point all
6050 // pending tasks will be cleared.
6051 sctp_invoker_->AsyncInvoke<void>(
6052 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6053 OnSctpTransportDataReceived_s(params, payload);
6054 });
6055}
6056
6057void PeerConnection::OnSctpTransportDataReceived_s(
6058 const cricket::ReceiveDataParams& params,
6059 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006060 RTC_DCHECK_RUN_ON(signaling_thread());
6061 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006062 SignalSctpDataReceived(params, payload);
6063 }
6064}
6065
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006066void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006067 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6068 RTC_DCHECK(network_thread()->IsCurrent());
6069 sctp_invoker_->AsyncInvoke<void>(
6070 RTC_FROM_HERE, signaling_thread(),
6071 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006072 &SignalSctpClosingProcedureStartedRemotely, sid));
6073}
6074
6075void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6076 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6077 RTC_DCHECK(network_thread()->IsCurrent());
6078 sctp_invoker_->AsyncInvoke<void>(
6079 RTC_FROM_HERE, signaling_thread(),
6080 rtc::Bind(&sigslot::signal1<int>::operator(),
6081 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006082}
6083
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006084bool PeerConnection::SetupMediaTransportForDataChannels_n(
6085 const std::string& mid) {
6086 media_transport_ = transport_controller_->GetMediaTransport(mid);
6087 if (!media_transport_) {
6088 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6089 return false;
6090 }
6091
6092 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6093 media_transport_->SetDataSink(this);
6094 media_transport_data_mid_ = mid;
6095 transport_controller_->SignalMediaTransportStateChanged.connect(
6096 this, &PeerConnection::OnMediaTransportStateChanged_n);
6097 // Check the initial state right away, in case transport is already writable.
6098 OnMediaTransportStateChanged_n();
6099 return true;
6100}
6101
6102void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6103 if (!media_transport_) {
6104 return;
6105 }
6106 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6107 media_transport_data_mid_.reset();
6108 media_transport_->SetDataSink(nullptr);
6109 media_transport_invoker_ = nullptr;
6110 media_transport_ = nullptr;
6111}
6112
6113void PeerConnection::OnMediaTransportStateChanged_n() {
6114 if (!media_transport_data_mid_ ||
6115 transport_controller_->GetMediaTransportState(
6116 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6117 return;
6118 }
6119 media_transport_invoker_->AsyncInvoke<void>(
6120 RTC_FROM_HERE, signaling_thread(), [this] {
6121 RTC_DCHECK_RUN_ON(signaling_thread());
6122 media_transport_ready_to_send_data_ = true;
6123 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6124 });
6125}
6126
Steve Anton75737c02017-11-06 10:37:17 -08006127// Returns false if bundle is enabled and rtcp_mux is disabled.
6128bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6129 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6130 if (!bundle_enabled)
6131 return true;
6132
6133 const cricket::ContentGroup* bundle_group =
6134 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6135 RTC_DCHECK(bundle_group != NULL);
6136
6137 const cricket::ContentInfos& contents = desc->contents();
6138 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6139 citer != contents.end(); ++citer) {
6140 const cricket::ContentInfo* content = (&*citer);
6141 RTC_DCHECK(content != NULL);
6142 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006143 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006144 if (!HasRtcpMuxEnabled(content))
6145 return false;
6146 }
6147 }
6148 // RTCP-MUX is enabled in all the contents.
6149 return true;
6150}
6151
6152bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006153 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006154}
6155
Steve Anton06817cd2018-12-18 15:55:30 -08006156static RTCError ValidateMids(const cricket::SessionDescription& description) {
6157 std::set<std::string> mids;
6158 for (const cricket::ContentInfo& content : description.contents()) {
6159 if (!mids.insert(content.name).second) {
6160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6161 "Duplicate a=mid value '" + content.name + "'.");
6162 }
6163 }
6164 return RTCError::OK();
6165}
6166
Steve Anton8a006912017-12-04 15:25:56 -08006167RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006168 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006169 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006170 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006171 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006172 }
6173
6174 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006175 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006176 }
6177
Steve Anton3828c062017-12-06 10:34:51 -08006178 SdpType type = sdesc->GetType();
6179 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6180 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006181 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006182 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006183 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006184 }
6185
Steve Anton06817cd2018-12-18 15:55:30 -08006186 RTCError error = ValidateMids(*sdesc->description());
6187 if (!error.ok()) {
6188 return error;
6189 }
6190
Steve Anton75737c02017-11-06 10:37:17 -08006191 // Verify crypto settings.
6192 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006193 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6194 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006195 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006196 if (!crypto_error.ok()) {
6197 return crypto_error;
6198 }
Steve Anton75737c02017-11-06 10:37:17 -08006199 }
6200
6201 // Verify ice-ufrag and ice-pwd.
6202 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6204 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006205 }
6206
6207 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6209 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006210 }
6211
6212 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6213 // m-lines that do not rtcp-mux enabled.
6214
6215 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006216 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006217 // With an answer we want to compare the new answer session description with
6218 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006219 const cricket::SessionDescription* offer_desc =
6220 (source == cricket::CS_LOCAL) ? remote_description()->description()
6221 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006222 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6223 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6224 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6226 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006227 }
6228 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006229 // The re-offers should respect the order of m= sections in current
6230 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006231 // With a re-offer, either the current local or current remote descriptions
6232 // could be the most up to date, so we would like to check against both of
6233 // them if they exist. It could be the case that one of them has a 0 port
6234 // for a media section, but the other does not. This is important to check
6235 // against in the case that we are recycling an m= section.
6236 const cricket::SessionDescription* current_desc = nullptr;
6237 const cricket::SessionDescription* secondary_current_desc = nullptr;
6238 if (local_description()) {
6239 current_desc = local_description()->description();
6240 if (remote_description()) {
6241 secondary_current_desc = remote_description()->description();
6242 }
6243 } else if (remote_description()) {
6244 current_desc = remote_description()->description();
6245 }
Steve Anton75737c02017-11-06 10:37:17 -08006246 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006247 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6248 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006249 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6250 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006251 }
6252 }
6253
Steve Antonba42e992018-04-09 14:10:01 -07006254 if (IsUnifiedPlan()) {
6255 // Ensure that each audio and video media section has at most one
6256 // "StreamParams". This will return an error if receiving a session
6257 // description from a "Plan B" endpoint which adds multiple tracks of the
6258 // same type. With Unified Plan, there can only be at most one track per
6259 // media section.
6260 for (const ContentInfo& content : sdesc->description()->contents()) {
6261 const MediaContentDescription& desc = *content.description;
6262 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6263 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6264 desc.streams().size() > 1u) {
6265 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6266 "Media section has more than one track specified "
6267 "with a=ssrc lines which is not supported with "
6268 "Unified Plan.");
6269 }
6270 }
6271 }
6272
Steve Anton8a006912017-12-04 15:25:56 -08006273 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006274}
6275
Steve Anton3828c062017-12-06 10:34:51 -08006276bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006277 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006278 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006279 return (state == PeerConnectionInterface::kStable) ||
6280 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006281 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006282 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006283 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6284 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6285 }
6286}
6287
Steve Anton3828c062017-12-06 10:34:51 -08006288bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006289 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006290 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006291 return (state == PeerConnectionInterface::kStable) ||
6292 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006293 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006294 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006295 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6296 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6297 }
6298}
6299
Steve Antonf8470812017-12-04 10:46:21 -08006300const char* PeerConnection::SessionErrorToString(SessionError error) const {
6301 switch (error) {
6302 case SessionError::kNone:
6303 return "ERROR_NONE";
6304 case SessionError::kContent:
6305 return "ERROR_CONTENT";
6306 case SessionError::kTransport:
6307 return "ERROR_TRANSPORT";
6308 }
6309 RTC_NOTREACHED();
6310 return "";
6311}
6312
Steve Anton75737c02017-11-06 10:37:17 -08006313std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006314 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006315 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6316 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006317 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006318}
6319
Steve Anton8e20f172018-03-06 10:55:04 -08006320void PeerConnection::ReportSdpFormatReceived(
6321 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006322 int num_audio_mlines = 0;
6323 int num_video_mlines = 0;
6324 int num_audio_tracks = 0;
6325 int num_video_tracks = 0;
6326 for (const ContentInfo& content : remote_offer.description()->contents()) {
6327 cricket::MediaType media_type = content.media_description()->type();
6328 int num_tracks = std::max(
6329 1, static_cast<int>(content.media_description()->streams().size()));
6330 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6331 num_audio_mlines += 1;
6332 num_audio_tracks += num_tracks;
6333 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6334 num_video_mlines += 1;
6335 num_video_tracks += num_tracks;
6336 }
6337 }
6338 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6339 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6340 format = kSdpFormatReceivedComplexUnifiedPlan;
6341 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6342 format = kSdpFormatReceivedComplexPlanB;
6343 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6344 format = kSdpFormatReceivedSimple;
6345 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006346 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6347 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006348}
6349
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006350void PeerConnection::NoteUsageEvent(UsageEvent event) {
6351 RTC_DCHECK_RUN_ON(signaling_thread());
6352 usage_event_accumulator_ |= static_cast<int>(event);
6353}
6354
6355void PeerConnection::ReportUsagePattern() const {
6356 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006357 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6358 usage_event_accumulator_,
6359 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006360 const int bad_bits =
6361 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6362 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6363 const int good_bits =
6364 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6365 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6366 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6367 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6368 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006369 // If called after close(), we can't report, because observer may have
6370 // been deallocated, and therefore pointer is null. Write to log instead.
6371 if (observer_) {
6372 Observer()->OnInterestingUsage(usage_event_accumulator_);
6373 } else {
6374 RTC_LOG(LS_INFO) << "Interesting usage signature "
6375 << usage_event_accumulator_
6376 << " observed after observer shutdown";
6377 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006378 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006379}
6380
Steve Anton0ffaaa22018-02-23 10:31:30 -08006381void PeerConnection::ReportNegotiatedSdpSemantics(
6382 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006383 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006384 switch (answer.description()->msid_signaling()) {
6385 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006386 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006387 break;
6388 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006389 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006390 break;
6391 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006392 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006393 break;
6394 case cricket::kMsidSignalingMediaSection |
6395 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006396 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006397 break;
6398 default:
6399 RTC_NOTREACHED();
6400 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006401 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6402 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006403}
6404
Steve Anton75737c02017-11-06 10:37:17 -08006405// We need to check the local/remote description for the Transport instead of
6406// the session, because a new Transport added during renegotiation may have
6407// them unset while the session has them set from the previous negotiation.
6408// Not doing so may trigger the auto generation of transport description and
6409// mess up DTLS identity information, ICE credential, etc.
6410bool PeerConnection::ReadyToUseRemoteCandidate(
6411 const IceCandidateInterface* candidate,
6412 const SessionDescriptionInterface* remote_desc,
6413 bool* valid) {
6414 *valid = true;
6415
6416 const SessionDescriptionInterface* current_remote_desc =
6417 remote_desc ? remote_desc : remote_description();
6418
6419 if (!current_remote_desc) {
6420 return false;
6421 }
6422
6423 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6424 size_t remote_content_size =
6425 current_remote_desc->description()->contents().size();
6426 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006427 RTC_LOG(LS_ERROR)
6428 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6429 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006430
6431 *valid = false;
6432 return false;
6433 }
6434
6435 cricket::ContentInfo content =
6436 current_remote_desc->description()->contents()[mediacontent_index];
6437
6438 const std::string transport_name = GetTransportName(content.name);
6439 if (transport_name.empty()) {
6440 return false;
6441 }
Zhi Huange830e682018-03-30 10:48:35 -07006442 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006443}
6444
6445bool PeerConnection::SrtpRequired() const {
6446 return dtls_enabled_ ||
6447 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6448}
6449
6450void PeerConnection::OnTransportControllerGatheringState(
6451 cricket::IceGatheringState state) {
6452 RTC_DCHECK(signaling_thread()->IsCurrent());
6453 if (state == cricket::kIceGatheringGathering) {
6454 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6455 } else if (state == cricket::kIceGatheringComplete) {
6456 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6457 }
6458}
6459
6460void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006461 std::map<std::string, std::set<cricket::MediaType>>
6462 media_types_by_transport_name;
6463 for (auto transceiver : transceivers_) {
6464 if (transceiver->internal()->channel()) {
6465 const std::string& transport_name =
6466 transceiver->internal()->channel()->transport_name();
6467 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006468 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006469 }
Steve Anton75737c02017-11-06 10:37:17 -08006470 }
6471 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006472 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6473 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006474 }
Zhi Huange830e682018-03-30 10:48:35 -07006475
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006476 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006477 if (transport_name) {
6478 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006479 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006480 }
Zhi Huange830e682018-03-30 10:48:35 -07006481
Steve Antonc7b964c2018-02-01 14:39:45 -08006482 for (const auto& entry : media_types_by_transport_name) {
6483 const std::string& transport_name = entry.first;
6484 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006485 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006486 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006487 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006488 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006489 }
6490 }
6491}
6492// Walk through the ConnectionInfos to gather best connection usage
6493// for IPv4 and IPv6.
6494void PeerConnection::ReportBestConnectionState(
6495 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006496 for (const cricket::TransportChannelStats& channel_stats :
6497 stats.channel_stats) {
6498 for (const cricket::ConnectionInfo& connection_info :
6499 channel_stats.connection_infos) {
6500 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006501 continue;
6502 }
6503
Steve Antonc7b964c2018-02-01 14:39:45 -08006504 const cricket::Candidate& local = connection_info.local_candidate;
6505 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006506
6507 // Increment the counter for IceCandidatePairType.
6508 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6509 (local.type() == RELAY_PORT_TYPE &&
6510 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006511 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6512 GetIceCandidatePairCounter(local, remote),
6513 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006514 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006515 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6516 GetIceCandidatePairCounter(local, remote),
6517 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006518 } else {
6519 RTC_CHECK(0);
6520 }
Steve Anton75737c02017-11-06 10:37:17 -08006521
6522 // Increment the counter for IP type.
6523 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006524 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6525 kBestConnections_IPv4,
6526 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006527 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006528 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6529 kBestConnections_IPv6,
6530 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006531 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006532 RTC_CHECK(!local.address().hostname().empty() &&
6533 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006534 }
6535
6536 return;
6537 }
6538 }
6539}
6540
6541void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006542 const cricket::TransportStats& stats,
6543 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006544 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6545 return;
6546 }
6547
6548 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6549 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6550 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6551 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6552 return;
6553 }
6554
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006555 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6556 for (cricket::MediaType media_type : media_types) {
6557 switch (media_type) {
6558 case cricket::MEDIA_TYPE_AUDIO:
6559 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6560 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6561 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6562 break;
6563 case cricket::MEDIA_TYPE_VIDEO:
6564 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6565 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6566 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6567 break;
6568 case cricket::MEDIA_TYPE_DATA:
6569 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6570 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6571 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6572 break;
6573 default:
6574 RTC_NOTREACHED();
6575 continue;
6576 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006577 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006578 }
6579
6580 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6581 for (cricket::MediaType media_type : media_types) {
6582 switch (media_type) {
6583 case cricket::MEDIA_TYPE_AUDIO:
6584 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6585 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6586 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6587 break;
6588 case cricket::MEDIA_TYPE_VIDEO:
6589 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6590 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6591 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6592 break;
6593 case cricket::MEDIA_TYPE_DATA:
6594 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6595 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6596 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6597 break;
6598 default:
6599 RTC_NOTREACHED();
6600 continue;
6601 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006602 }
Steve Anton75737c02017-11-06 10:37:17 -08006603 }
6604}
6605
6606void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6607 RTC_DCHECK(worker_thread()->IsCurrent());
6608 RTC_DCHECK(call_);
6609 call_->OnSentPacket(sent_packet);
6610}
6611
6612const std::string PeerConnection::GetTransportName(
6613 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006614 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006615 if (channel) {
6616 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006617 }
Steve Anton6fec8802017-12-04 10:37:29 -08006618 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006619 RTC_DCHECK(sctp_mid_);
6620 if (content_name == *sctp_mid_) {
6621 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006622 }
6623 }
6624 // Return an empty string if failed to retrieve the transport name.
6625 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006626}
6627
Steve Anton6fec8802017-12-04 10:37:29 -08006628void PeerConnection::DestroyTransceiverChannel(
6629 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6630 transceiver) {
6631 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006632
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006633 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006634 if (channel) {
6635 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006636 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006637 }
6638}
6639
6640void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006641 if (rtp_data_channel_) {
6642 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006643 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006644 rtp_data_channel_ = nullptr;
6645 }
6646
6647 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6648 // grab a reference to this PeerConnection. If this is called from the
6649 // PeerConnection destructor, the RefCountedObject vtable will have already
6650 // been destroyed (since it is a subclass of PeerConnection) and using
6651 // rtc::Bind will cause "Pure virtual function called" error to appear.
6652
6653 if (sctp_transport_) {
6654 OnDataChannelDestroyed();
6655 network_thread()->Invoke<void>(RTC_FROM_HERE,
6656 [this] { DestroySctpTransport_n(); });
6657 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006658
6659 if (media_transport_) {
6660 OnDataChannelDestroyed();
6661 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6662 RTC_DCHECK_RUN_ON(network_thread());
6663 TeardownMediaTransportForDataChannels_n();
6664 });
6665 }
Steve Anton6fec8802017-12-04 10:37:29 -08006666}
6667
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006668void PeerConnection::DestroyChannelInterface(
6669 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006670 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006671 switch (channel->media_type()) {
6672 case cricket::MEDIA_TYPE_AUDIO:
6673 channel_manager()->DestroyVoiceChannel(
6674 static_cast<cricket::VoiceChannel*>(channel));
6675 break;
6676 case cricket::MEDIA_TYPE_VIDEO:
6677 channel_manager()->DestroyVideoChannel(
6678 static_cast<cricket::VideoChannel*>(channel));
6679 break;
6680 case cricket::MEDIA_TYPE_DATA:
6681 channel_manager()->DestroyRtpDataChannel(
6682 static_cast<cricket::RtpDataChannel*>(channel));
6683 break;
6684 default:
6685 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6686 break;
6687 }
Zhi Huange830e682018-03-30 10:48:35 -07006688}
Steve Anton6fec8802017-12-04 10:37:29 -08006689
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006690bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006691 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006692 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006693 cricket::DtlsTransportInternal* dtls_transport,
6694 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006695 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006696 auto base_channel = GetChannel(mid);
6697 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006698 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006699 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006700 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006701 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006702 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006703
6704 call_->MediaTransportChange(media_transport);
6705
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006706 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006707}
6708
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006709PeerConnectionObserver* PeerConnection::Observer() const {
6710 // In earlier production code, the pointer was not cleared on close,
6711 // which might have led to undefined behavior if the observer was not
6712 // deallocated, or strange crashes if it was.
6713 // We use CHECK in order to catch such behavior if it exists.
6714 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6715 RTC_CHECK(observer_);
6716 return observer_;
6717}
6718
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006719CryptoOptions PeerConnection::GetCryptoOptions() {
6720 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6721 // after it has been removed.
6722 return configuration_.crypto_options.has_value()
6723 ? *configuration_.crypto_options
6724 : factory_->options().crypto_options;
6725}
6726
Harald Alvestrand89061872018-01-02 14:08:34 +01006727void PeerConnection::ClearStatsCache() {
6728 if (stats_collector_) {
6729 stats_collector_->ClearCachedStatsReport();
6730 }
6731}
6732
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006733void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006734 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6735 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006736}
6737
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006738} // namespace webrtc