blob: 9434b0b6e259573f0fc13fbbe4065aec3468f27a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
Steve Antonad182762018-09-05 20:22:40 +0000104enum {
105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
106 MSG_SET_SESSIONDESCRIPTION_FAILED,
107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
108 MSG_GETSTATS,
109 MSG_FREE_DATACHANNELS,
110 MSG_REPORT_USAGE_PATTERN,
111};
112
Harald Alvestrand19793842018-06-25 12:03:50 +0200113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
Steve Antonad182762018-09-05 20:22:40 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
118 : observer(observer) {}
119
120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
121 RTCError error;
122};
123
124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct GetStatsMsg : public rtc::MessageData {
134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
136 : observer(observer), track(track) {}
137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
139};
140
deadbeefab9b2d12015-10-14 11:33:11 -0700141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200176 cricket::MediaDescriptionOptions* video_media_description_options,
177 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700178 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700179 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
180 if (audio_media_description_options) {
181 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700182 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700183 }
184 } else {
185 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
186 if (video_media_description_options) {
187 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200188 sender->id(), sender->internal()->stream_ids(),
189 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700190 }
191 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700192 }
zhihuang1c378ed2017-08-17 14:10:50 -0700193}
olka3c747662017-08-17 06:50:32 -0700194
zhihuang1c378ed2017-08-17 14:10:50 -0700195// Add options to |session_options| from |rtp_data_channels|.
196void AddRtpDataChannelOptions(
197 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
198 rtp_data_channels,
199 cricket::MediaDescriptionOptions* data_media_description_options) {
200 if (!data_media_description_options) {
201 return;
202 }
deadbeefab9b2d12015-10-14 11:33:11 -0700203 // Check for data channels.
204 for (const auto& kv : rtp_data_channels) {
205 const DataChannel* channel = kv.second;
206 if (channel->state() == DataChannel::kConnecting ||
207 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700208 // Legacy RTP data channels are signaled with the track/stream ID set to
209 // the data channel's label.
210 data_media_description_options->AddRtpDataChannel(channel->label(),
211 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700212 }
213 }
214}
215
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700216uint32_t ConvertIceTransportTypeToCandidateFilter(
217 PeerConnectionInterface::IceTransportsType type) {
218 switch (type) {
219 case PeerConnectionInterface::kNone:
220 return cricket::CF_NONE;
221 case PeerConnectionInterface::kRelay:
222 return cricket::CF_RELAY;
223 case PeerConnectionInterface::kNoHost:
224 return (cricket::CF_ALL & ~cricket::CF_HOST);
225 case PeerConnectionInterface::kAll:
226 return cricket::CF_ALL;
227 default:
nissec80e7412017-01-11 05:56:46 -0800228 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700229 }
230 return cricket::CF_NONE;
231}
232
deadbeef293e9262017-01-11 12:28:30 -0800233// Helper to set an error and return from a method.
234bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
235 if (error) {
236 error->set_type(type);
237 }
238 return type == webrtc::RTCErrorType::NONE;
239}
240
Steve Anton038834f2017-07-14 15:59:59 -0700241bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700242 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700243 if (error_out) {
244 *error_out = std::move(error);
245 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700246 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700247}
248
Steve Antonba818672017-11-06 10:21:57 -0800249std::string GetSignalingStateString(
250 PeerConnectionInterface::SignalingState state) {
251 switch (state) {
252 case PeerConnectionInterface::kStable:
253 return "kStable";
254 case PeerConnectionInterface::kHaveLocalOffer:
255 return "kHaveLocalOffer";
256 case PeerConnectionInterface::kHaveLocalPrAnswer:
257 return "kHavePrAnswer";
258 case PeerConnectionInterface::kHaveRemoteOffer:
259 return "kHaveRemoteOffer";
260 case PeerConnectionInterface::kHaveRemotePrAnswer:
261 return "kHaveRemotePrAnswer";
262 case PeerConnectionInterface::kClosed:
263 return "kClosed";
264 }
265 RTC_NOTREACHED();
266 return "";
267}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700268
Steve Anton75737c02017-11-06 10:37:17 -0800269IceCandidatePairType GetIceCandidatePairCounter(
270 const cricket::Candidate& local,
271 const cricket::Candidate& remote) {
272 const auto& l = local.type();
273 const auto& r = remote.type();
274 const auto& host = LOCAL_PORT_TYPE;
275 const auto& srflx = STUN_PORT_TYPE;
276 const auto& relay = RELAY_PORT_TYPE;
277 const auto& prflx = PRFLX_PORT_TYPE;
278 if (l == host && r == host) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800279 bool local_hostname =
280 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
281 bool remote_hostname = !remote.address().hostname().empty() &&
282 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800283 bool local_private = IPIsPrivate(local.address().ipaddr());
284 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800285 if (local_hostname) {
286 if (remote_hostname) {
287 return kIceCandidatePairHostNameHostName;
288 } else if (remote_private) {
289 return kIceCandidatePairHostNameHostPrivate;
290 } else {
291 return kIceCandidatePairHostNameHostPublic;
292 }
293 } else if (local_private) {
294 if (remote_hostname) {
295 return kIceCandidatePairHostPrivateHostName;
296 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800297 return kIceCandidatePairHostPrivateHostPrivate;
298 } else {
299 return kIceCandidatePairHostPrivateHostPublic;
300 }
301 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800302 if (remote_hostname) {
303 return kIceCandidatePairHostPublicHostName;
304 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800305 return kIceCandidatePairHostPublicHostPrivate;
306 } else {
307 return kIceCandidatePairHostPublicHostPublic;
308 }
309 }
310 }
311 if (l == host && r == srflx)
312 return kIceCandidatePairHostSrflx;
313 if (l == host && r == relay)
314 return kIceCandidatePairHostRelay;
315 if (l == host && r == prflx)
316 return kIceCandidatePairHostPrflx;
317 if (l == srflx && r == host)
318 return kIceCandidatePairSrflxHost;
319 if (l == srflx && r == srflx)
320 return kIceCandidatePairSrflxSrflx;
321 if (l == srflx && r == relay)
322 return kIceCandidatePairSrflxRelay;
323 if (l == srflx && r == prflx)
324 return kIceCandidatePairSrflxPrflx;
325 if (l == relay && r == host)
326 return kIceCandidatePairRelayHost;
327 if (l == relay && r == srflx)
328 return kIceCandidatePairRelaySrflx;
329 if (l == relay && r == relay)
330 return kIceCandidatePairRelayRelay;
331 if (l == relay && r == prflx)
332 return kIceCandidatePairRelayPrflx;
333 if (l == prflx && r == host)
334 return kIceCandidatePairPrflxHost;
335 if (l == prflx && r == srflx)
336 return kIceCandidatePairPrflxSrflx;
337 if (l == prflx && r == relay)
338 return kIceCandidatePairPrflxRelay;
339 return kIceCandidatePairMax;
340}
341
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800342// Logic to decide if an m= section can be recycled. This means that the new
343// m= section is not rejected, but the old local or remote m= section is
344// rejected. |old_content_one| and |old_content_two| refer to the m= section
345// of the old remote and old local descriptions in no particular order.
346// We need to check both the old local and remote because either
347// could be the most current from the latest negotation.
348bool IsMediaSectionBeingRecycled(SdpType type,
349 const ContentInfo& content,
350 const ContentInfo* old_content_one,
351 const ContentInfo* old_content_two) {
352 return type == SdpType::kOffer && !content.rejected &&
353 ((old_content_one && old_content_one->rejected) ||
354 (old_content_two && old_content_two->rejected));
355}
356
Steve Anton75737c02017-11-06 10:37:17 -0800357// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800358// |current_desc|. The number of m= sections in |new_desc| should be no
359// less than |current_desc|. In the case of checking an answer's
360// |new_desc|, the |current_desc| is the last offer that was set as the
361// local or remote. In the case of checking an offer's |new_desc| we
362// check against the local and remote descriptions stored from the last
363// negotiation, because either of these could be the most up to date for
364// possible rejected m sections. These are the |current_desc| and
365// |secondary_current_desc|.
366bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
367 const SessionDescription* secondary_current_desc,
368 const SessionDescription& new_desc,
369 const SdpType type) {
370 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800371 return false;
372 }
373
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800374 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
375 const cricket::ContentInfo* secondary_content_info = nullptr;
376 if (secondary_current_desc &&
377 i < secondary_current_desc->contents().size()) {
378 secondary_content_info = &secondary_current_desc->contents()[i];
379 }
380 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
381 &current_desc.contents()[i],
382 secondary_content_info)) {
383 // For new offer descriptions, if the media section can be recycled, it's
384 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800385 continue;
386 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800387 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800388 return false;
389 }
390 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800391 new_desc.contents()[i].media_description();
392 const MediaContentDescription* current_desc_mdesc =
393 current_desc.contents()[i].media_description();
394 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800395 return false;
396 }
397 }
398 return true;
399}
400
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800401bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
402 const SessionDescription& desc2) {
403 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800404}
405
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700406void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
407 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200408 // Array of structs needed to map {KeyExchangeProtocolType,
409 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
410 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
411 static constexpr struct {
412 KeyExchangeProtocolType protocol_type;
413 cricket::MediaType media_type;
414 KeyExchangeProtocolMedia protocol_media;
415 } kEnumCounterKeyProtocolMediaMap[] = {
416 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
417 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
418 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
419 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
420 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
421 kEnumCounterKeyProtocolMediaTypeDtlsData},
422 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
423 kEnumCounterKeyProtocolMediaTypeSdesAudio},
424 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
425 kEnumCounterKeyProtocolMediaTypeSdesVideo},
426 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
427 kEnumCounterKeyProtocolMediaTypeSdesData},
428 };
429
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700430 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
431 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100432
Mirko Bonadeiab499822018-09-11 10:43:20 +0200433 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
434 if (i.protocol_type == protocol_type && i.media_type == media_type) {
435 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
436 i.protocol_media,
437 kEnumCounterKeyProtocolMediaTypeMax);
438 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100439 }
440}
441
Harald Alvestrand76829d72018-07-18 23:24:36 +0200442void NoteAddIceCandidateResult(int result) {
443 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
444 kAddIceCandidateMax);
445}
446
Steve Anton75737c02017-11-06 10:37:17 -0800447// Checks that each non-rejected content has SDES crypto keys or a DTLS
448// fingerprint, unless it's in a BUNDLE group, in which case only the
449// BUNDLE-tag section (first media section/description in the BUNDLE group)
450// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
451// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
452// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700453RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800454 const cricket::ContentGroup* bundle =
455 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800456 for (const cricket::ContentInfo& content_info : desc->contents()) {
457 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800458 continue;
459 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100460 // Note what media is used with each crypto protocol, for all sections.
461 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
462 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700463 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800464 const std::string& mid = content_info.name;
465 if (bundle && bundle->HasContentName(mid) &&
466 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800467 // This isn't the first media section in the BUNDLE group, so it's not
468 // required to have crypto attributes, since only the crypto attributes
469 // from the first section actually get used.
470 continue;
471 }
472
473 // If the content isn't rejected or bundled into another m= section, crypto
474 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800475 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800476 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800477 if (!media || !tinfo) {
478 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800479 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800480 }
481 if (dtls_enabled) {
482 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100483 RTC_LOG(LS_WARNING)
484 << "Session description must have DTLS fingerprint if "
485 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800486 return RTCError(RTCErrorType::INVALID_PARAMETER,
487 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800488 }
489 } else {
490 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100491 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800492 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800493 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800494 }
495 }
496 }
Steve Anton8a006912017-12-04 15:25:56 -0800497 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800498}
499
500// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
501// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
502// media section/description in the BUNDLE group) needs a ufrag and pwd.
503bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
504 const cricket::ContentGroup* bundle =
505 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800506 for (const cricket::ContentInfo& content_info : desc->contents()) {
507 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800508 continue;
509 }
Steve Anton8a006912017-12-04 15:25:56 -0800510 const std::string& mid = content_info.name;
511 if (bundle && bundle->HasContentName(mid) &&
512 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800513 // This isn't the first media section in the BUNDLE group, so it's not
514 // required to have ufrag/password, since only the ufrag/password from
515 // the first section actually get used.
516 continue;
517 }
518
519 // If the content isn't rejected or bundled into another m= section,
520 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800521 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800522 if (!tinfo) {
523 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100524 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800525 return false;
526 }
527 if (tinfo->description.ice_ufrag.empty() ||
528 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100529 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800530 return false;
531 }
532 }
533 return true;
534}
535
Steve Anton75737c02017-11-06 10:37:17 -0800536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200596 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200599 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800600}
601
Seth Hampson5b4f0752018-04-02 16:31:36 -0700602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200613absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200617 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700618 }
619 return rtc_configuration_parameter;
620}
621
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800622cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
623 switch (type) {
624 case DataMessageType::kText:
625 return cricket::DMT_TEXT;
626 case DataMessageType::kBinary:
627 return cricket::DMT_BINARY;
628 case DataMessageType::kControl:
629 return cricket::DMT_CONTROL;
630 default:
631 return cricket::DMT_NONE;
632 }
633 return cricket::DMT_NONE;
634}
635
636DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
637 switch (type) {
638 case cricket::DMT_TEXT:
639 return DataMessageType::kText;
640 case cricket::DMT_BINARY:
641 return DataMessageType::kBinary;
642 case cricket::DMT_CONTROL:
643 return DataMessageType::kControl;
644 case cricket::DMT_NONE:
645 default:
646 RTC_NOTREACHED();
647 }
648 return DataMessageType::kControl;
649}
650
Steve Anton75737c02017-11-06 10:37:17 -0800651} // namespace
652
Henrik Boström31638672017-11-23 17:48:32 +0100653// Upon completion, posts a task to execute the callback of the
654// SetSessionDescriptionObserver asynchronously on the same thread. At this
655// point, the state of the peer connection might no longer reflect the effects
656// of the SetRemoteDescription operation, as the peer connection could have been
657// modified during the post.
658// TODO(hbos): Remove this class once we remove the version of
659// PeerConnectionInterface::SetRemoteDescription() that takes a
660// SetSessionDescriptionObserver as an argument.
661class PeerConnection::SetRemoteDescriptionObserverAdapter
662 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
663 public:
664 SetRemoteDescriptionObserverAdapter(
665 rtc::scoped_refptr<PeerConnection> pc,
666 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
667 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
668
669 // SetRemoteDescriptionObserverInterface implementation.
670 void OnSetRemoteDescriptionComplete(RTCError error) override {
671 if (error.ok())
672 pc_->PostSetSessionDescriptionSuccess(wrapper_);
673 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100674 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100675 }
676
677 private:
678 rtc::scoped_refptr<PeerConnection> pc_;
679 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
680};
681
deadbeef293e9262017-01-11 12:28:30 -0800682bool PeerConnectionInterface::RTCConfiguration::operator==(
683 const PeerConnectionInterface::RTCConfiguration& o) const {
684 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700685 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800686 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000687 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700688 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800689 BundlePolicy bundle_policy;
690 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700691 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
692 int ice_candidate_pool_size;
693 bool disable_ipv6;
694 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700695 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100696 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200698 absl::optional<int> screencast_min_bitrate;
699 absl::optional<bool> combined_audio_video_bwe;
700 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800701 TcpCandidatePolicy tcp_candidate_policy;
702 CandidateNetworkPolicy candidate_network_policy;
703 int audio_jitter_buffer_max_packets;
704 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100705 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800706 int ice_connection_receiving_timeout;
707 int ice_backup_candidate_pair_ping_interval;
708 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800709 bool prioritize_most_likely_ice_candidate_pairs;
710 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800711 bool prune_turn_ports;
712 bool presume_writable_when_fully_relayed;
713 bool enable_ice_renomination;
714 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200715 absl::optional<int> ice_check_interval_strong_connectivity;
716 absl::optional<int> ice_check_interval_weak_connectivity;
717 absl::optional<int> ice_check_min_interval;
718 absl::optional<int> ice_unwritable_timeout;
719 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800720 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200721 absl::optional<int> stun_candidate_keepalive_interval;
722 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200723 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800724 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200725 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700726 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700727 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700728 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700729 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100730 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800731 };
732 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
733 "Did you add something to RTCConfiguration and forget to "
734 "update operator==?");
735 return type == o.type && servers == o.servers &&
736 bundle_policy == o.bundle_policy &&
737 rtcp_mux_policy == o.rtcp_mux_policy &&
738 tcp_candidate_policy == o.tcp_candidate_policy &&
739 candidate_network_policy == o.candidate_network_policy &&
740 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
741 audio_jitter_buffer_fast_accelerate ==
742 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100743 audio_jitter_buffer_min_delay_ms ==
744 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800745 ice_connection_receiving_timeout ==
746 o.ice_connection_receiving_timeout &&
747 ice_backup_candidate_pair_ping_interval ==
748 o.ice_backup_candidate_pair_ping_interval &&
749 continual_gathering_policy == o.continual_gathering_policy &&
750 certificates == o.certificates &&
751 prioritize_most_likely_ice_candidate_pairs ==
752 o.prioritize_most_likely_ice_candidate_pairs &&
753 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800754 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700755 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100756 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800757 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800758 screencast_min_bitrate == o.screencast_min_bitrate &&
759 combined_audio_video_bwe == o.combined_audio_video_bwe &&
760 enable_dtls_srtp == o.enable_dtls_srtp &&
761 ice_candidate_pool_size == o.ice_candidate_pool_size &&
762 prune_turn_ports == o.prune_turn_ports &&
763 presume_writable_when_fully_relayed ==
764 o.presume_writable_when_fully_relayed &&
765 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800766 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800767 ice_check_interval_strong_connectivity ==
768 o.ice_check_interval_strong_connectivity &&
769 ice_check_interval_weak_connectivity ==
770 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700771 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700772 ice_unwritable_timeout == o.ice_unwritable_timeout &&
773 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800774 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800775 stun_candidate_keepalive_interval ==
776 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200777 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800778 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800779 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700780 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700781 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700782 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700783 use_media_transport_for_data_channels ==
784 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100785 crypto_options == o.crypto_options &&
786 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800787}
788
789bool PeerConnectionInterface::RTCConfiguration::operator!=(
790 const PeerConnectionInterface::RTCConfiguration& o) const {
791 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800792}
793
zhihuang8f65cdf2016-05-06 18:40:30 -0700794// Generate a RTCP CNAME when a PeerConnection is created.
795std::string GenerateRtcpCname() {
796 std::string cname;
797 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100798 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800799 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700800 }
801 return cname;
802}
803
zhihuang1c378ed2017-08-17 14:10:50 -0700804bool ValidateOfferAnswerOptions(
805 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
806 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
807 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700808}
809
zhihuang1c378ed2017-08-17 14:10:50 -0700810// From |rtc_options|, fill parts of |session_options| shared by all generated
811// m= sections (in other words, nothing that involves a map/array).
812void ExtractSharedMediaSessionOptions(
813 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
814 cricket::MediaSessionOptions* session_options) {
815 session_options->vad_enabled = rtc_options.voice_activity_detection;
816 session_options->bundle_enabled = rtc_options.use_rtp_mux;
817}
zhihuanga77e6bb2017-08-14 18:17:48 -0700818
zhihuang38ede132017-06-15 12:52:32 -0700819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 11:20:13 -0800833 // Need to stop transceivers before destroying the stats collector because
834 // AudioRtpSender has a reference to the StatsCollector it will update when
835 // stopping.
836 for (auto transceiver : transceivers_) {
837 transceiver->Stop();
838 }
Steve Anton4171afb2017-11-20 10:20:22 -0800839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Don't destroy BaseChannels until after stats has been cleaned up so that
847 // the last stats request can still read from the channels.
848 DestroyAllChannels();
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800855 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800856 transport_controller_.reset();
857
deadbeef91dd5672016-05-18 16:55:30 -0700858 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700859 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700860 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700861 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700862 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700863 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800864 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700865 event_log_.reset();
866 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867}
868
Steve Anton8af21862017-12-15 11:20:13 -0800869void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800870 // Destroy video channels first since they may have a pointer to a voice
871 // channel.
872 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800873 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800874 DestroyTransceiverChannel(transceiver);
875 }
876 }
877 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800878 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800879 DestroyTransceiverChannel(transceiver);
880 }
881 }
882 DestroyDataChannel();
883}
884
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000885bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000886 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700887 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100888 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700889
890 RTCError config_error = ValidateConfiguration(configuration);
891 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100892 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700893 return false;
894 }
895
Benjamin Wrightcab58882018-05-02 15:12:47 -0700896 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_ERROR)
898 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100899 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800900 return false;
901 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200902
Benjamin Wrightcab58882018-05-02 15:12:47 -0700903 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800904 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100905 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100906 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800907 return false;
908 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700909
Benjamin Wrightcab58882018-05-02 15:12:47 -0700910 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700911 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700912 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700913 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800914
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200915 cricket::ServerAddresses stun_servers;
916 std::vector<cricket::RelayServerConfig> turn_servers;
917
918 RTCErrorType parse_error =
919 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
920 if (parse_error != RTCErrorType::NONE) {
921 return false;
922 }
923
deadbeef91dd5672016-05-18 16:55:30 -0700924 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700925 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700926 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200927 RTC_FROM_HERE,
928 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
929 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 return false;
931 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200932 // If initialization was successful, note if STUN or TURN servers
933 // were supplied.
934 if (!stun_servers.empty()) {
935 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
936 }
937 if (!turn_servers.empty()) {
938 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
939 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700941 // Send information about IPv4/IPv6 status.
942 PeerConnectionAddressFamilyCounter address_family;
943 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
944 address_family = kPeerConnection_IPv6;
945 } else {
946 address_family = kPeerConnection_IPv4;
947 }
948 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
949 kPeerConnectionAddressFamilyCounter_Max);
950
Zhi Huange830e682018-03-30 10:48:35 -0700951 const PeerConnectionFactoryInterface::Options& options = factory_->options();
952
Steve Anton75737c02017-11-06 10:37:17 -0800953 // RFC 3264: The numeric value of the session id and version in the
954 // o line MUST be representable with a "64 bit signed integer".
955 // Due to this constraint session id |session_id_| is max limited to
956 // LLONG_MAX.
957 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700958 JsepTransportController::Config config;
959 config.redetermine_role_on_ice_restart =
960 configuration.redetermine_role_on_ice_restart;
961 config.ssl_max_version = factory_->options().ssl_max_version;
962 config.disable_encryption = options.disable_encryption;
963 config.bundle_policy = configuration.bundle_policy;
964 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700965 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
966 // stub.
967 config.crypto_options = configuration.crypto_options.has_value()
968 ? *configuration.crypto_options
969 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700970 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700971 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700972#if defined(ENABLE_EXTERNAL_AUTH)
973 config.enable_external_auth = true;
974#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700975 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700976
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700977 if (configuration.use_media_transport ||
978 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700979 if (!factory_->media_transport_factory()) {
980 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700981 << "PeerConnecton is initialized with use_media_transport = true or "
982 << "use_media_transport_for_data_channels = true "
983 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700984 return false;
985 }
986
987 config.media_transport_factory = factory_->media_transport_factory();
988 }
989
Zhi Huange830e682018-03-30 10:48:35 -0700990 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700991 signaling_thread(), network_thread(), port_allocator_.get(),
992 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700993 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000994 this, &PeerConnection::OnTransportControllerConnectionState);
995 transport_controller_->SignalStandardizedIceConnectionState.connect(
996 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200997 transport_controller_->SignalConnectionState.connect(
998 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700999 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001000 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001001 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001002 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001003 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001004 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1005 transport_controller_->SignalDtlsHandshakeError.connect(
1006 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1007
1008 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001009
deadbeefab9b2d12015-10-14 11:33:11 -07001010 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001011 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012
Steve Antonba818672017-11-06 10:21:57 -08001013 configuration_ = configuration;
1014
Steve Anton75737c02017-11-06 10:37:17 -08001015 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1016 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1017 if (!configuration.certificates.empty()) {
1018 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1019 // just picking the first one. The decision should be made based on the DTLS
1020 // handshake. The DTLS negotiations need to know about all certificates.
1021 certificate = configuration.certificates[0];
1022 }
1023
Steve Antond25da372017-11-06 14:50:29 -08001024 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001025
1026 if (options.disable_encryption) {
1027 dtls_enabled_ = false;
1028 } else {
1029 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001030 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001031 // |configuration| can override the default |dtls_enabled_| value.
1032 if (configuration.enable_dtls_srtp) {
1033 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1034 }
1035 }
1036
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001037 if (configuration.use_media_transport_for_data_channels) {
1038 if (configuration.enable_rtp_data_channel) {
1039 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1040 "use_media_transport_for_data_channels are "
1041 "incompatible and cannot both be set to true";
1042 return false;
1043 }
1044 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1045 } else if (configuration.enable_rtp_data_channel) {
1046 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1047 // set. It takes precendence over the disable_sctp_data_channels
1048 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001049 data_channel_type_ = cricket::DCT_RTP;
1050 } else {
1051 // DTLS has to be enabled to use SCTP.
1052 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1053 data_channel_type_ = cricket::DCT_SCTP;
1054 }
1055 }
1056
1057 video_options_.screencast_min_bitrate_kbps =
1058 configuration.screencast_min_bitrate;
1059 audio_options_.combined_audio_video_bwe =
1060 configuration.combined_audio_video_bwe;
1061
1062 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001063 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001064
1065 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001066 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001067
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001068 audio_options_.audio_jitter_buffer_min_delay_ms =
1069 configuration.audio_jitter_buffer_min_delay_ms;
1070
Steve Anton75737c02017-11-06 10:37:17 -08001071 // Whether the certificate generator/certificate is null or not determines
1072 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1073 // the right instructions by clearing the variables if needed.
1074 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001075 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001076 certificate = nullptr;
1077 } else if (certificate) {
1078 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001079 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001080 }
1081
1082 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1083 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001084 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001085 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1086 this, &PeerConnection::OnCertificateReady);
1087
1088 if (options.disable_encryption) {
1089 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1090 }
1091
1092 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001093 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001094 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095
Steve Anton4171afb2017-11-20 10:20:22 -08001096 // Add default audio/video transceivers for Plan B SDP.
1097 if (!IsUnifiedPlan()) {
1098 transceivers_.push_back(
1099 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1100 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1101 transceivers_.push_back(
1102 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1103 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1104 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001105 int delay_ms =
1106 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001107 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1108 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 return true;
1110}
1111
Steve Anton038834f2017-07-14 15:59:59 -07001112RTCError PeerConnection::ValidateConfiguration(
1113 const RTCConfiguration& config) const {
1114 if (config.ice_regather_interval_range &&
1115 config.continual_gathering_policy == GATHER_ONCE) {
1116 return RTCError(RTCErrorType::INVALID_PARAMETER,
1117 "ice_regather_interval_range specified but continual "
1118 "gathering policy is GATHER_ONCE");
1119 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001120 auto result =
1121 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1122 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001123}
1124
Yves Gerey665174f2018-06-19 15:03:05 +02001125rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001126 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1127 "Plan SdpSemantics. Please use GetSenders "
1128 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001129 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130}
1131
Yves Gerey665174f2018-06-19 15:03:05 +02001132rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001133 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1134 "Plan SdpSemantics. Please use GetReceivers "
1135 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001136 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137}
1138
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001139bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001140 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1141 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001142 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001143 if (IsClosed()) {
1144 return false;
1145 }
deadbeefab9b2d12015-10-14 11:33:11 -07001146 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001147 return false;
1148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149
1150 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001151 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1152 observer->SignalAudioTrackAdded.connect(this,
1153 &PeerConnection::OnAudioTrackAdded);
1154 observer->SignalAudioTrackRemoved.connect(
1155 this, &PeerConnection::OnAudioTrackRemoved);
1156 observer->SignalVideoTrackAdded.connect(this,
1157 &PeerConnection::OnVideoTrackAdded);
1158 observer->SignalVideoTrackRemoved.connect(
1159 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001160 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001161
deadbeefab9b2d12015-10-14 11:33:11 -07001162 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001163 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001164 }
1165 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001166 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001167 }
1168
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001169 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001170 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001171 return true;
1172}
1173
1174void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001175 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1176 "Plan SdpSemantics. Please use RemoveTrack "
1177 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001178 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001179 if (!IsClosed()) {
1180 for (const auto& track : local_stream->GetAudioTracks()) {
1181 RemoveAudioTrack(track.get(), local_stream);
1182 }
1183 for (const auto& track : local_stream->GetVideoTracks()) {
1184 RemoveVideoTrack(track.get(), local_stream);
1185 }
deadbeefab9b2d12015-10-14 11:33:11 -07001186 }
deadbeefab9b2d12015-10-14 11:33:11 -07001187 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001188 stream_observers_.erase(
1189 std::remove_if(
1190 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001191 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001192 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001193 }),
1194 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001195
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196 if (IsClosed()) {
1197 return;
1198 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001199 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200}
1201
Steve Anton2d6c76a2018-01-05 17:10:52 -08001202RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001204 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001205 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001206 if (!track) {
1207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1208 }
1209 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1210 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1212 "Track has invalid kind: " + track->kind());
1213 }
Steve Antonf9381f02017-12-14 10:23:57 -08001214 if (IsClosed()) {
1215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1216 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001217 }
Steve Anton4171afb2017-11-20 10:20:22 -08001218 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001219 LOG_AND_RETURN_ERROR(
1220 RTCErrorType::INVALID_PARAMETER,
1221 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001222 }
Steve Antonf9381f02017-12-14 10:23:57 -08001223 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001224 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1225 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001226 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001227 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001228 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001229 }
1230 return sender_or_error;
1231}
deadbeefe1f9d832016-01-14 15:35:42 -08001232
Steve Antonf9381f02017-12-14 10:23:57 -08001233RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1234PeerConnection::AddTrackPlanB(
1235 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001236 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001237 if (stream_ids.size() > 1u) {
1238 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1239 "AddTrack with more than one stream is not "
1240 "supported with Plan B semantics.");
1241 }
1242 std::vector<std::string> adjusted_stream_ids = stream_ids;
1243 if (adjusted_stream_ids.empty()) {
1244 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1245 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001246 cricket::MediaType media_type =
1247 (track->kind() == MediaStreamTrackInterface::kAudioKind
1248 ? cricket::MEDIA_TYPE_AUDIO
1249 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001250 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001251 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001252 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001253 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001254 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001255 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001256 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001257 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001258 if (sender_info) {
1259 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001260 }
Steve Antonf9381f02017-12-14 10:23:57 -08001261 } else {
1262 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001263 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001264 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001265 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001266 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001267 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001268 if (sender_info) {
1269 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001270 }
deadbeefe1f9d832016-01-14 15:35:42 -08001271 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001272 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001273}
deadbeefe1f9d832016-01-14 15:35:42 -08001274
Steve Antonf9381f02017-12-14 10:23:57 -08001275RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1276PeerConnection::AddTrackUnifiedPlan(
1277 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001278 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001279 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1280 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001281 RTC_LOG(LS_INFO) << "Reusing an existing "
1282 << cricket::MediaTypeToString(transceiver->media_type())
1283 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001284 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001285 transceiver->internal()->set_direction(
1286 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001287 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001288 transceiver->internal()->set_direction(
1289 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001290 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001291 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001292 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 } else {
1294 cricket::MediaType media_type =
1295 (track->kind() == MediaStreamTrackInterface::kAudioKind
1296 ? cricket::MEDIA_TYPE_AUDIO
1297 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001298 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1299 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001300 std::string sender_id = track->id();
1301 // Avoid creating a sender with an existing ID by generating a random ID.
1302 // This can happen if this is the second time AddTrack has created a sender
1303 // for this track.
1304 if (FindSenderById(sender_id)) {
1305 sender_id = rtc::CreateRandomUuid();
1306 }
Florent Castelli892acf02018-10-01 22:47:20 +02001307 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001308 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1309 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001311 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001312 }
Steve Antonf9381f02017-12-14 10:23:57 -08001313 return transceiver->sender();
1314}
1315
1316rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1317PeerConnection::FindFirstTransceiverForAddedTrack(
1318 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1319 RTC_DCHECK(track);
1320 for (auto transceiver : transceivers_) {
1321 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001322 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001323 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001324 !transceiver->internal()->has_ever_been_used_to_send() &&
1325 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001326 return transceiver;
1327 }
1328 }
1329 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001330}
1331
1332bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1333 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001334 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001335}
1336
Steve Anton24db5732018-07-23 10:27:33 -07001337RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001338 rtc::scoped_refptr<RtpSenderInterface> sender) {
1339 if (!sender) {
1340 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1341 }
deadbeefe1f9d832016-01-14 15:35:42 -08001342 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1344 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001345 }
Steve Antonf9381f02017-12-14 10:23:57 -08001346 if (IsUnifiedPlan()) {
1347 auto transceiver = FindTransceiverBySender(sender);
1348 if (!transceiver || !sender->track()) {
1349 return RTCError::OK();
1350 }
1351 sender->SetTrack(nullptr);
1352 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001353 transceiver->internal()->set_direction(
1354 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001355 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001356 transceiver->internal()->set_direction(
1357 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001358 }
Steve Anton4171afb2017-11-20 10:20:22 -08001359 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001360 bool removed;
1361 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1362 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1363 } else {
1364 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1365 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1366 }
1367 if (!removed) {
1368 LOG_AND_RETURN_ERROR(
1369 RTCErrorType::INVALID_PARAMETER,
1370 "Couldn't find sender " + sender->id() + " to remove.");
1371 }
Steve Anton4171afb2017-11-20 10:20:22 -08001372 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001373 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001374 return RTCError::OK();
1375}
1376
1377rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1378PeerConnection::FindTransceiverBySender(
1379 rtc::scoped_refptr<RtpSenderInterface> sender) {
1380 for (auto transceiver : transceivers_) {
1381 if (transceiver->sender() == sender) {
1382 return transceiver;
1383 }
1384 }
1385 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001386}
1387
Steve Anton9158ef62017-11-27 13:01:52 -08001388RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1389PeerConnection::AddTransceiver(
1390 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1391 return AddTransceiver(track, RtpTransceiverInit());
1392}
1393
1394RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1395PeerConnection::AddTransceiver(
1396 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1397 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001398 RTC_CHECK(IsUnifiedPlan())
1399 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001400 if (!track) {
1401 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1402 }
1403 cricket::MediaType media_type;
1404 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1405 media_type = cricket::MEDIA_TYPE_AUDIO;
1406 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1407 media_type = cricket::MEDIA_TYPE_VIDEO;
1408 } else {
1409 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1410 "Track kind is not audio or video");
1411 }
1412 return AddTransceiver(media_type, track, init);
1413}
1414
1415RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1416PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1417 return AddTransceiver(media_type, RtpTransceiverInit());
1418}
1419
1420RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1421PeerConnection::AddTransceiver(cricket::MediaType media_type,
1422 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001423 RTC_CHECK(IsUnifiedPlan())
1424 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001425 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1426 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1427 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1428 "media type is not audio or video");
1429 }
1430 return AddTransceiver(media_type, nullptr, init);
1431}
1432
1433RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1434PeerConnection::AddTransceiver(
1435 cricket::MediaType media_type,
1436 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001437 const RtpTransceiverInit& init,
1438 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001439 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1440 media_type == cricket::MEDIA_TYPE_VIDEO));
1441 if (track) {
1442 RTC_DCHECK_EQ(media_type,
1443 (track->kind() == MediaStreamTrackInterface::kAudioKind
1444 ? cricket::MEDIA_TYPE_AUDIO
1445 : cricket::MEDIA_TYPE_VIDEO));
1446 }
1447
1448 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001449 if (init.send_encodings.size() > 1) {
1450 LOG_AND_RETURN_ERROR(
1451 RTCErrorType::UNSUPPORTED_PARAMETER,
1452 "Attempted to create an encoder with more than 1 encoding parameter.");
1453 }
1454
1455 for (const auto& encoding : init.send_encodings) {
1456 if (encoding.ssrc.has_value()) {
1457 LOG_AND_RETURN_ERROR(
1458 RTCErrorType::UNSUPPORTED_PARAMETER,
1459 "Attempted to set an unimplemented parameter of RtpParameters.");
1460 }
1461 }
1462
1463 RtpParameters parameters;
1464 parameters.encodings = init.send_encodings;
1465 if (UnimplementedRtpParameterHasValue(parameters)) {
1466 LOG_AND_RETURN_ERROR(
1467 RTCErrorType::UNSUPPORTED_PARAMETER,
1468 "Attempted to set an unimplemented parameter of RtpParameters.");
1469 }
Steve Anton9158ef62017-11-27 13:01:52 -08001470
Steve Anton3d954a62018-04-02 11:27:23 -07001471 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1472 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001473 // Set the sender ID equal to the track ID if the track is specified unless
1474 // that sender ID is already in use.
1475 std::string sender_id =
1476 (track && !FindSenderById(track->id()) ? track->id()
1477 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001478 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1479 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001480 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1481 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1482 transceiver->internal()->set_direction(init.direction);
1483
Steve Anton22da89f2018-01-25 13:58:07 -08001484 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001485 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001486 }
Steve Antonf9381f02017-12-14 10:23:57 -08001487
1488 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1489}
1490
Steve Anton02ee47c2018-01-10 16:26:06 -08001491rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1492PeerConnection::CreateSender(
1493 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001494 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001496 const std::vector<std::string>& stream_ids,
1497 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001498 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001499 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1500 RTC_DCHECK(!track ||
1501 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1502 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1503 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001504 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001505 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001506 } else {
1507 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1508 RTC_DCHECK(!track ||
1509 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1510 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001511 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001512 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001513 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001514 bool set_track_succeeded = sender->SetTrack(track);
1515 RTC_DCHECK(set_track_succeeded);
1516 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001517 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001518 return sender;
1519}
1520
1521rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1522PeerConnection::CreateReceiver(cricket::MediaType media_type,
1523 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001524 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1525 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001526 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001527 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001528 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1529 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001530 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001531 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001532 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001533 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001534 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1535 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001536 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001537 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 return receiver;
1539}
1540
1541rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1542PeerConnection::CreateAndAddTransceiver(
1543 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1544 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1545 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001546 // Ensure that the new sender does not have an ID that is already in use by
1547 // another sender.
1548 // Allow receiver IDs to conflict since those come from remote SDP (which
1549 // could be invalid, but should not cause a crash).
1550 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001551 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1552 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001553 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001554 transceiver->internal()->SignalNegotiationNeeded.connect(
1555 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001556 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001557}
1558
Steve Anton52d86772018-02-20 15:48:12 -08001559void PeerConnection::OnNegotiationNeeded() {
1560 RTC_DCHECK_RUN_ON(signaling_thread());
1561 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001562 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001563}
1564
deadbeeffac06552015-11-25 11:26:01 -08001565rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001566 const std::string& kind,
1567 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001568 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1569 "Plan SdpSemantics. Please use AddTransceiver "
1570 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001571 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001572 if (IsClosed()) {
1573 return nullptr;
1574 }
Steve Anton4171afb2017-11-20 10:20:22 -08001575
Seth Hampson5b4f0752018-04-02 16:31:36 -07001576 // Internally we need to have one stream with Plan B semantics, so we
1577 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001578 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001579 if (stream_id.empty()) {
1580 stream_ids.push_back(rtc::CreateRandomUuid());
1581 RTC_LOG(LS_INFO)
1582 << "No stream_id specified for sender. Generated stream ID: "
1583 << stream_ids[0];
1584 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001585 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001586 }
1587
Steve Anton4171afb2017-11-20 10:20:22 -08001588 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001589 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001590 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001591 auto* audio_sender = new AudioRtpSender(
1592 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001593 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001594 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001595 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001596 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001597 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001598 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001599 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001600 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001601 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001602 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001603 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001604 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001605 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001606 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001607 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001608 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001609
deadbeefe1f9d832016-01-14 15:35:42 -08001610 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001611}
1612
deadbeef70ab1a12015-09-28 16:53:55 -07001613std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1614 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001615 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001616 for (auto sender : GetSendersInternal()) {
1617 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001618 }
1619 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001620}
1621
Steve Anton4171afb2017-11-20 10:20:22 -08001622std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1623PeerConnection::GetSendersInternal() const {
1624 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1625 all_senders;
1626 for (auto transceiver : transceivers_) {
1627 auto senders = transceiver->internal()->senders();
1628 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1629 }
1630 return all_senders;
1631}
1632
deadbeef70ab1a12015-09-28 16:53:55 -07001633std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1634PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001635 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001636 for (const auto& receiver : GetReceiversInternal()) {
1637 ret.push_back(receiver);
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<
1643 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1644PeerConnection::GetReceiversInternal() const {
1645 std::vector<
1646 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1647 all_receivers;
1648 for (auto transceiver : transceivers_) {
1649 auto receivers = transceiver->internal()->receivers();
1650 all_receivers.insert(all_receivers.end(), receivers.begin(),
1651 receivers.end());
1652 }
1653 return all_receivers;
1654}
1655
Steve Anton9158ef62017-11-27 13:01:52 -08001656std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1657PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001658 RTC_CHECK(IsUnifiedPlan())
1659 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001660 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1661 for (auto transceiver : transceivers_) {
1662 all_transceivers.push_back(transceiver);
1663 }
1664 return all_transceivers;
1665}
1666
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001667bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001668 MediaStreamTrackInterface* track,
1669 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001670 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001671 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001672 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001673 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674 return false;
1675 }
1676
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001677 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001678 // The StatsCollector is used to tell if a track is valid because it may
1679 // remember tracks that the PeerConnection previously removed.
1680 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001681 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1682 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001683 return false;
1684 }
Steve Antonad182762018-09-05 20:22:40 +00001685 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1686 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687 return true;
1688}
1689
hbos74e1a4f2016-09-15 23:33:01 -07001690void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001691 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001692 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001693 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001694 stats_collector_->GetStatsReport(callback);
1695}
1696
Henrik Boström1df1bf82018-03-20 13:24:20 +01001697void PeerConnection::GetStats(
1698 rtc::scoped_refptr<RtpSenderInterface> selector,
1699 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1700 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1701 RTC_DCHECK(callback);
1702 RTC_DCHECK(stats_collector_);
1703 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1704 if (selector) {
1705 for (const auto& proxy_transceiver : transceivers_) {
1706 for (const auto& proxy_sender :
1707 proxy_transceiver->internal()->senders()) {
1708 if (proxy_sender == selector) {
1709 internal_sender = proxy_sender->internal();
1710 break;
1711 }
1712 }
1713 if (internal_sender)
1714 break;
1715 }
1716 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001717 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001718 // belong to the PeerConnection (in Plan B, senders can be removed from the
1719 // PeerConnection). This means that "all the stats objects representing the
1720 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1721 // produces an empty stats report.
1722 stats_collector_->GetStatsReport(internal_sender, callback);
1723}
1724
1725void PeerConnection::GetStats(
1726 rtc::scoped_refptr<RtpReceiverInterface> selector,
1727 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1728 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1729 RTC_DCHECK(callback);
1730 RTC_DCHECK(stats_collector_);
1731 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1732 if (selector) {
1733 for (const auto& proxy_transceiver : transceivers_) {
1734 for (const auto& proxy_receiver :
1735 proxy_transceiver->internal()->receivers()) {
1736 if (proxy_receiver == selector) {
1737 internal_receiver = proxy_receiver->internal();
1738 break;
1739 }
1740 }
1741 if (internal_receiver)
1742 break;
1743 }
1744 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001745 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001746 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1747 // the PeerConnection). This means that "all the stats objects representing
1748 // the selector" is an empty set. Invoking GetStatsReport() with a null
1749 // selector produces an empty stats report.
1750 stats_collector_->GetStatsReport(internal_receiver, callback);
1751}
1752
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001753PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1754 return signaling_state_;
1755}
1756
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757PeerConnectionInterface::IceConnectionState
1758PeerConnection::ice_connection_state() {
1759 return ice_connection_state_;
1760}
1761
Alex Loiko9289eda2018-11-23 16:18:59 +00001762PeerConnectionInterface::IceConnectionState
1763PeerConnection::standardized_ice_connection_state() {
1764 return standardized_ice_connection_state_;
1765}
1766
Jonas Olsson635474e2018-10-18 15:58:17 +02001767PeerConnectionInterface::PeerConnectionState
1768PeerConnection::peer_connection_state() {
1769 return connection_state_;
1770}
1771
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772PeerConnectionInterface::IceGatheringState
1773PeerConnection::ice_gathering_state() {
1774 return ice_gathering_state_;
1775}
1776
Yves Gerey665174f2018-06-19 15:03:05 +02001777rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778 const std::string& label,
1779 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001780 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001781
deadbeefab9b2d12015-10-14 11:33:11 -07001782 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001783
kwibergd1fe2812016-04-27 06:47:29 -07001784 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001785 if (config) {
1786 internal_config.reset(new InternalDataChannelInit(*config));
1787 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001788 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001789 InternalCreateDataChannel(label, internal_config.get()));
1790 if (!channel.get()) {
1791 return nullptr;
1792 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001794 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1795 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001796 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001797 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001798 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001799 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 return DataChannelProxy::Create(signaling_thread(), channel.get());
1801}
1802
1803void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001804 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001805 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001806
nisse7ce109a2017-01-31 00:57:56 -08001807 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001809 return;
1810 }
deadbeefab9b2d12015-10-14 11:33:11 -07001811
Steve Anton8d3444d2017-10-20 15:30:51 -07001812 if (IsClosed()) {
1813 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001814 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001815 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001816 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001817 return;
1818 }
1819
zhihuang1c378ed2017-08-17 14:10:50 -07001820 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001821 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001822 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001823 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001824 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001825 return;
1826 }
1827
Steve Anton22da89f2018-01-25 13:58:07 -08001828 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1829 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1830 if (IsUnifiedPlan()) {
1831 RTCError error = HandleLegacyOfferOptions(options);
1832 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001833 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001834 return;
1835 }
1836 }
1837
zhihuang1c378ed2017-08-17 14:10:50 -07001838 cricket::MediaSessionOptions session_options;
1839 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001840 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841}
1842
Steve Anton22da89f2018-01-25 13:58:07 -08001843RTCError PeerConnection::HandleLegacyOfferOptions(
1844 const RTCOfferAnswerOptions& options) {
1845 RTC_DCHECK(IsUnifiedPlan());
1846
1847 if (options.offer_to_receive_audio == 0) {
1848 RemoveRecvDirectionFromReceivingTransceiversOfType(
1849 cricket::MEDIA_TYPE_AUDIO);
1850 } else if (options.offer_to_receive_audio == 1) {
1851 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1852 } else if (options.offer_to_receive_audio > 1) {
1853 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1854 "offer_to_receive_audio > 1 is not supported.");
1855 }
1856
1857 if (options.offer_to_receive_video == 0) {
1858 RemoveRecvDirectionFromReceivingTransceiversOfType(
1859 cricket::MEDIA_TYPE_VIDEO);
1860 } else if (options.offer_to_receive_video == 1) {
1861 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1862 } else if (options.offer_to_receive_video > 1) {
1863 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1864 "offer_to_receive_video > 1 is not supported.");
1865 }
1866
1867 return RTCError::OK();
1868}
1869
1870void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1871 cricket::MediaType media_type) {
1872 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001873 RtpTransceiverDirection new_direction =
1874 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1875 if (new_direction != transceiver->direction()) {
1876 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1877 << " transceiver (MID="
1878 << transceiver->mid().value_or("<not set>") << ") from "
1879 << RtpTransceiverDirectionToString(
1880 transceiver->direction())
1881 << " to "
1882 << RtpTransceiverDirectionToString(new_direction)
1883 << " since CreateOffer specified offer_to_receive=0";
1884 transceiver->internal()->set_direction(new_direction);
1885 }
Steve Anton22da89f2018-01-25 13:58:07 -08001886 }
1887}
1888
1889void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1890 cricket::MediaType media_type) {
1891 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001892 RTC_LOG(LS_INFO)
1893 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1894 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001895 RtpTransceiverInit init;
1896 init.direction = RtpTransceiverDirection::kRecvOnly;
1897 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1898 }
1899}
1900
1901std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1902PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1903 std::vector<
1904 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1905 receiving_transceivers;
1906 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001907 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001908 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1909 receiving_transceivers.push_back(transceiver);
1910 }
1911 }
1912 return receiving_transceivers;
1913}
1914
htaa2a49d92016-03-04 02:51:39 -08001915void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1916 const RTCOfferAnswerOptions& options) {
1917 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001918 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001919 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001920 return;
1921 }
1922
Steve Antondffead82018-02-06 10:31:29 -08001923 if (!(signaling_state_ == kHaveRemoteOffer ||
1924 signaling_state_ == kHaveLocalPrAnswer)) {
1925 std::string error =
1926 "PeerConnection cannot create an answer in a state other than "
1927 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001928 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001929 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001930 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001931 return;
1932 }
1933
Steve Antondffead82018-02-06 10:31:29 -08001934 // The remote description should be set if we're in the right state.
1935 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001936
Steve Anton22da89f2018-01-25 13:58:07 -08001937 if (IsUnifiedPlan()) {
1938 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1939 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1940 "supported with Unified Plan semantics. Use the "
1941 "RtpTransceiver API instead.";
1942 }
1943 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1944 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1945 "supported with Unified Plan semantics. Use the "
1946 "RtpTransceiver API instead.";
1947 }
1948 }
1949
htaa2a49d92016-03-04 02:51:39 -08001950 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001951 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001952
Steve Antond25da372017-11-06 14:50:29 -08001953 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954}
1955
1956void PeerConnection::SetLocalDescription(
1957 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001958 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001959 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001960
Steve Anton80dd7b52018-02-16 17:08:42 -08001961 // The SetLocalDescription contract is that we take ownership of the session
1962 // description regardless of the outcome, so wrap it in a unique_ptr right
1963 // away. Ideally, SetLocalDescription's signature will be changed to take the
1964 // description as a unique_ptr argument to formalize this agreement.
1965 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1966
nisse7ce109a2017-01-31 00:57:56 -08001967 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001968 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 return;
1970 }
Steve Anton8a006912017-12-04 15:25:56 -08001971
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001973 PostSetSessionDescriptionFailure(
1974 observer,
1975 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 return;
1977 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001978
Steve Anton80dd7b52018-02-16 17:08:42 -08001979 // If a session error has occurred the PeerConnection is in a possibly
1980 // inconsistent state so fail right away.
1981 if (session_error() != SessionError::kNone) {
1982 std::string error_message = GetSessionErrorMsg();
1983 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001984 PostSetSessionDescriptionFailure(
1985 observer,
1986 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001987 return;
1988 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001989
Steve Anton80dd7b52018-02-16 17:08:42 -08001990 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1991 if (!error.ok()) {
1992 std::string error_message = GetSetDescriptionErrorMessage(
1993 cricket::CS_LOCAL, desc->GetType(), error);
1994 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001995 PostSetSessionDescriptionFailure(
1996 observer,
1997 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001998 return;
1999 }
2000
2001 // Grab the description type before moving ownership to ApplyLocalDescription,
2002 // which may destroy it before returning.
2003 const SdpType type = desc->GetType();
2004
2005 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002006 // |desc| may be destroyed at this point.
2007
2008 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002009 // If ApplyLocalDescription fails, the PeerConnection could be in an
2010 // inconsistent state, so act conservatively here and set the session error
2011 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2012 SetSessionError(SessionError::kContent, error.message());
2013 std::string error_message =
2014 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2015 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002016 PostSetSessionDescriptionFailure(
2017 observer,
2018 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002019 return;
2020 }
Steve Anton8a006912017-12-04 15:25:56 -08002021 RTC_DCHECK(local_description());
2022
2023 PostSetSessionDescriptionSuccess(observer);
2024
Steve Antonad182762018-09-05 20:22:40 +00002025 // MaybeStartGathering needs to be called after posting
2026 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2027 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002028 transport_controller_->MaybeStartGathering();
2029
Steve Antona3a92c22017-12-07 10:27:41 -08002030 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002031 // TODO(deadbeef): We already had to hop to the network thread for
2032 // MaybeStartGathering...
2033 network_thread()->Invoke<void>(
2034 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2035 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002036 // Make UMA notes about what was agreed to.
2037 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002038 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002039 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002040}
2041
2042RTCError PeerConnection::ApplyLocalDescription(
2043 std::unique_ptr<SessionDescriptionInterface> desc) {
2044 RTC_DCHECK_RUN_ON(signaling_thread());
2045 RTC_DCHECK(desc);
2046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 // Update stats here so that we have the most recent stats for tracks and
2048 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002049 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002050
Steve Antondcc3c022017-12-22 16:02:54 -08002051 // Take a reference to the old local description since it's used below to
2052 // compare against the new local description. When setting the new local
2053 // description, grab ownership of the replaced session description in case it
2054 // is the same as |old_local_description|, to keep it alive for the duration
2055 // of the method.
2056 const SessionDescriptionInterface* old_local_description =
2057 local_description();
2058 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002059 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002060 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002061 replaced_local_description = pending_local_description_
2062 ? std::move(pending_local_description_)
2063 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002064 current_local_description_ = std::move(desc);
2065 pending_local_description_ = nullptr;
2066 current_remote_description_ = std::move(pending_remote_description_);
2067 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002068 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002069 pending_local_description_ = std::move(desc);
2070 }
2071 // The session description to apply now must be accessed by
2072 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002073 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002074
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002075 if (!is_caller_) {
2076 if (remote_description()) {
2077 // Remote description was applied first, so this PC is the callee.
2078 is_caller_ = false;
2079 } else {
2080 // Local description is applied first, so this PC is the caller.
2081 is_caller_ = true;
2082 }
2083 }
2084
Zhi Huange830e682018-03-30 10:48:35 -07002085 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2086 if (!error.ok()) {
2087 return error;
2088 }
2089
Steve Antondcc3c022017-12-22 16:02:54 -08002090 if (IsUnifiedPlan()) {
2091 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002092 cricket::CS_LOCAL, *local_description(), old_local_description,
2093 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002094 if (!error.ok()) {
2095 return error;
2096 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002097 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2098 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002099 for (auto transceiver : transceivers_) {
2100 const ContentInfo* content =
2101 FindMediaSectionForTransceiver(transceiver, local_description());
2102 if (!content) {
2103 continue;
2104 }
2105 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002106 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2107 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002108 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002109 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2110 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2111 // "recvonly", process the removal of a remote track for the media
2112 // description, given transceiver, removeList, and muteTracks.
2113 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2114 (transceiver->internal()->fired_direction() &&
2115 RtpTransceiverDirectionHasRecv(
2116 *transceiver->internal()->fired_direction()))) {
2117 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2118 &removed_streams);
2119 }
2120 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2121 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002122 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002123 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002124 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002125 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002126 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002127 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002128 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002129 }
2130 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002131 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002132 }
2133 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002134 // Media channels will be created only when offer is set. These may use new
2135 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002136 if (type == SdpType::kOffer) {
2137 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2138 // description is applied. Restore back to old description.
2139 RTCError error = CreateChannels(*local_description()->description());
2140 if (!error.ok()) {
2141 return error;
2142 }
2143 }
Steve Antondcc3c022017-12-22 16:02:54 -08002144 // Remove unused channels if MediaContentDescription is rejected.
2145 RemoveUnusedChannels(local_description()->description());
2146 }
Steve Anton8a006912017-12-04 15:25:56 -08002147
Zhi Huange830e682018-03-30 10:48:35 -07002148 error = UpdateSessionState(type, cricket::CS_LOCAL,
2149 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002150 if (!error.ok()) {
2151 return error;
2152 }
Steve Antondcc3c022017-12-22 16:02:54 -08002153
Steve Anton8a006912017-12-04 15:25:56 -08002154 if (remote_description()) {
2155 // Now that we have a local description, we can push down remote candidates.
2156 UseCandidatesInSessionDescription(remote_description());
2157 }
2158
2159 pending_ice_restarts_.clear();
2160 if (session_error() != SessionError::kNone) {
2161 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2162 }
2163
deadbeefab9b2d12015-10-14 11:33:11 -07002164 // If setting the description decided our SSL role, allocate any necessary
2165 // SCTP sids.
2166 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002167 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002168 AllocateSctpSids(role);
2169 }
2170
Steve Antond3679212018-01-17 17:41:02 -08002171 if (IsUnifiedPlan()) {
2172 for (auto transceiver : transceivers_) {
2173 const ContentInfo* content =
2174 FindMediaSectionForTransceiver(transceiver, local_description());
2175 if (!content) {
2176 continue;
2177 }
Steve Anton74255ff2018-01-24 18:32:57 -08002178 const auto& streams = content->media_description()->streams();
2179 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002180 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002181 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002182 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002183 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002184 } else {
2185 // 0 is a special value meaning "this sender has no associated send
2186 // stream". Need to call this so the sender won't attempt to configure
2187 // a no longer existing stream and run into DCHECKs in the lower
2188 // layers.
2189 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002190 }
2191 }
2192 } else {
2193 // Plan B semantics.
2194
Steve Antondcc3c022017-12-22 16:02:54 -08002195 // Update state and SSRC of local MediaStreams and DataChannels based on the
2196 // local session description.
2197 const cricket::ContentInfo* audio_content =
2198 GetFirstAudioContent(local_description()->description());
2199 if (audio_content) {
2200 if (audio_content->rejected) {
2201 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2202 } else {
2203 const cricket::AudioContentDescription* audio_desc =
2204 audio_content->media_description()->as_audio();
2205 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2206 }
deadbeeffaac4972015-11-12 15:33:07 -08002207 }
deadbeefab9b2d12015-10-14 11:33:11 -07002208
Steve Antondcc3c022017-12-22 16:02:54 -08002209 const cricket::ContentInfo* video_content =
2210 GetFirstVideoContent(local_description()->description());
2211 if (video_content) {
2212 if (video_content->rejected) {
2213 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2214 } else {
2215 const cricket::VideoContentDescription* video_desc =
2216 video_content->media_description()->as_video();
2217 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2218 }
deadbeeffaac4972015-11-12 15:33:07 -08002219 }
deadbeefab9b2d12015-10-14 11:33:11 -07002220 }
2221
2222 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002223 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002224 if (data_content) {
2225 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002226 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002227 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002228 cricket::kMediaProtocolRtpPrefix)) {
2229 UpdateLocalRtpDataChannels(data_desc->streams());
2230 }
2231 }
2232
Steve Anton8a006912017-12-04 15:25:56 -08002233 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234}
2235
2236void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002237 SetSessionDescriptionObserver* observer,
2238 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002239 SetRemoteDescription(
2240 std::unique_ptr<SessionDescriptionInterface>(desc),
2241 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2242 new SetRemoteDescriptionObserverAdapter(this, observer)));
2243}
2244
2245void PeerConnection::SetRemoteDescription(
2246 std::unique_ptr<SessionDescriptionInterface> desc,
2247 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002248 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002249
nisse7ce109a2017-01-31 00:57:56 -08002250 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002251 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 return;
2253 }
Steve Anton8a006912017-12-04 15:25:56 -08002254
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002256 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002257 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 return;
2259 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002260
Steve Anton80dd7b52018-02-16 17:08:42 -08002261 // If a session error has occurred the PeerConnection is in a possibly
2262 // inconsistent state so fail right away.
2263 if (session_error() != SessionError::kNone) {
2264 std::string error_message = GetSessionErrorMsg();
2265 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2266 observer->OnSetRemoteDescriptionComplete(
2267 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2268 return;
2269 }
Steve Anton71439a62018-02-15 11:53:06 -08002270
Steve Antonba42e992018-04-09 14:10:01 -07002271 if (desc->GetType() == SdpType::kOffer) {
2272 // Report to UMA the format of the received offer.
2273 ReportSdpFormatReceived(*desc);
2274 }
2275
Steve Anton80dd7b52018-02-16 17:08:42 -08002276 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002277 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002278 std::string error_message = GetSetDescriptionErrorMessage(
2279 cricket::CS_REMOTE, desc->GetType(), error);
2280 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002281 observer->OnSetRemoteDescriptionComplete(
2282 RTCError(error.type(), std::move(error_message)));
2283 return;
2284 }
Steve Anton71439a62018-02-15 11:53:06 -08002285
Steve Anton80dd7b52018-02-16 17:08:42 -08002286 // Grab the description type before moving ownership to
2287 // ApplyRemoteDescription, which may destroy it before returning.
2288 const SdpType type = desc->GetType();
2289
2290 error = ApplyRemoteDescription(std::move(desc));
2291 // |desc| may be destroyed at this point.
2292
2293 if (!error.ok()) {
2294 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2295 // inconsistent state, so act conservatively here and set the session error
2296 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2297 SetSessionError(SessionError::kContent, error.message());
2298 std::string error_message =
2299 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2300 RTC_LOG(LS_ERROR) << error_message;
2301 observer->OnSetRemoteDescriptionComplete(
2302 RTCError(error.type(), std::move(error_message)));
2303 return;
2304 }
2305 RTC_DCHECK(remote_description());
2306
2307 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002308 // TODO(deadbeef): We already had to hop to the network thread for
2309 // MaybeStartGathering...
2310 network_thread()->Invoke<void>(
2311 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2312 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002313 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002314 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002315 }
2316
2317 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002318 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002319}
2320
2321RTCError PeerConnection::ApplyRemoteDescription(
2322 std::unique_ptr<SessionDescriptionInterface> desc) {
2323 RTC_DCHECK_RUN_ON(signaling_thread());
2324 RTC_DCHECK(desc);
2325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 // Update stats here so that we have the most recent stats for tracks and
2327 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002328 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002329
Steve Antondcc3c022017-12-22 16:02:54 -08002330 // Take a reference to the old remote description since it's used below to
2331 // compare against the new remote description. When setting the new remote
2332 // description, grab ownership of the replaced session description in case it
2333 // is the same as |old_remote_description|, to keep it alive for the duration
2334 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002335 const SessionDescriptionInterface* old_remote_description =
2336 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002337 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002338 SdpType type = desc->GetType();
2339 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002340 replaced_remote_description = pending_remote_description_
2341 ? std::move(pending_remote_description_)
2342 : std::move(current_remote_description_);
2343 current_remote_description_ = std::move(desc);
2344 pending_remote_description_ = nullptr;
2345 current_local_description_ = std::move(pending_local_description_);
2346 } else {
2347 replaced_remote_description = std::move(pending_remote_description_);
2348 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349 }
Steve Anton8a006912017-12-04 15:25:56 -08002350 // The session description to apply now must be accessed by
2351 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002352 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353
Zhi Huange830e682018-03-30 10:48:35 -07002354 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2355 if (!error.ok()) {
2356 return error;
2357 }
Steve Anton8a006912017-12-04 15:25:56 -08002358 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002359 if (IsUnifiedPlan()) {
2360 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002361 cricket::CS_REMOTE, *remote_description(), local_description(),
2362 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002363 if (!error.ok()) {
2364 return error;
2365 }
Steve Antondcc3c022017-12-22 16:02:54 -08002366 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002367 // Media channels will be created only when offer is set. These may use new
2368 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002369 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002370 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002371 // description is applied. Restore back to old description.
2372 RTCError error = CreateChannels(*remote_description()->description());
2373 if (!error.ok()) {
2374 return error;
2375 }
2376 }
Steve Antondcc3c022017-12-22 16:02:54 -08002377 // Remove unused channels if MediaContentDescription is rejected.
2378 RemoveUnusedChannels(remote_description()->description());
2379 }
Steve Anton8a006912017-12-04 15:25:56 -08002380
Zhi Huange830e682018-03-30 10:48:35 -07002381 // NOTE: Candidates allocation will be initiated only when
2382 // SetLocalDescription is called.
2383 error = UpdateSessionState(type, cricket::CS_REMOTE,
2384 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002385 if (!error.ok()) {
2386 return error;
2387 }
2388
2389 if (local_description() &&
2390 !UseCandidatesInSessionDescription(remote_description())) {
2391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2392 }
2393
2394 if (old_remote_description) {
2395 for (const cricket::ContentInfo& content :
2396 old_remote_description->description()->contents()) {
2397 // Check if this new SessionDescription contains new ICE ufrag and
2398 // password that indicates the remote peer requests an ICE restart.
2399 // TODO(deadbeef): When we start storing both the current and pending
2400 // remote description, this should reset pending_ice_restarts and compare
2401 // against the current description.
2402 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2403 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002404 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002405 pending_ice_restarts_.insert(content.name);
2406 }
2407 } else {
2408 // We retain all received candidates only if ICE is not restarted.
2409 // When ICE is restarted, all previous candidates belong to an old
2410 // generation and should not be kept.
2411 // TODO(deadbeef): This goes against the W3C spec which says the remote
2412 // description should only contain candidates from the last set remote
2413 // description plus any candidates added since then. We should remove
2414 // this once we're sure it won't break anything.
2415 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2416 old_remote_description, content.name, mutable_remote_description());
2417 }
2418 }
2419 }
2420
2421 if (session_error() != SessionError::kNone) {
2422 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2423 }
2424
2425 // Set the the ICE connection state to connecting since the connection may
2426 // become writable with peer reflexive candidates before any remote candidate
2427 // is signaled.
2428 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2429 // is to have a new signal the indicates a change in checking state from the
2430 // transport and expose a new checking() member from transport that can be
2431 // read to determine the current checking state. The existing SignalConnecting
2432 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002433 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002434 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002435 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2436 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2437 }
2438
deadbeefab9b2d12015-10-14 11:33:11 -07002439 // If setting the description decided our SSL role, allocate any necessary
2440 // SCTP sids.
2441 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002442 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002443 AllocateSctpSids(role);
2444 }
2445
Steve Antondcc3c022017-12-22 16:02:54 -08002446 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002447 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002448 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002449 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002450 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002451 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002452 for (auto transceiver : transceivers_) {
2453 const ContentInfo* content =
2454 FindMediaSectionForTransceiver(transceiver, remote_description());
2455 if (!content) {
2456 continue;
2457 }
2458 const MediaContentDescription* media_desc = content->media_description();
2459 RtpTransceiverDirection local_direction =
2460 RtpTransceiverDirectionReversed(media_desc->direction());
2461 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2462 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2463 // transceiver's current direction is neither sendrecv nor recvonly,
2464 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002465 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002466 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002467 // The remote description has signaled the stream IDs.
2468 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002469 }
Steve Antondcc3c022017-12-22 16:02:54 -08002470 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002471 (!transceiver->fired_direction() ||
2472 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002473 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002474 << content->name << " (added to "
2475 << GetStreamIdsString(stream_ids) << ").";
2476
2477 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2478 for (const std::string& stream_id : stream_ids) {
2479 rtc::scoped_refptr<MediaStreamInterface> stream =
2480 remote_streams_->find(stream_id);
2481 if (!stream) {
2482 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2483 MediaStream::Create(stream_id));
2484 remote_streams_->AddStream(stream);
2485 added_streams.push_back(stream);
2486 }
2487 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002488 }
Henrik Boström5b147782018-12-04 11:25:05 +01002489 // Special case: "a=msid" missing, use random stream ID.
2490 if (media_streams.empty() &&
2491 !(remote_description()->description()->msid_signaling() &
2492 cricket::kMsidSignalingMediaSection)) {
2493 if (!missing_msid_default_stream_) {
2494 missing_msid_default_stream_ = MediaStreamProxy::Create(
2495 rtc::Thread::Current(),
2496 MediaStream::Create(rtc::CreateRandomUuid()));
2497 added_streams.push_back(missing_msid_default_stream_);
2498 }
2499 media_streams.push_back(missing_msid_default_stream_);
2500 }
Steve Anton3172c032018-05-03 15:30:18 -07002501 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002502 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2503 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002504 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002505 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002506 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002507 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2508 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2509 // removal of a remote track for the media description, given transceiver,
2510 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002511 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002512 (transceiver->fired_direction() &&
2513 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2514 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2515 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002516 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002517 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2518 transceiver->internal()->set_fired_direction(local_direction);
2519 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2520 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002521 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002522 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2523 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002524 transceiver->internal()->set_current_direction(local_direction);
2525 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002526 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2527 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002528 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002529 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2530 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002531 transceiver->Stop();
2532 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002533 if (!content->rejected &&
2534 RtpTransceiverDirectionHasRecv(local_direction)) {
2535 // Set ssrc to 0 in the case of an unsignalled ssrc.
2536 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002537 if (!media_desc->streams().empty() &&
2538 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002539 ssrc = media_desc->streams()[0].first_ssrc();
2540 }
2541 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002542 }
Steve Antondcc3c022017-12-22 16:02:54 -08002543 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002544 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002545 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002546 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002547 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002548 observer->OnTrack(transceiver);
2549 observer->OnAddTrack(transceiver->receiver(),
2550 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002551 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002552 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002553 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002554 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002555 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002556 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002557 }
2558 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002559 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002560 }
Steve Antondcc3c022017-12-22 16:02:54 -08002561 }
2562
Henrik Boströmfdb92012017-11-09 19:55:44 +01002563 const cricket::ContentInfo* audio_content =
2564 GetFirstAudioContent(remote_description()->description());
2565 const cricket::ContentInfo* video_content =
2566 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002567 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002568 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002569 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002570 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002571 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002572 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002573
2574 // Check if the descriptions include streams, just in case the peer supports
2575 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002576 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002577 (audio_desc && !audio_desc->streams().empty()) ||
2578 (video_desc && !video_desc->streams().empty())) {
2579 remote_peer_supports_msid_ = true;
2580 }
deadbeefab9b2d12015-10-14 11:33:11 -07002581
2582 // We wait to signal new streams until we finish processing the description,
2583 // since only at that point will new streams have all their tracks.
2584 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2585
Steve Antondcc3c022017-12-22 16:02:54 -08002586 if (!IsUnifiedPlan()) {
2587 // TODO(steveanton): When removing RTP senders/receivers in response to a
2588 // rejected media section, there is some cleanup logic that expects the
2589 // voice/ video channel to still be set. But in this method the voice/video
2590 // channel would have been destroyed by the SetRemoteDescription caller
2591 // above so the cleanup that relies on them fails to run. The RemoveSenders
2592 // calls should be moved to right before the DestroyChannel calls to fix
2593 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002594
Steve Antondcc3c022017-12-22 16:02:54 -08002595 // Find all audio rtp streams and create corresponding remote AudioTracks
2596 // and MediaStreams.
2597 if (audio_content) {
2598 if (audio_content->rejected) {
2599 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2600 } else {
2601 bool default_audio_track_needed =
2602 !remote_peer_supports_msid_ &&
2603 RtpTransceiverDirectionHasSend(audio_desc->direction());
2604 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2605 default_audio_track_needed, audio_desc->type(),
2606 new_streams);
2607 }
deadbeeffaac4972015-11-12 15:33:07 -08002608 }
deadbeefab9b2d12015-10-14 11:33:11 -07002609
Steve Antondcc3c022017-12-22 16:02:54 -08002610 // Find all video rtp streams and create corresponding remote VideoTracks
2611 // and MediaStreams.
2612 if (video_content) {
2613 if (video_content->rejected) {
2614 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2615 } else {
2616 bool default_video_track_needed =
2617 !remote_peer_supports_msid_ &&
2618 RtpTransceiverDirectionHasSend(video_desc->direction());
2619 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2620 default_video_track_needed, video_desc->type(),
2621 new_streams);
2622 }
deadbeeffaac4972015-11-12 15:33:07 -08002623 }
deadbeefab9b2d12015-10-14 11:33:11 -07002624
Steve Antondcc3c022017-12-22 16:02:54 -08002625 // Update the DataChannels with the information from the remote peer.
2626 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002627 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002628 cricket::kMediaProtocolRtpPrefix)) {
2629 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2630 }
deadbeefab9b2d12015-10-14 11:33:11 -07002631 }
deadbeefab9b2d12015-10-14 11:33:11 -07002632
Steve Antondcc3c022017-12-22 16:02:54 -08002633 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002634 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002635 for (size_t i = 0; i < new_streams->count(); ++i) {
2636 MediaStreamInterface* new_stream = new_streams->at(i);
2637 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002638 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002639 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2640 }
deadbeefab9b2d12015-10-14 11:33:11 -07002641
Steve Antondcc3c022017-12-22 16:02:54 -08002642 UpdateEndedRemoteMediaStreams();
2643 }
deadbeefab9b2d12015-10-14 11:33:11 -07002644
Steve Anton8a006912017-12-04 15:25:56 -08002645 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002646}
2647
Steve Anton0f5400a2018-07-17 14:25:36 -07002648void PeerConnection::ProcessRemovalOfRemoteTrack(
2649 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2650 transceiver,
2651 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2652 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2653 RTC_DCHECK(transceiver->mid());
2654 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2655 << *transceiver->mid();
2656 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2657 transceiver->internal()->receiver_internal()->streams();
2658 // This will remove the remote track from the streams.
2659 transceiver->internal()->receiver_internal()->set_stream_ids({});
2660 remove_list->push_back(transceiver);
2661 // Remove any streams that no longer have tracks.
2662 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2663 // of streams, see if the stream was removed by checking if this was the
2664 // last receiver with that stream ID.
2665 for (auto stream : media_streams) {
2666 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2667 remote_streams_->RemoveStream(stream);
2668 removed_streams->push_back(stream);
2669 }
2670 }
2671}
2672
Steve Antondcc3c022017-12-22 16:02:54 -08002673RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2674 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002675 const SessionDescriptionInterface& new_session,
2676 const SessionDescriptionInterface* old_local_description,
2677 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002678 RTC_DCHECK(IsUnifiedPlan());
2679
Steve Anton7464fca2018-01-19 11:10:37 -08002680 const cricket::ContentGroup* bundle_group = nullptr;
2681 if (new_session.GetType() == SdpType::kOffer) {
2682 auto bundle_group_or_error =
2683 GetEarlyBundleGroup(*new_session.description());
2684 if (!bundle_group_or_error.ok()) {
2685 return bundle_group_or_error.MoveError();
2686 }
2687 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002688 }
Steve Antondcc3c022017-12-22 16:02:54 -08002689
Steve Antondcc3c022017-12-22 16:02:54 -08002690 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002691 for (size_t i = 0; i < new_contents.size(); ++i) {
2692 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002693 cricket::MediaType media_type = new_content.media_description()->type();
2694 seen_mids_.insert(new_content.name);
2695 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2696 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002697 const cricket::ContentInfo* old_local_content = nullptr;
2698 if (old_local_description &&
2699 i < old_local_description->description()->contents().size()) {
2700 old_local_content =
2701 &old_local_description->description()->contents()[i];
2702 }
2703 const cricket::ContentInfo* old_remote_content = nullptr;
2704 if (old_remote_description &&
2705 i < old_remote_description->description()->contents().size()) {
2706 old_remote_content =
2707 &old_remote_description->description()->contents()[i];
2708 }
Steve Antondcc3c022017-12-22 16:02:54 -08002709 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002710 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2711 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002712 if (!transceiver_or_error.ok()) {
2713 return transceiver_or_error.MoveError();
2714 }
2715 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002716 RTCError error =
2717 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2718 if (!error.ok()) {
2719 return error;
2720 }
2721 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002722 if (GetDataMid() && new_content.name != *GetDataMid()) {
2723 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002724 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2725 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002726 continue;
2727 }
2728 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2729 if (!error.ok()) {
2730 return error;
2731 }
Steve Antondcc3c022017-12-22 16:02:54 -08002732 } else {
2733 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2734 "Unknown section type.");
2735 }
2736 }
2737
2738 return RTCError::OK();
2739}
2740
2741RTCError PeerConnection::UpdateTransceiverChannel(
2742 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2743 transceiver,
2744 const cricket::ContentInfo& content,
2745 const cricket::ContentGroup* bundle_group) {
2746 RTC_DCHECK(IsUnifiedPlan());
2747 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002748 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002749 if (content.rejected) {
2750 if (channel) {
2751 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002752 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002753 }
2754 } else {
2755 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002756 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002757 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002758 } else {
Steve Anton69470252018-02-09 11:43:08 -08002759 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002760 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002761 }
2762 if (!channel) {
2763 LOG_AND_RETURN_ERROR(
2764 RTCErrorType::INTERNAL_ERROR,
2765 "Failed to create channel for mid=" + content.name);
2766 }
2767 transceiver->internal()->SetChannel(channel);
2768 }
2769 }
2770 return RTCError::OK();
2771}
2772
Steve Antonfa2260d2017-12-28 16:38:23 -08002773RTCError PeerConnection::UpdateDataChannel(
2774 cricket::ContentSource source,
2775 const cricket::ContentInfo& content,
2776 const cricket::ContentGroup* bundle_group) {
2777 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002778 // If data channels are disabled, ignore this media section. CreateAnswer
2779 // will take care of rejecting it.
2780 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002781 }
2782 if (content.rejected) {
2783 DestroyDataChannel();
2784 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002785 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002786 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002787 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2788 "Failed to create data channel.");
2789 }
2790 }
2791 if (source == cricket::CS_REMOTE) {
2792 const MediaContentDescription* data_desc = content.media_description();
2793 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2794 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2795 }
2796 }
2797 }
2798 return RTCError::OK();
2799}
2800
Steve Antondcc3c022017-12-22 16:02:54 -08002801RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2802PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002803 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002804 size_t mline_index,
2805 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002806 const ContentInfo* old_local_content,
2807 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002808 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002809 // If this is an offer then the m= section might be recycled. If the m=
2810 // section is being recycled (defined as: rejected in the current local or
2811 // remote description and not rejected in new description), dissociate the
2812 // currently associated RtpTransceiver by setting its mid property to null,
2813 // and discard the mapping between the transceiver and its m= section index.
2814 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2815 old_remote_content)) {
2816 // We want to dissociate the transceiver that has the rejected mid.
2817 const std::string& old_mid =
2818 (old_local_content && old_local_content->rejected)
2819 ? old_local_content->name
2820 : old_remote_content->name;
2821 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002822 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002823 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2824 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002825 old_transceiver->internal()->set_mid(absl::nullopt);
2826 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002827 }
2828 }
2829 const MediaContentDescription* media_desc = content.media_description();
2830 auto transceiver = GetAssociatedTransceiver(content.name);
2831 if (source == cricket::CS_LOCAL) {
2832 // Find the RtpTransceiver that corresponds to this m= section, using the
2833 // mapping between transceivers and m= section indices established when
2834 // creating the offer.
2835 if (!transceiver) {
2836 transceiver = GetTransceiverByMLineIndex(mline_index);
2837 }
2838 if (!transceiver) {
2839 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2840 "Unknown transceiver");
2841 }
2842 } else {
2843 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2844 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2845 // of the same type...
2846 if (!transceiver &&
2847 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2848 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2849 }
2850 // If no RtpTransceiver was found in the previous step, create one with a
2851 // recvonly direction.
2852 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002853 RTC_LOG(LS_INFO) << "Adding "
2854 << cricket::MediaTypeToString(media_desc->type())
2855 << " transceiver for MID=" << content.name
2856 << " at i=" << mline_index
2857 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002858 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002859 auto sender =
2860 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002861 std::string receiver_id;
2862 if (!media_desc->streams().empty()) {
2863 receiver_id = media_desc->streams()[0].id;
2864 } else {
2865 receiver_id = rtc::CreateRandomUuid();
2866 }
2867 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002868 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002869 transceiver->internal()->set_direction(
2870 RtpTransceiverDirection::kRecvOnly);
2871 }
2872 }
2873 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002874 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002875 LOG_AND_RETURN_ERROR(
2876 RTCErrorType::INVALID_PARAMETER,
2877 "Transceiver type does not match media description type.");
2878 }
2879 // Associate the found or created RtpTransceiver with the m= section by
2880 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2881 // section, and establish a mapping between the transceiver and the index of
2882 // the m= section.
2883 transceiver->internal()->set_mid(content.name);
2884 transceiver->internal()->set_mline_index(mline_index);
2885 return std::move(transceiver);
2886}
2887
2888rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2889PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2890 RTC_DCHECK(IsUnifiedPlan());
2891 for (auto transceiver : transceivers_) {
2892 if (transceiver->mid() == mid) {
2893 return transceiver;
2894 }
2895 }
2896 return nullptr;
2897}
2898
2899rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2900PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2901 RTC_DCHECK(IsUnifiedPlan());
2902 for (auto transceiver : transceivers_) {
2903 if (transceiver->internal()->mline_index() == mline_index) {
2904 return transceiver;
2905 }
2906 }
2907 return nullptr;
2908}
2909
2910rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2911PeerConnection::FindAvailableTransceiverToReceive(
2912 cricket::MediaType media_type) const {
2913 RTC_DCHECK(IsUnifiedPlan());
2914 // From JSEP section 5.10 (Applying a Remote Description):
2915 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2916 // the same type that were added to the PeerConnection by addTrack and are not
2917 // associated with any m= section and are not stopped, find the first such
2918 // RtpTransceiver.
2919 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002920 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002921 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2922 !transceiver->stopped()) {
2923 return transceiver;
2924 }
2925 }
2926 return nullptr;
2927}
2928
Steve Antoned10bd92017-12-05 10:52:59 -08002929const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2930 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2931 transceiver,
2932 const SessionDescriptionInterface* sdesc) const {
2933 RTC_DCHECK(transceiver);
2934 RTC_DCHECK(sdesc);
2935 if (IsUnifiedPlan()) {
2936 if (!transceiver->internal()->mid()) {
2937 // This transceiver is not associated with a media section yet.
2938 return nullptr;
2939 }
2940 return sdesc->description()->GetContentByName(
2941 *transceiver->internal()->mid());
2942 } else {
2943 // Plan B only allows at most one audio and one video section, so use the
2944 // first media section of that type.
2945 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002946 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002947 }
2948}
2949
deadbeef46c73892016-11-16 19:42:04 -08002950PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2951 return configuration_;
2952}
2953
deadbeef293e9262017-01-11 12:28:30 -08002954bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2955 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002956 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002957 if (IsClosed()) {
2958 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2959 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2960 }
2961
Qingsi Wanga2d60672018-04-11 16:57:45 -07002962 // According to JSEP, after setLocalDescription, changing the candidate pool
2963 // size is not allowed, and changing the set of ICE servers will not result
2964 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002965 if (local_description() && configuration.ice_candidate_pool_size !=
2966 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002967 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2968 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002969 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002970 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002971
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002972 if (local_description() &&
2973 configuration.use_media_transport != configuration_.use_media_transport) {
2974 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2975 "SetLocalDescription.";
2976 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2977 }
2978
2979 if (remote_description() &&
2980 configuration.use_media_transport != configuration_.use_media_transport) {
2981 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2982 "SetRemoteDescription.";
2983 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2984 }
2985
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002986 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002987 configuration.use_media_transport_for_data_channels !=
2988 configuration_.use_media_transport_for_data_channels) {
2989 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2990 "after calling SetLocalDescription.";
2991 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2992 }
2993
2994 if (remote_description() &&
2995 configuration.use_media_transport_for_data_channels !=
2996 configuration_.use_media_transport_for_data_channels) {
2997 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2998 "after calling SetRemoteDescription.";
2999 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3000 }
3001
3002 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003003 configuration.crypto_options != configuration_.crypto_options) {
3004 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3005 "SetLocalDescription.";
3006 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3007 }
3008
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003009 if (configuration.use_media_transport_for_data_channels ||
3010 configuration.use_media_transport) {
3011 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3012 << "Media transport requires MaxBundle policy.";
3013 }
3014
deadbeef293e9262017-01-11 12:28:30 -08003015 // The simplest (and most future-compatible) way to tell if the config was
3016 // modified in an invalid way is to copy each property we do support
3017 // modifying, then use operator==. There are far more properties we don't
3018 // support modifying than those we do, and more could be added.
3019 RTCConfiguration modified_config = configuration_;
3020 modified_config.servers = configuration.servers;
3021 modified_config.type = configuration.type;
3022 modified_config.ice_candidate_pool_size =
3023 configuration.ice_candidate_pool_size;
3024 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003025 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003026 modified_config.ice_check_interval_strong_connectivity =
3027 configuration.ice_check_interval_strong_connectivity;
3028 modified_config.ice_check_interval_weak_connectivity =
3029 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003030 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3031 modified_config.ice_unwritable_min_checks =
3032 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003033 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003034 modified_config.stun_candidate_keepalive_interval =
3035 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003036 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003037 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003038 modified_config.active_reset_srtp_params =
3039 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003040 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003041 modified_config.use_media_transport_for_data_channels =
3042 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003043 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003044 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003045 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3046 }
3047
Steve Anton038834f2017-07-14 15:59:59 -07003048 // Validate the modified configuration.
3049 RTCError validate_error = ValidateConfiguration(modified_config);
3050 if (!validate_error.ok()) {
3051 return SafeSetError(std::move(validate_error), error);
3052 }
3053
deadbeef293e9262017-01-11 12:28:30 -08003054 // Note that this isn't possible through chromium, since it's an unsigned
3055 // short in WebIDL.
3056 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003057 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003058 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3059 }
3060
3061 // Parse ICE servers before hopping to network thread.
3062 cricket::ServerAddresses stun_servers;
3063 std::vector<cricket::RelayServerConfig> turn_servers;
3064 RTCErrorType parse_error =
3065 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3066 if (parse_error != RTCErrorType::NONE) {
3067 return SafeSetError(parse_error, error);
3068 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003069 // Note if STUN or TURN servers were supplied.
3070 if (!stun_servers.empty()) {
3071 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3072 }
3073 if (!turn_servers.empty()) {
3074 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3075 }
deadbeef293e9262017-01-11 12:28:30 -08003076
3077 // In theory this shouldn't fail.
3078 if (!network_thread()->Invoke<bool>(
3079 RTC_FROM_HERE,
3080 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3081 stun_servers, turn_servers, modified_config.type,
3082 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003083 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003084 modified_config.turn_customizer,
3085 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003086 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003087 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3088 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003089
deadbeefd1a38b52016-12-10 13:15:33 -08003090 // As described in JSEP, calling setConfiguration with new ICE servers or
3091 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3092 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003093 if (modified_config.servers != configuration_.servers ||
3094 modified_config.type != configuration_.type ||
3095 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003096 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003097 }
skvladd1f5fda2017-02-03 16:54:05 -08003098
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003099 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003100 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003101 modified_config.use_media_transport ||
3102 modified_config.use_media_transport_for_data_channels
3103 ? factory_->media_transport_factory()
3104 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003105
Zhi Huangb57e1692018-06-12 11:41:11 -07003106 if (configuration_.active_reset_srtp_params !=
3107 modified_config.active_reset_srtp_params) {
3108 transport_controller_->SetActiveResetSrtpParams(
3109 modified_config.active_reset_srtp_params);
3110 }
3111
deadbeef293e9262017-01-11 12:28:30 -08003112 configuration_ = modified_config;
3113 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003114}
3115
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116bool PeerConnection::AddIceCandidate(
3117 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003118 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003119 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003120 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003121 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003122 return false;
3123 }
Steve Antond25da372017-11-06 14:50:29 -08003124
3125 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003126 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003127 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003128 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003129 return false;
3130 }
3131
3132 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003133 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003134 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003135 return false;
3136 }
3137
3138 bool valid = false;
3139 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3140 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003141 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003142 return false;
3143 }
3144
3145 // Add this candidate to the remote session description.
3146 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003147 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003148 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003149 return false;
3150 }
3151
3152 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003153 bool result = UseCandidate(ice_candidate);
3154 if (result) {
3155 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3156 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3157 } else {
3158 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3159 }
3160 return result;
Steve Antond25da372017-11-06 14:50:29 -08003161 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003162 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003163 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003164 return true;
3165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166}
3167
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003168bool PeerConnection::RemoveIceCandidates(
3169 const std::vector<cricket::Candidate>& candidates) {
3170 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003171 if (IsClosed()) {
3172 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3173 return false;
3174 }
3175
Steve Antond25da372017-11-06 14:50:29 -08003176 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003177 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3178 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003179 return false;
3180 }
3181
3182 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003183 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003184 return false;
3185 }
3186
3187 size_t number_removed =
3188 mutable_remote_description()->RemoveCandidates(candidates);
3189 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003190 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003191 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003192 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003193 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003194 }
3195
3196 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003197 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3198 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003199 RTC_LOG(LS_ERROR)
3200 << "RemoveIceCandidates: Error when removing remote candidates: "
3201 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003202 }
3203 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003204}
3205
Niels Möller0c4f7be2018-05-07 14:01:37 +02003206RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003207 if (!worker_thread()->IsCurrent()) {
3208 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003209 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003210 }
3211
Niels Möller0c4f7be2018-05-07 14:01:37 +02003212 const bool has_min = bitrate.min_bitrate_bps.has_value();
3213 const bool has_start = bitrate.start_bitrate_bps.has_value();
3214 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003215 if (has_min && *bitrate.min_bitrate_bps < 0) {
3216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3217 "min_bitrate_bps <= 0");
3218 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003219 if (has_start) {
3220 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003221 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003222 "start_bitrate_bps < min_bitrate_bps");
3223 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3225 "curent_bitrate_bps < 0");
3226 }
3227 }
3228 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003229 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003230 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003231 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003232 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3234 "max_bitrate_bps < min_bitrate_bps");
3235 } else if (*bitrate.max_bitrate_bps < 0) {
3236 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3237 "max_bitrate_bps < 0");
3238 }
3239 }
3240
zstein4b979802017-06-02 14:37:37 -07003241 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003242 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003243
3244 return RTCError::OK();
3245}
3246
Alex Narest78609d52017-10-20 10:37:47 +02003247void PeerConnection::SetBitrateAllocationStrategy(
3248 std::unique_ptr<rtc::BitrateAllocationStrategy>
3249 bitrate_allocation_strategy) {
3250 rtc::Thread* worker_thread = factory_->worker_thread();
3251 if (!worker_thread->IsCurrent()) {
3252 rtc::BitrateAllocationStrategy* strategy_raw =
3253 bitrate_allocation_strategy.release();
3254 auto functor = [this, strategy_raw]() {
3255 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003256 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003257 };
3258 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3259 return;
3260 }
3261 RTC_DCHECK(call_.get());
3262 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3263}
3264
henrika5f6bf242017-11-01 11:06:56 +01003265void PeerConnection::SetAudioPlayout(bool playout) {
3266 if (!worker_thread()->IsCurrent()) {
3267 worker_thread()->Invoke<void>(
3268 RTC_FROM_HERE,
3269 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3270 return;
3271 }
3272 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003273 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003274 audio_state->SetPlayout(playout);
3275}
3276
3277void PeerConnection::SetAudioRecording(bool recording) {
3278 if (!worker_thread()->IsCurrent()) {
3279 worker_thread()->Invoke<void>(
3280 RTC_FROM_HERE,
3281 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3282 return;
3283 }
3284 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003285 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003286 audio_state->SetRecording(recording);
3287}
3288
Steve Anton8c0f7a72017-10-03 10:03:10 -07003289std::unique_ptr<rtc::SSLCertificate>
3290PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003291 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3292 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003293 return nullptr;
3294 }
Steve Antonf25303e2018-10-16 15:23:31 -07003295 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003296}
3297
Zhi Huang70b820f2018-01-27 14:16:15 -08003298std::unique_ptr<rtc::SSLCertChain>
3299PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003300 auto audio_transceiver = GetFirstAudioTransceiver();
3301 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003302 return nullptr;
3303 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003304 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003305 audio_transceiver->internal()->channel()->transport_name());
3306}
3307
3308rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3309PeerConnection::GetFirstAudioTransceiver() const {
3310 for (auto transceiver : transceivers_) {
3311 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3312 return transceiver;
3313 }
3314 }
3315 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003316}
3317
ivoc14d5dbe2016-07-04 07:06:55 -07003318bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3319 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003320 // TODO(eladalon): It would be better to not allow negative values into PC.
3321 const size_t max_size = (max_size_bytes < 0)
3322 ? RtcEventLog::kUnlimitedOutput
3323 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003324 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3325 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3326 output_period_ms = 5000;
3327 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003328 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003329 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003330 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003331}
3332
Bjorn Tereliusde939432017-11-20 17:38:14 +01003333bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3334 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003335 // TODO(eladalon): In C++14, this can be done with a lambda.
3336 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003337 bool operator()() {
3338 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3339 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003340 PeerConnection* const pc;
3341 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003342 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003343 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003344 return worker_thread()->Invoke<bool>(
3345 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003346}
3347
3348void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003349 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003350 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3351}
3352
Harald Alvestrandad88c882018-11-28 16:47:46 +01003353rtc::scoped_refptr<DtlsTransportInterface>
3354PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3355 return transport_controller_->LookupDtlsTransportByMid(mid);
3356}
3357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003359 return pending_local_description_ ? pending_local_description_.get()
3360 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361}
3362
3363const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003364 return pending_remote_description_ ? pending_remote_description_.get()
3365 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003366}
3367
deadbeeffe4a8a42016-12-20 17:56:17 -08003368const SessionDescriptionInterface* PeerConnection::current_local_description()
3369 const {
Steve Anton75737c02017-11-06 10:37:17 -08003370 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003371}
3372
3373const SessionDescriptionInterface* PeerConnection::current_remote_description()
3374 const {
Steve Anton75737c02017-11-06 10:37:17 -08003375 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003376}
3377
3378const SessionDescriptionInterface* PeerConnection::pending_local_description()
3379 const {
Steve Anton75737c02017-11-06 10:37:17 -08003380 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003381}
3382
3383const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3384 const {
Steve Anton75737c02017-11-06 10:37:17 -08003385 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003386}
3387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003389 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 // Update stats here so that we have the most recent stats for tracks and
3391 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003392 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393
Steve Anton75737c02017-11-06 10:37:17 -08003394 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003395 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003396
Steve Anton8af21862017-12-15 11:20:13 -08003397 for (auto transceiver : transceivers_) {
3398 transceiver->Stop();
3399 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003400
3401 // Ensure that all asynchronous stats requests are completed before destroying
3402 // the transport controller below.
3403 if (stats_collector_) {
3404 stats_collector_->WaitForPendingRequest();
3405 }
3406
3407 // Don't destroy BaseChannels until after stats has been cleaned up so that
3408 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003409 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003410
Qingsi Wang93a84392018-01-30 17:13:09 -08003411 // The event log is used in the transport controller, which must be outlived
3412 // by the former. CreateOffer by the peer connection is implemented
3413 // asynchronously and if the peer connection is closed without resetting the
3414 // WebRTC session description factory, the session description factory would
3415 // call the transport controller.
3416 webrtc_session_desc_factory_.reset();
3417 transport_controller_.reset();
3418
deadbeef42a42632017-03-10 15:18:00 -08003419 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003420 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3421 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003422
Steve Anton978b8762017-09-29 12:15:02 -07003423 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003424 call_.reset();
3425 // The event log must outlive call (and any other object that uses it).
3426 event_log_.reset();
3427 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003428 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003429 // The .h file says that observer can be discarded after close() returns.
3430 // Make sure this is true.
3431 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432}
3433
Steve Antonad182762018-09-05 20:22:40 +00003434void PeerConnection::OnMessage(rtc::Message* msg) {
3435 switch (msg->message_id) {
3436 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3437 SetSessionDescriptionMsg* param =
3438 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3439 param->observer->OnSuccess();
3440 delete param;
3441 break;
3442 }
3443 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3444 SetSessionDescriptionMsg* param =
3445 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3446 param->observer->OnFailure(std::move(param->error));
3447 delete param;
3448 break;
3449 }
3450 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3451 CreateSessionDescriptionMsg* param =
3452 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3453 param->observer->OnFailure(std::move(param->error));
3454 delete param;
3455 break;
3456 }
3457 case MSG_GETSTATS: {
3458 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3459 StatsReports reports;
3460 stats_->GetStats(param->track, &reports);
3461 param->observer->OnComplete(reports);
3462 delete param;
3463 break;
3464 }
3465 case MSG_FREE_DATACHANNELS: {
3466 sctp_data_channels_to_free_.clear();
3467 break;
3468 }
3469 case MSG_REPORT_USAGE_PATTERN: {
3470 ReportUsagePattern();
3471 break;
3472 }
3473 default:
3474 RTC_NOTREACHED() << "Not implemented";
3475 break;
3476 }
3477}
3478
Steve Antonafb0bb72018-02-20 11:35:37 -08003479cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3480 RTC_DCHECK(!IsUnifiedPlan());
3481 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3482 GetAudioTransceiver()->internal()->channel());
3483 if (voice_channel) {
3484 return voice_channel->media_channel();
3485 } else {
3486 return nullptr;
3487 }
3488}
3489
3490cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3491 RTC_DCHECK(!IsUnifiedPlan());
3492 auto* video_channel = static_cast<cricket::VideoChannel*>(
3493 GetVideoTransceiver()->internal()->channel());
3494 if (video_channel) {
3495 return video_channel->media_channel();
3496 } else {
3497 return nullptr;
3498 }
3499}
3500
Steve Anton4171afb2017-11-20 10:20:22 -08003501void PeerConnection::CreateAudioReceiver(
3502 MediaStreamInterface* stream,
3503 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003504 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3505 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003506 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3507 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003508 auto* audio_receiver = new AudioRtpReceiver(
3509 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003510 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003511 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3512 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3513 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003514 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003515 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003516 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517}
3518
Steve Anton4171afb2017-11-20 10:20:22 -08003519void PeerConnection::CreateVideoReceiver(
3520 MediaStreamInterface* stream,
3521 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003522 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3523 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003524 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3525 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003526 auto* video_receiver = new VideoRtpReceiver(
3527 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003528 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003529 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3530 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3531 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003532 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003533 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003534 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003535}
3536
deadbeef70ab1a12015-09-28 16:53:55 -07003537// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3538// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003539rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003540 const RtpSenderInfo& remote_sender_info) {
3541 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3542 if (!receiver) {
3543 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3544 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003545 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003546 }
Steve Anton4171afb2017-11-20 10:20:22 -08003547 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3548 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3549 } else {
3550 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3551 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003552 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003553}
3554
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003555void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3556 MediaStreamInterface* stream) {
3557 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003558 RTC_DCHECK(track);
3559 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003560 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003561 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003562 // We already have a sender for this track, so just change the stream_id
3563 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003564 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003565 return;
3566 }
3567
3568 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003569 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003570 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003571 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003572 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003573 // If the sender has already been configured in SDP, we call SetSsrc,
3574 // which will connect the sender to the underlying transport. This can
3575 // occur if a local session description that contains the ID of the sender
3576 // is set before AddStream is called. It can also occur if the local
3577 // session description is not changed and RemoveStream is called, and
3578 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003579 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003580 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003581 if (sender_info) {
3582 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003583 }
3584}
3585
3586// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3587// indefinitely, when we have unified plan SDP.
3588void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3589 MediaStreamInterface* stream) {
3590 RTC_DCHECK(!IsClosed());
3591 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003592 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003593 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3594 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003595 return;
3596 }
Steve Anton4171afb2017-11-20 10:20:22 -08003597 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003598}
3599
3600void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3601 MediaStreamInterface* stream) {
3602 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003603 RTC_DCHECK(track);
3604 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003605 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003606 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003607 // We already have a sender for this track, so just change the stream_id
3608 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003609 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003610 return;
3611 }
3612
3613 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003614 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003615 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003616 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003617 GetVideoTransceiver()->internal()->AddSender(new_sender);
3618 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003619 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003620 if (sender_info) {
3621 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003622 }
3623}
3624
3625void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3626 MediaStreamInterface* stream) {
3627 RTC_DCHECK(!IsClosed());
3628 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003629 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003630 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3631 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003632 return;
3633 }
Steve Anton4171afb2017-11-20 10:20:22 -08003634 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003635}
3636
Steve Antonba818672017-11-06 10:21:57 -08003637void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003638 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003639 if (ice_connection_state_ == new_state) {
3640 return;
3641 }
3642
deadbeefcbecd352015-09-23 11:50:27 -07003643 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003644 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003645 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003646 return;
3647 }
Steve Antonba818672017-11-06 10:21:57 -08003648
Mirko Bonadei675513b2017-11-09 11:09:25 +01003649 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3650 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003651 RTC_DCHECK(ice_connection_state_ !=
3652 PeerConnectionInterface::kIceConnectionClosed);
3653
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003654 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003655 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003656}
3657
Alex Loiko9289eda2018-11-23 16:18:59 +00003658void PeerConnection::SetStandardizedIceConnectionState(
3659 PeerConnectionInterface::IceConnectionState new_state) {
3660 RTC_DCHECK(signaling_thread()->IsCurrent());
3661 if (standardized_ice_connection_state_ == new_state)
3662 return;
3663 if (IsClosed())
3664 return;
3665 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003666 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003667}
3668
Jonas Olsson635474e2018-10-18 15:58:17 +02003669void PeerConnection::SetConnectionState(
3670 PeerConnectionInterface::PeerConnectionState new_state) {
3671 RTC_DCHECK(signaling_thread()->IsCurrent());
3672 if (connection_state_ == new_state)
3673 return;
3674 if (IsClosed())
3675 return;
3676 connection_state_ = new_state;
3677 Observer()->OnConnectionChange(new_state);
3678}
3679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003680void PeerConnection::OnIceGatheringChange(
3681 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003682 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003683 if (IsClosed()) {
3684 return;
3685 }
3686 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003687 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003688}
3689
jbauch81bf7b02017-03-25 08:31:12 -07003690void PeerConnection::OnIceCandidate(
3691 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003692 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003693 if (IsClosed()) {
3694 return;
3695 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003696 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003697 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3698 candidate->candidate().address().IsPrivateIP()) {
3699 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3700 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003701 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003702}
3703
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003704void PeerConnection::OnIceCandidatesRemoved(
3705 const std::vector<cricket::Candidate>& candidates) {
3706 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003707 if (IsClosed()) {
3708 return;
3709 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003710 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003711}
3712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003713void PeerConnection::ChangeSignalingState(
3714 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003715 RTC_DCHECK(signaling_thread()->IsCurrent());
3716 if (signaling_state_ == signaling_state) {
3717 return;
3718 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003719 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3720 << GetSignalingStateString(signaling_state_)
3721 << " New state: "
3722 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003723 signaling_state_ = signaling_state;
3724 if (signaling_state == kClosed) {
3725 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003726 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003727 standardized_ice_connection_state_ =
3728 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003729 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3730 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003731 if (ice_gathering_state_ != kIceGatheringComplete) {
3732 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003733 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003734 }
3735 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003736 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003737}
3738
deadbeefeb459812015-12-15 19:24:43 -08003739void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3740 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003741 if (IsClosed()) {
3742 return;
3743 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003744 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003745 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003746}
3747
deadbeefeb459812015-12-15 19:24:43 -08003748void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3749 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003750 if (IsClosed()) {
3751 return;
3752 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003753 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003754 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003755}
3756
3757void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3758 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003759 if (IsClosed()) {
3760 return;
3761 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003762 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003763 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003764}
3765
3766void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3767 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003768 if (IsClosed()) {
3769 return;
3770 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003771 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003772 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003773}
3774
Henrik Boström31638672017-11-23 17:48:32 +01003775void PeerConnection::PostSetSessionDescriptionSuccess(
3776 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003777 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3778 signaling_thread()->Post(RTC_FROM_HERE, this,
3779 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003780}
3781
deadbeefab9b2d12015-10-14 11:33:11 -07003782void PeerConnection::PostSetSessionDescriptionFailure(
3783 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003784 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003785 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003786 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3787 msg->error = std::move(error);
3788 signaling_thread()->Post(RTC_FROM_HERE, this,
3789 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003790}
3791
3792void PeerConnection::PostCreateSessionDescriptionFailure(
3793 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003794 RTCError error) {
3795 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003796 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3797 msg->error = std::move(error);
3798 signaling_thread()->Post(RTC_FROM_HERE, this,
3799 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003800}
3801
zhihuang1c378ed2017-08-17 14:10:50 -07003802void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003803 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003804 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003805 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003806
Steve Antondcc3c022017-12-22 16:02:54 -08003807 if (IsUnifiedPlan()) {
3808 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3809 } else {
3810 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3811 }
3812
Steve Antonfa2260d2017-12-28 16:38:23 -08003813 // Intentionally unset the data channel type for RTP data channel with the
3814 // second condition. Otherwise the RTP data channels would be successfully
3815 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3816 // when building with chromium. We want to leave RTP data channels broken, so
3817 // people won't try to use them.
3818 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3819 session_options->data_channel_type = data_channel_type();
3820 }
3821
Steve Antondcc3c022017-12-22 16:02:54 -08003822 // Apply ICE restart flag and renomination flag.
3823 for (auto& options : session_options->media_description_options) {
3824 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3825 options.transport_options.enable_ice_renomination =
3826 configuration_.enable_ice_renomination;
3827 }
3828
3829 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003830 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003831 session_options->pooled_ice_credentials =
3832 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3833 RTC_FROM_HERE,
3834 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3835 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003836 session_options->offer_extmap_allow_mixed =
3837 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003838}
3839
3840void PeerConnection::GetOptionsForPlanBOffer(
3841 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3842 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003843 // Figure out transceiver directional preferences.
3844 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3845 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3846
3847 // By default, generate sendrecv/recvonly m= sections.
3848 bool recv_audio = true;
3849 bool recv_video = true;
3850
3851 // By default, only offer a new m= section if we have media to send with it.
3852 bool offer_new_audio_description = send_audio;
3853 bool offer_new_video_description = send_video;
3854 bool offer_new_data_description = HasDataChannels();
3855
3856 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003857 if (offer_answer_options.offer_to_receive_audio !=
3858 RTCOfferAnswerOptions::kUndefined) {
3859 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003860 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003861 offer_new_audio_description ||
3862 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003863 }
Steve Antondcc3c022017-12-22 16:02:54 -08003864 if (offer_answer_options.offer_to_receive_video !=
3865 RTCOfferAnswerOptions::kUndefined) {
3866 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003867 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003868 offer_new_video_description ||
3869 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003870 }
3871
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003872 absl::optional<size_t> audio_index;
3873 absl::optional<size_t> video_index;
3874 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003875 // If a current description exists, generate m= sections in the same order,
3876 // using the first audio/video/data section that appears and rejecting
3877 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003878 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003879 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003880 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003881 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3882 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3883 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003884 }
3885
zhihuang1c378ed2017-08-17 14:10:50 -07003886 // Add audio/video/data m= sections to the end if needed.
3887 if (!audio_index && offer_new_audio_description) {
3888 session_options->media_description_options.push_back(
3889 cricket::MediaDescriptionOptions(
3890 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003891 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3892 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003893 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003894 }
zhihuang1c378ed2017-08-17 14:10:50 -07003895 if (!video_index && offer_new_video_description) {
3896 session_options->media_description_options.push_back(
3897 cricket::MediaDescriptionOptions(
3898 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003899 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3900 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003901 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003902 }
zhihuang1c378ed2017-08-17 14:10:50 -07003903 if (!data_index && offer_new_data_description) {
3904 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003905 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003906 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003907 }
3908
3909 cricket::MediaDescriptionOptions* audio_media_description_options =
3910 !audio_index ? nullptr
3911 : &session_options->media_description_options[*audio_index];
3912 cricket::MediaDescriptionOptions* video_media_description_options =
3913 !video_index ? nullptr
3914 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003915
Steve Anton4171afb2017-11-20 10:20:22 -08003916 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003917 video_media_description_options,
3918 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003919}
3920
3921// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3922// and return a reference to it.
3923// Generated MIDs should be no more than 3 bytes long to take up less space in
3924// the RTP packet.
3925static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3926 RTC_DCHECK(used_mids);
3927 // We're boring: just generate MIDs 0, 1, 2, ...
3928 size_t i = 0;
3929 std::set<std::string>::iterator it;
3930 bool inserted;
3931 do {
3932 std::string mid = rtc::ToString(i++);
3933 auto insert_result = used_mids->insert(mid);
3934 it = insert_result.first;
3935 inserted = insert_result.second;
3936 } while (!inserted);
3937 return *it;
3938}
3939
3940static cricket::MediaDescriptionOptions
3941GetMediaDescriptionOptionsForTransceiver(
3942 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3943 transceiver,
3944 const std::string& mid) {
3945 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003946 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003947 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003948 // This behavior is specified in JSEP. The gist is that:
3949 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3950 // sendrecv.
3951 // 2. If the MSID is included, then it must be included in any subsequent
3952 // offer/answer exactly the same until the RtpTransceiver is stopped.
3953 if (!transceiver->stopped() &&
3954 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3955 transceiver->internal()->has_ever_been_used_to_send())) {
3956 cricket::SenderOptions sender_options;
3957 sender_options.track_id = transceiver->sender()->id();
3958 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003959 int num_send_encoding_layers =
3960 transceiver->sender()->init_send_encodings().size();
3961 sender_options.num_sim_layers =
3962 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003963 media_description_options.sender_options.push_back(sender_options);
3964 }
Steve Antondcc3c022017-12-22 16:02:54 -08003965 return media_description_options;
3966}
3967
Steve Anton5c72e712018-12-10 14:25:30 -08003968// Returns the ContentInfo at mline index |i|, or null if none exists.
3969static const ContentInfo* GetContentByIndex(
3970 const SessionDescriptionInterface* sdesc,
3971 size_t i) {
3972 if (!sdesc) {
3973 return nullptr;
3974 }
3975 const ContentInfos& contents = sdesc->description()->contents();
3976 return (i < contents.size() ? &contents[i] : nullptr);
3977}
3978
Steve Antondcc3c022017-12-22 16:02:54 -08003979void PeerConnection::GetOptionsForUnifiedPlanOffer(
3980 const RTCOfferAnswerOptions& offer_answer_options,
3981 cricket::MediaSessionOptions* session_options) {
3982 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3983 // Offers) and 5.2.2 (Subsequent Offers).
3984 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3985 const ContentInfos& local_contents =
3986 (local_description() ? local_description()->description()->contents()
3987 : ContentInfos());
3988 const ContentInfos& remote_contents =
3989 (remote_description() ? remote_description()->description()->contents()
3990 : ContentInfos());
3991 // The mline indices that can be recycled. New transceivers should reuse these
3992 // slots first.
3993 std::queue<size_t> recycleable_mline_indices;
3994 // Track the MIDs used in previous offer/answer exchanges and the current
3995 // offer so that new, unique MIDs are generated.
3996 std::set<std::string> used_mids = seen_mids_;
3997 // First, go through each media section that exists in either the local or
3998 // remote description and generate a media section in this offer for the
3999 // associated transceiver. If a media section can be recycled, generate a
4000 // default, rejected media section here that can be later overwritten.
4001 for (size_t i = 0;
4002 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4003 // Either |local_content| or |remote_content| is non-null.
4004 const ContentInfo* local_content =
4005 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004006 const ContentInfo* current_local_content =
4007 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004008 const ContentInfo* remote_content =
4009 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004010 const ContentInfo* current_remote_content =
4011 GetContentByIndex(current_remote_description(), i);
4012 bool had_been_rejected =
4013 (current_local_content && current_local_content->rejected) ||
4014 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004015 const std::string& mid =
4016 (local_content ? local_content->name : remote_content->name);
4017 cricket::MediaType media_type =
4018 (local_content ? local_content->media_description()->type()
4019 : remote_content->media_description()->type());
4020 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4021 media_type == cricket::MEDIA_TYPE_VIDEO) {
4022 auto transceiver = GetAssociatedTransceiver(mid);
4023 RTC_CHECK(transceiver);
4024 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004025 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004026 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004027 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004028 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4029 RtpTransceiverDirection::kInactive,
4030 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004031 recycleable_mline_indices.push(i);
4032 } else {
4033 session_options->media_description_options.push_back(
4034 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4035 // CreateOffer shouldn't really cause any state changes in
4036 // PeerConnection, but we need a way to match new transceivers to new
4037 // media sections in SetLocalDescription and JSEP specifies this is done
4038 // by recording the index of the media section generated for the
4039 // transceiver in the offer.
4040 transceiver->internal()->set_mline_index(i);
4041 }
4042 } else {
4043 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004044 RTC_CHECK(GetDataMid());
4045 if (had_been_rejected || mid != *GetDataMid()) {
4046 session_options->media_description_options.push_back(
4047 GetMediaDescriptionOptionsForRejectedData(mid));
4048 } else {
4049 session_options->media_description_options.push_back(
4050 GetMediaDescriptionOptionsForActiveData(mid));
4051 }
Steve Antondcc3c022017-12-22 16:02:54 -08004052 }
4053 }
4054 // Next, look for transceivers that are newly added (that is, are not stopped
4055 // and not associated). Reuse media sections marked as recyclable first,
4056 // otherwise append to the end of the offer. New media sections should be
4057 // added in the order they were added to the PeerConnection.
4058 for (auto transceiver : transceivers_) {
4059 if (transceiver->mid() || transceiver->stopped()) {
4060 continue;
4061 }
4062 size_t mline_index;
4063 if (!recycleable_mline_indices.empty()) {
4064 mline_index = recycleable_mline_indices.front();
4065 recycleable_mline_indices.pop();
4066 session_options->media_description_options[mline_index] =
4067 GetMediaDescriptionOptionsForTransceiver(transceiver,
4068 AllocateMid(&used_mids));
4069 } else {
4070 mline_index = session_options->media_description_options.size();
4071 session_options->media_description_options.push_back(
4072 GetMediaDescriptionOptionsForTransceiver(transceiver,
4073 AllocateMid(&used_mids)));
4074 }
4075 // See comment above for why CreateOffer changes the transceiver's state.
4076 transceiver->internal()->set_mline_index(mline_index);
4077 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004078 // Lastly, add a m-section if we have local data channels and an m section
4079 // does not already exist.
4080 if (!GetDataMid() && HasDataChannels()) {
4081 session_options->media_description_options.push_back(
4082 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4083 }
Steve Antondcc3c022017-12-22 16:02:54 -08004084}
4085
4086void PeerConnection::GetOptionsForAnswer(
4087 const RTCOfferAnswerOptions& offer_answer_options,
4088 cricket::MediaSessionOptions* session_options) {
4089 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4090
4091 if (IsUnifiedPlan()) {
4092 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4093 } else {
4094 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4095 }
4096
Steve Antonfa2260d2017-12-28 16:38:23 -08004097 // Intentionally unset the data channel type for RTP data channel. Otherwise
4098 // the RTP data channels would be successfully negotiated by default and the
4099 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4100 // We want to leave RTP data channels broken, so people won't try to use them.
4101 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4102 session_options->data_channel_type = data_channel_type();
4103 }
4104
Steve Antondcc3c022017-12-22 16:02:54 -08004105 // Apply ICE renomination flag.
4106 for (auto& options : session_options->media_description_options) {
4107 options.transport_options.enable_ice_renomination =
4108 configuration_.enable_ice_renomination;
4109 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004110
4111 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004112 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004113 session_options->pooled_ice_credentials =
4114 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4115 RTC_FROM_HERE,
4116 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4117 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004118}
4119
Steve Antondcc3c022017-12-22 16:02:54 -08004120void PeerConnection::GetOptionsForPlanBAnswer(
4121 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004122 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004123 // Figure out transceiver directional preferences.
4124 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4125 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4126
4127 // By default, generate sendrecv/recvonly m= sections. The direction is also
4128 // restricted by the direction in the offer.
4129 bool recv_audio = true;
4130 bool recv_video = true;
4131
4132 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004133 if (offer_answer_options.offer_to_receive_audio !=
4134 RTCOfferAnswerOptions::kUndefined) {
4135 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004136 }
Steve Antondcc3c022017-12-22 16:02:54 -08004137 if (offer_answer_options.offer_to_receive_video !=
4138 RTCOfferAnswerOptions::kUndefined) {
4139 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004140 }
4141
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004142 absl::optional<size_t> audio_index;
4143 absl::optional<size_t> video_index;
4144 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004145
4146 // Generate m= sections that match those in the offer.
4147 // Note that mediasession.cc will handle intersection our preferred
4148 // direction with the offered direction.
4149 GenerateMediaDescriptionOptions(
4150 remote_description(),
4151 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4152 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4153 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004154
4155 cricket::MediaDescriptionOptions* audio_media_description_options =
4156 !audio_index ? nullptr
4157 : &session_options->media_description_options[*audio_index];
4158 cricket::MediaDescriptionOptions* video_media_description_options =
4159 !video_index ? nullptr
4160 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004161
Steve Anton4171afb2017-11-20 10:20:22 -08004162 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004163 video_media_description_options,
4164 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004165}
zhihuangaf388472016-11-02 16:49:48 -07004166
Steve Antondcc3c022017-12-22 16:02:54 -08004167void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4168 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4169 cricket::MediaSessionOptions* session_options) {
4170 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4171 // Answers) and 5.3.2 (Subsequent Answers).
4172 RTC_DCHECK(remote_description());
4173 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4174 for (const ContentInfo& content :
4175 remote_description()->description()->contents()) {
4176 cricket::MediaType media_type = content.media_description()->type();
4177 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4178 media_type == cricket::MEDIA_TYPE_VIDEO) {
4179 auto transceiver = GetAssociatedTransceiver(content.name);
4180 RTC_CHECK(transceiver);
4181 session_options->media_description_options.push_back(
4182 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4183 } else {
4184 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004185 // Reject all data sections if data channels are disabled.
4186 // Reject a data section if it has already been rejected.
4187 // Reject all data sections except for the first one.
4188 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4189 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004190 session_options->media_description_options.push_back(
4191 GetMediaDescriptionOptionsForRejectedData(content.name));
4192 } else {
4193 session_options->media_description_options.push_back(
4194 GetMediaDescriptionOptionsForActiveData(content.name));
4195 }
Steve Antondcc3c022017-12-22 16:02:54 -08004196 }
4197 }
htaa2a49d92016-03-04 02:51:39 -08004198}
4199
zhihuang1c378ed2017-08-17 14:10:50 -07004200void PeerConnection::GenerateMediaDescriptionOptions(
4201 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004202 RtpTransceiverDirection audio_direction,
4203 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004204 absl::optional<size_t>* audio_index,
4205 absl::optional<size_t>* video_index,
4206 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004207 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004208 for (const cricket::ContentInfo& content :
4209 session_desc->description()->contents()) {
4210 if (IsAudioContent(&content)) {
4211 // If we already have an audio m= section, reject this extra one.
4212 if (*audio_index) {
4213 session_options->media_description_options.push_back(
4214 cricket::MediaDescriptionOptions(
4215 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004216 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004217 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004218 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004219 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004220 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4221 content.name, audio_direction,
4222 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004223 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004224 }
4225 } else if (IsVideoContent(&content)) {
4226 // If we already have an video m= section, reject this extra one.
4227 if (*video_index) {
4228 session_options->media_description_options.push_back(
4229 cricket::MediaDescriptionOptions(
4230 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004231 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004232 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004233 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004234 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004235 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4236 content.name, video_direction,
4237 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004238 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004239 }
4240 } else {
4241 RTC_DCHECK(IsDataContent(&content));
4242 // If we already have an data m= section, reject this extra one.
4243 if (*data_index) {
4244 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004245 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004246 } else {
4247 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004248 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004249 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004250 }
4251 }
htaa2a49d92016-03-04 02:51:39 -08004252 }
deadbeefab9b2d12015-10-14 11:33:11 -07004253}
4254
Steve Antonfa2260d2017-12-28 16:38:23 -08004255cricket::MediaDescriptionOptions
4256PeerConnection::GetMediaDescriptionOptionsForActiveData(
4257 const std::string& mid) const {
4258 // Direction for data sections is meaningless, but legacy endpoints might
4259 // expect sendrecv.
4260 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4261 RtpTransceiverDirection::kSendRecv,
4262 /*stopped=*/false);
4263 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4264 return options;
4265}
4266
4267cricket::MediaDescriptionOptions
4268PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4269 const std::string& mid) const {
4270 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4271 RtpTransceiverDirection::kInactive,
4272 /*stopped=*/true);
4273 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4274 return options;
4275}
4276
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004277absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004278 switch (data_channel_type_) {
4279 case cricket::DCT_RTP:
4280 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004281 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004282 }
4283 return rtp_data_channel_->content_name();
4284 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004285 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004286 case cricket::DCT_MEDIA_TRANSPORT:
4287 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004288 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004289 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004290 }
4291}
4292
Steve Anton4171afb2017-11-20 10:20:22 -08004293void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4294 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4295 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004296 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004297}
4298
Steve Anton4171afb2017-11-20 10:20:22 -08004299void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004300 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004301 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004302 cricket::MediaType media_type,
4303 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004304 RTC_DCHECK(!IsUnifiedPlan());
4305
Steve Anton4171afb2017-11-20 10:20:22 -08004306 std::vector<RtpSenderInfo>* current_senders =
4307 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004308
Steve Anton4171afb2017-11-20 10:20:22 -08004309 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004310 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004311 for (auto sender_it = current_senders->begin();
4312 sender_it != current_senders->end();
4313 /* incremented manually */) {
4314 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004315 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004316 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004317 std::string params_stream_id;
4318 if (params) {
4319 params_stream_id =
4320 (!params->first_stream_id().empty() ? params->first_stream_id()
4321 : kDefaultStreamId);
4322 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004323 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004324 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004325 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004326 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004327 sender_exists) {
4328 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004329 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004330 OnRemoteSenderRemoved(info, media_type);
4331 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004332 }
4333 }
4334
Steve Anton4171afb2017-11-20 10:20:22 -08004335 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004336 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004337 if (!params.has_ssrcs()) {
4338 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4339 // sender, this means it is coming from a Unified Plan endpoint,so we just
4340 // create a default.
4341 default_sender_needed = true;
4342 break;
4343 }
4344
Seth Hampson845e8782018-03-02 11:34:10 -08004345 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004346 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004347 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4348 // not supported in Plan B, we just take the first here and create the
4349 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004350 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004351 (!params.first_stream_id().empty() ? params.first_stream_id()
4352 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004353 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004354 uint32_t ssrc = params.first_ssrc();
4355
4356 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004357 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004358 if (!stream) {
4359 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004360 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004361 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004362 remote_streams_->AddStream(stream);
4363 new_streams->AddStream(stream);
4364 }
4365
Steve Anton4171afb2017-11-20 10:20:22 -08004366 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004367 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004368 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004369 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004370 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004371 }
4372 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004373
Steve Anton4171afb2017-11-20 10:20:22 -08004374 // Add default sender if necessary.
4375 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004376 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004377 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004378 if (!default_stream) {
4379 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004380 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004381 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004382 remote_streams_->AddStream(default_stream);
4383 new_streams->AddStream(default_stream);
4384 }
Steve Anton4171afb2017-11-20 10:20:22 -08004385 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4386 ? kDefaultAudioSenderId
4387 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004388 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004389 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004390 if (!default_sender_info) {
4391 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004392 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004393 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004394 }
4395 }
deadbeefab9b2d12015-10-14 11:33:11 -07004396}
4397
Steve Anton4171afb2017-11-20 10:20:22 -08004398void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4399 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004400 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4401 << " receiver for track_id=" << sender_info.sender_id
4402 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004403
Steve Anton3d954a62018-04-02 11:27:23 -07004404 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004405 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004406 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004407 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004408 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004409 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004410 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004411 }
4412}
4413
Steve Anton4171afb2017-11-20 10:20:22 -08004414void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4415 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004416 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4417 << " receiver for track_id=" << sender_info.sender_id
4418 << " and stream_id=" << sender_info.stream_id;
4419
Seth Hampson845e8782018-03-02 11:34:10 -08004420 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004421
Henrik Boström933d8b02017-10-10 10:05:16 -07004422 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004423 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004424 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4425 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004426 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004427 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004428 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004429 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004430 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004431 }
4432 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004433 // Stopping or destroying a VideoRtpReceiver will end the
4434 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004435 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004436 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004437 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004438 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004439 // There's no guarantee the track is still available, e.g. the track may
4440 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004441 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004442 }
4443 } else {
nisseede5da42017-01-12 05:15:36 -08004444 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004445 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004446 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004447 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004448 }
deadbeefab9b2d12015-10-14 11:33:11 -07004449}
4450
4451void PeerConnection::UpdateEndedRemoteMediaStreams() {
4452 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4453 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4454 MediaStreamInterface* stream = remote_streams_->at(i);
4455 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4456 streams_to_remove.push_back(stream);
4457 }
4458 }
4459
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004460 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004461 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004462 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004463 }
4464}
4465
Steve Anton4171afb2017-11-20 10:20:22 -08004466void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004467 const std::vector<cricket::StreamParams>& streams,
4468 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004469 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004470
Seth Hampson845e8782018-03-02 11:34:10 -08004471 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004472 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004473 for (auto sender_it = current_senders->begin();
4474 sender_it != current_senders->end();
4475 /* incremented manually */) {
4476 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004477 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004478 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4479 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004480 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004481 OnLocalSenderRemoved(info, media_type);
4482 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004483 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004484 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004485 }
4486 }
4487
Steve Anton4171afb2017-11-20 10:20:22 -08004488 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004489 for (const cricket::StreamParams& params : streams) {
4490 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004491 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004492 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004493 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004494 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004495 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004496 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004497 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004498 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004499 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004500 }
4501 }
4502}
4503
Steve Anton4171afb2017-11-20 10:20:22 -08004504void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4505 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004506 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004507 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004508 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004509 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4510 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004511 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004512 return;
4513 }
4514
deadbeeffac06552015-11-25 11:26:01 -08004515 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004516 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004517 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004518 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004519 }
deadbeeffac06552015-11-25 11:26:01 -08004520
Seth Hampson5b4f0752018-04-02 16:31:36 -07004521 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004522 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004523}
4524
Steve Anton4171afb2017-11-20 10:20:22 -08004525void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4526 cricket::MediaType media_type) {
4527 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004528 if (!sender) {
4529 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004530 // SessionDescriptions has been renegotiated.
4531 return;
4532 }
deadbeeffac06552015-11-25 11:26:01 -08004533
4534 // A sender has been removed from the SessionDescription but it's still
4535 // associated with the PeerConnection. This only occurs if the SDP doesn't
4536 // match with the calls to CreateSender, AddStream and RemoveStream.
4537 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004538 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004539 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004540 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004541 }
deadbeeffac06552015-11-25 11:26:01 -08004542
Steve Anton4171afb2017-11-20 10:20:22 -08004543 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004544}
4545
4546void PeerConnection::UpdateLocalRtpDataChannels(
4547 const cricket::StreamParamsVec& streams) {
4548 std::vector<std::string> existing_channels;
4549
4550 // Find new and active data channels.
4551 for (const cricket::StreamParams& params : streams) {
4552 // |it->sync_label| is actually the data channel label. The reason is that
4553 // we use the same naming of data channels as we do for
4554 // MediaStreams and Tracks.
4555 // For MediaStreams, the sync_label is the MediaStream label and the
4556 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004557 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004558 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004559 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004560 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004561 continue;
4562 }
4563 // Set the SSRC the data channel should use for sending.
4564 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4565 existing_channels.push_back(data_channel_it->first);
4566 }
4567
4568 UpdateClosingRtpDataChannels(existing_channels, true);
4569}
4570
4571void PeerConnection::UpdateRemoteRtpDataChannels(
4572 const cricket::StreamParamsVec& streams) {
4573 std::vector<std::string> existing_channels;
4574
4575 // Find new and active data channels.
4576 for (const cricket::StreamParams& params : streams) {
4577 // The data channel label is either the mslabel or the SSRC if the mslabel
4578 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004579 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004580 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004581 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004582 auto data_channel_it = rtp_data_channels_.find(label);
4583 if (data_channel_it == rtp_data_channels_.end()) {
4584 // This is a new data channel.
4585 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4586 } else {
4587 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4588 }
4589 existing_channels.push_back(label);
4590 }
4591
4592 UpdateClosingRtpDataChannels(existing_channels, false);
4593}
4594
4595void PeerConnection::UpdateClosingRtpDataChannels(
4596 const std::vector<std::string>& active_channels,
4597 bool is_local_update) {
4598 auto it = rtp_data_channels_.begin();
4599 while (it != rtp_data_channels_.end()) {
4600 DataChannel* data_channel = it->second;
4601 if (std::find(active_channels.begin(), active_channels.end(),
4602 data_channel->label()) != active_channels.end()) {
4603 ++it;
4604 continue;
4605 }
4606
4607 if (is_local_update) {
4608 data_channel->SetSendSsrc(0);
4609 } else {
4610 data_channel->RemotePeerRequestClose();
4611 }
4612
4613 if (data_channel->state() == DataChannel::kClosed) {
4614 rtp_data_channels_.erase(it);
4615 it = rtp_data_channels_.begin();
4616 } else {
4617 ++it;
4618 }
4619 }
4620}
4621
4622void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4623 uint32_t remote_ssrc) {
4624 rtc::scoped_refptr<DataChannel> channel(
4625 InternalCreateDataChannel(label, nullptr));
4626 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004627 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004628 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004629 return;
4630 }
4631 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004632 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4633 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004634 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004635}
4636
4637rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4638 const std::string& label,
4639 const InternalDataChannelInit* config) {
4640 if (IsClosed()) {
4641 return nullptr;
4642 }
Steve Anton75737c02017-11-06 10:37:17 -08004643 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004644 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004645 << "InternalCreateDataChannel: Data is not supported in this call.";
4646 return nullptr;
4647 }
4648 InternalDataChannelInit new_config =
4649 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004650 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004651 if (new_config.id < 0) {
4652 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004653 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004654 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004655 RTC_LOG(LS_ERROR)
4656 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004657 return nullptr;
4658 }
4659 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004660 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004661 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004662 return nullptr;
4663 }
4664 }
4665
Steve Anton75737c02017-11-06 10:37:17 -08004666 rtc::scoped_refptr<DataChannel> channel(
4667 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004668 if (!channel) {
4669 sid_allocator_.ReleaseSid(new_config.id);
4670 return nullptr;
4671 }
4672
4673 if (channel->data_channel_type() == cricket::DCT_RTP) {
4674 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004675 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4676 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004677 return nullptr;
4678 }
4679 rtp_data_channels_[channel->label()] = channel;
4680 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004681 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004682 sctp_data_channels_.push_back(channel);
4683 channel->SignalClosed.connect(this,
4684 &PeerConnection::OnSctpDataChannelClosed);
4685 }
4686
Steve Anton2d8609c2018-01-23 16:38:46 -08004687 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004688 return channel;
4689}
4690
4691bool PeerConnection::HasDataChannels() const {
4692 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4693}
4694
4695void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4696 for (const auto& channel : sctp_data_channels_) {
4697 if (channel->id() < 0) {
4698 int sid;
4699 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004700 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004701 continue;
4702 }
4703 channel->SetSctpSid(sid);
4704 }
4705 }
4706}
4707
4708void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004709 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004710 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4711 ++it) {
4712 if (it->get() == channel) {
4713 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004714 // After the closing procedure is done, it's safe to use this ID for
4715 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004716 sid_allocator_.ReleaseSid(channel->id());
4717 }
deadbeefbd292462015-12-14 18:15:29 -08004718 // Since this method is triggered by a signal from the DataChannel,
4719 // we can't free it directly here; we need to free it asynchronously.
4720 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004721 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004722 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4723 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004724 return;
4725 }
4726 }
4727}
4728
deadbeefab9b2d12015-10-14 11:33:11 -07004729void PeerConnection::OnDataChannelDestroyed() {
4730 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4731 // DataChannel may callback to us and try to modify the list.
4732 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4733 temp_rtp_dcs.swap(rtp_data_channels_);
4734 for (const auto& kv : temp_rtp_dcs) {
4735 kv.second->OnTransportChannelDestroyed();
4736 }
4737
4738 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4739 temp_sctp_dcs.swap(sctp_data_channels_);
4740 for (const auto& channel : temp_sctp_dcs) {
4741 channel->OnTransportChannelDestroyed();
4742 }
4743}
4744
4745void PeerConnection::OnDataChannelOpenMessage(
4746 const std::string& label,
4747 const InternalDataChannelInit& config) {
4748 rtc::scoped_refptr<DataChannel> channel(
4749 InternalCreateDataChannel(label, &config));
4750 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004751 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004752 return;
4753 }
4754
deadbeefa601f5c2016-06-06 14:27:39 -07004755 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4756 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004757 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004758 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004759}
4760
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004761bool PeerConnection::HandleOpenMessage_s(
4762 const cricket::ReceiveDataParams& params,
4763 const rtc::CopyOnWriteBuffer& buffer) {
4764 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4765 // Received OPEN message; parse and signal that a new data channel should
4766 // be created.
4767 std::string label;
4768 InternalDataChannelInit config;
4769 config.id = params.ssrc;
4770 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4771 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4772 << params.ssrc;
4773 return true;
4774 }
4775 config.open_handshake_role = InternalDataChannelInit::kAcker;
4776 OnDataChannelOpenMessage(label, config);
4777 return true;
4778 }
4779 return false;
4780}
4781
Steve Anton4171afb2017-11-20 10:20:22 -08004782rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4783PeerConnection::GetAudioTransceiver() const {
4784 // This method only works with Plan B SDP, where there is a single
4785 // audio/video transceiver.
4786 RTC_DCHECK(!IsUnifiedPlan());
4787 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004788 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004789 return transceiver;
4790 }
4791 }
4792 RTC_NOTREACHED();
4793 return nullptr;
4794}
4795
4796rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4797PeerConnection::GetVideoTransceiver() const {
4798 // This method only works with Plan B SDP, where there is a single
4799 // audio/video transceiver.
4800 RTC_DCHECK(!IsUnifiedPlan());
4801 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004802 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004803 return transceiver;
4804 }
4805 }
4806 RTC_NOTREACHED();
4807 return nullptr;
4808}
4809
4810// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4811// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004812bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004813 switch (type) {
4814 case cricket::MEDIA_TYPE_AUDIO:
4815 return !GetAudioTransceiver()->internal()->senders().empty();
4816 case cricket::MEDIA_TYPE_VIDEO:
4817 return !GetVideoTransceiver()->internal()->senders().empty();
4818 case cricket::MEDIA_TYPE_DATA:
4819 return false;
4820 }
4821 RTC_NOTREACHED();
4822 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004823}
4824
Steve Anton4171afb2017-11-20 10:20:22 -08004825rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4826PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4827 for (auto transceiver : transceivers_) {
4828 for (auto sender : transceiver->internal()->senders()) {
4829 if (sender->track() == track) {
4830 return sender;
4831 }
4832 }
4833 }
4834 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004835}
4836
Steve Anton4171afb2017-11-20 10:20:22 -08004837rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4838PeerConnection::FindSenderById(const std::string& sender_id) const {
4839 for (auto transceiver : transceivers_) {
4840 for (auto sender : transceiver->internal()->senders()) {
4841 if (sender->id() == sender_id) {
4842 return sender;
4843 }
4844 }
4845 }
4846 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004847}
4848
Steve Anton4171afb2017-11-20 10:20:22 -08004849rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4850PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4851 for (auto transceiver : transceivers_) {
4852 for (auto receiver : transceiver->internal()->receivers()) {
4853 if (receiver->id() == receiver_id) {
4854 return receiver;
4855 }
4856 }
4857 }
4858 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004859}
4860
Steve Anton4171afb2017-11-20 10:20:22 -08004861std::vector<PeerConnection::RtpSenderInfo>*
4862PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4863 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4864 media_type == cricket::MEDIA_TYPE_VIDEO);
4865 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4866 ? &remote_audio_sender_infos_
4867 : &remote_video_sender_infos_;
4868}
4869
4870std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004871 cricket::MediaType media_type) {
4872 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4873 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004874 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4875 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004876}
4877
Steve Anton4171afb2017-11-20 10:20:22 -08004878const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4879 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004880 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004881 const std::string sender_id) const {
4882 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004883 if (sender_info.stream_id == stream_id &&
4884 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004885 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004886 }
4887 }
4888 return nullptr;
4889}
4890
4891DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4892 for (const auto& channel : sctp_data_channels_) {
4893 if (channel->id() == sid) {
4894 return channel;
4895 }
4896 }
4897 return nullptr;
4898}
4899
deadbeef91dd5672016-05-18 16:55:30 -07004900bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004901 const cricket::ServerAddresses& stun_servers,
4902 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004903 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004904 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004905 // To handle both internal and externally created port allocator, we will
4906 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004907 port_allocator_flags_ = port_allocator_->flags();
4908 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4909 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4910 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004911 // If the disable-IPv6 flag was specified, we'll not override it
4912 // by experiment.
4913 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004914 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004915 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4916 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004917 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004918 }
4919
zhihuangb09b3f92017-03-07 14:40:51 -08004920 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004921 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004922 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004923 }
4924
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004925 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004926 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004927 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004928 }
4929
honghaiz60347052016-05-31 18:29:12 -07004930 if (configuration.candidate_network_policy ==
4931 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004932 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004933 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004934 }
4935
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004936 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004937 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004938 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4939 }
4940
Qingsi Wanga2d60672018-04-11 16:57:45 -07004941 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004942 // No step delay is used while allocating ports.
4943 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4944 port_allocator_->set_candidate_filter(
4945 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004946 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004947
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004948 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004949 for (auto& turn_server : turn_servers_copy) {
4950 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004951 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004952 // Call this last since it may create pooled allocator sessions using the
4953 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004954 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004955 stun_servers, std::move(turn_servers_copy),
4956 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4957 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004958 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004959 return true;
4960}
4961
deadbeef91dd5672016-05-18 16:55:30 -07004962bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004963 const cricket::ServerAddresses& stun_servers,
4964 const std::vector<cricket::RelayServerConfig>& turn_servers,
4965 IceTransportsType type,
4966 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004967 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004968 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004969 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004970 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004971 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004972 // According to JSEP, after setLocalDescription, changing the candidate pool
4973 // size is not allowed, and changing the set of ICE servers will not result
4974 // in new candidates being gathered.
4975 if (local_description()) {
4976 port_allocator_->FreezeCandidatePool();
4977 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004978 // Add the custom tls turn servers if they exist.
4979 auto turn_servers_copy = turn_servers;
4980 for (auto& turn_server : turn_servers_copy) {
4981 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4982 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004983 // Call this last since it may create pooled allocator sessions using the
4984 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004985 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004986 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4987 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004988}
4989
Steve Antonba818672017-11-06 10:21:57 -08004990cricket::ChannelManager* PeerConnection::channel_manager() const {
4991 return factory_->channel_manager();
4992}
4993
Elad Alon99c3fe52017-10-13 16:29:40 +02004994bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004995 std::unique_ptr<RtcEventLogOutput> output,
4996 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004997 if (!event_log_) {
4998 return false;
4999 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005000 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005001}
5002
5003void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005004 if (event_log_) {
5005 event_log_->StopLogging();
5006 }
ivoc14d5dbe2016-07-04 07:06:55 -07005007}
nisseeaabdf62017-05-05 02:23:02 -07005008
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005009cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005010 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005011 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005012 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005013 if (channel && channel->content_name() == content_name) {
5014 return channel;
5015 }
Steve Anton75737c02017-11-06 10:37:17 -08005016 }
5017 if (rtp_data_channel() &&
5018 rtp_data_channel()->content_name() == content_name) {
5019 return rtp_data_channel();
5020 }
5021 return nullptr;
5022}
5023
5024bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005025 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005026 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005027 RTC_LOG(LS_INFO)
5028 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005029 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005030 return false;
5031 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005032 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005033 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005034 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005035 return false;
5036 }
5037
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005038 absl::optional<rtc::SSLRole> dtls_role;
5039 if (sctp_mid_) {
5040 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5041 } else if (is_caller_) {
5042 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5043 }
Zhi Huange830e682018-03-30 10:48:35 -07005044 if (dtls_role) {
5045 *role = *dtls_role;
5046 return true;
5047 }
5048 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005049}
5050
5051bool PeerConnection::GetSslRole(const std::string& content_name,
5052 rtc::SSLRole* role) {
5053 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005054 RTC_LOG(LS_INFO)
5055 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005056 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005057 return false;
5058 }
5059
Zhi Huange830e682018-03-30 10:48:35 -07005060 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5061 if (dtls_role) {
5062 *role = *dtls_role;
5063 return true;
5064 }
5065 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005066}
5067
Steve Antonf8470812017-12-04 10:46:21 -08005068void PeerConnection::SetSessionError(SessionError error,
5069 const std::string& error_desc) {
5070 RTC_DCHECK_RUN_ON(signaling_thread());
5071 if (error != session_error_) {
5072 session_error_ = error;
5073 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005074 }
5075}
5076
Zhi Huange830e682018-03-30 10:48:35 -07005077RTCError PeerConnection::UpdateSessionState(
5078 SdpType type,
5079 cricket::ContentSource source,
5080 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005081 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005082
5083 // If there's already a pending error then no state transition should happen.
5084 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005085 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005086
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005087 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005088 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005089 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005090 }
5091
5092 // Update the signaling state according to the specified state machine (see
5093 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005094 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005095 ChangeSignalingState(source == cricket::CS_LOCAL
5096 ? PeerConnectionInterface::kHaveLocalOffer
5097 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005098 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005099 ChangeSignalingState(source == cricket::CS_LOCAL
5100 ? PeerConnectionInterface::kHaveLocalPrAnswer
5101 : PeerConnectionInterface::kHaveRemotePrAnswer);
5102 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005103 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005104 ChangeSignalingState(PeerConnectionInterface::kStable);
5105 }
5106
5107 // Update internal objects according to the session description's media
5108 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005109 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005110 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005111 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005112 }
5113
Steve Anton8a006912017-12-04 15:25:56 -08005114 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005115}
5116
Steve Anton8a006912017-12-04 15:25:56 -08005117RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005118 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005119 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005120 const SessionDescriptionInterface* sdesc =
5121 (source == cricket::CS_LOCAL ? local_description()
5122 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005123 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005124
5125 // Push down the new SDP media section for each audio/video transceiver.
5126 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005127 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005128 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005129 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005130 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005131 continue;
5132 }
5133 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005134 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005135 if (!content_desc) {
5136 continue;
5137 }
5138 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005139 bool success = (source == cricket::CS_LOCAL)
5140 ? channel->SetLocalContent(content_desc, type, &error)
5141 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005142 if (!success) {
5143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5144 }
5145 }
5146
5147 // If using the RtpDataChannel, push down the new SDP section for it too.
5148 if (rtp_data_channel_) {
5149 const ContentInfo* data_content =
5150 cricket::GetFirstDataContent(sdesc->description());
5151 if (data_content && !data_content->rejected) {
5152 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005153 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005154 if (data_desc) {
5155 std::string error;
5156 bool success =
5157 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005158 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005159 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005160 if (!success) {
5161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5162 std::move(error));
5163 }
Steve Anton75737c02017-11-06 10:37:17 -08005164 }
5165 }
5166 }
Steve Antoned10bd92017-12-05 10:52:59 -08005167
Steve Anton75737c02017-11-06 10:37:17 -08005168 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5169 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5170 if (sctp_transport_ && local_description() && remote_description() &&
5171 cricket::GetFirstDataContent(local_description()->description()) &&
5172 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005173 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005174 RTC_FROM_HERE,
5175 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005176 if (!success) {
5177 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5178 "Failed to push down SCTP parameters.");
5179 }
Steve Anton75737c02017-11-06 10:37:17 -08005180 }
Steve Antoned10bd92017-12-05 10:52:59 -08005181
Steve Anton8a006912017-12-04 15:25:56 -08005182 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005183}
5184
5185bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5186 RTC_DCHECK(network_thread()->IsCurrent());
5187 RTC_DCHECK(local_description());
5188 RTC_DCHECK(remote_description());
5189 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5190 // When we support "max-message-size", that would also be pushed down here.
5191 return sctp_transport_->Start(
5192 GetSctpPort(local_description()->description()),
5193 GetSctpPort(remote_description()->description()));
5194}
5195
Steve Anton8a006912017-12-04 15:25:56 -08005196RTCError PeerConnection::PushdownTransportDescription(
5197 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005198 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005199 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005200
Zhi Huange830e682018-03-30 10:48:35 -07005201 if (source == cricket::CS_LOCAL) {
5202 const SessionDescriptionInterface* sdesc = local_description();
5203 RTC_DCHECK(sdesc);
5204 return transport_controller_->SetLocalDescription(type,
5205 sdesc->description());
5206 } else {
5207 const SessionDescriptionInterface* sdesc = remote_description();
5208 RTC_DCHECK(sdesc);
5209 return transport_controller_->SetRemoteDescription(type,
5210 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005211 }
Steve Anton75737c02017-11-06 10:37:17 -08005212}
5213
5214bool PeerConnection::GetTransportDescription(
5215 const SessionDescription* description,
5216 const std::string& content_name,
5217 cricket::TransportDescription* tdesc) {
5218 if (!description || !tdesc) {
5219 return false;
5220 }
5221 const TransportInfo* transport_info =
5222 description->GetTransportInfoByName(content_name);
5223 if (!transport_info) {
5224 return false;
5225 }
5226 *tdesc = transport_info->description;
5227 return true;
5228}
5229
Steve Anton75737c02017-11-06 10:37:17 -08005230cricket::IceConfig PeerConnection::ParseIceConfig(
5231 const PeerConnectionInterface::RTCConfiguration& config) const {
5232 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005233 switch (config.continual_gathering_policy) {
5234 case PeerConnectionInterface::GATHER_ONCE:
5235 gathering_policy = cricket::GATHER_ONCE;
5236 break;
5237 case PeerConnectionInterface::GATHER_CONTINUALLY:
5238 gathering_policy = cricket::GATHER_CONTINUALLY;
5239 break;
5240 default:
5241 RTC_NOTREACHED();
5242 gathering_policy = cricket::GATHER_ONCE;
5243 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005244
Steve Anton75737c02017-11-06 10:37:17 -08005245 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005246 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5247 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005248 ice_config.prioritize_most_likely_candidate_pairs =
5249 config.prioritize_most_likely_ice_candidate_pairs;
5250 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005251 RTCConfigurationToIceConfigOptionalInt(
5252 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005253 ice_config.continual_gathering_policy = gathering_policy;
5254 ice_config.presume_writable_when_fully_relayed =
5255 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005256 ice_config.ice_check_interval_strong_connectivity =
5257 config.ice_check_interval_strong_connectivity;
5258 ice_config.ice_check_interval_weak_connectivity =
5259 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005260 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005261 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5262 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005263 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005264 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005265 ice_config.regather_all_networks_interval_range =
5266 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005267 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005268 return ice_config;
5269}
5270
Steve Antona41959e2018-11-28 11:15:33 -08005271static absl::string_view GetTrackIdBySsrc(
5272 const SessionDescriptionInterface* session_description,
5273 uint32_t ssrc) {
5274 if (!session_description) {
5275 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
Steve Antona41959e2018-11-28 11:15:33 -08005277 for (const cricket::ContentInfo& content :
5278 session_description->description()->contents()) {
5279 const cricket::MediaContentDescription& media =
5280 *content.media_description();
5281 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5282 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5283 const cricket::StreamParams* stream_params =
5284 cricket::GetStreamBySsrc(media.streams(), ssrc);
5285 if (stream_params) {
5286 return stream_params->id;
5287 }
5288 }
5289 }
5290 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005291}
5292
Steve Antona41959e2018-11-28 11:15:33 -08005293absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5294 return GetTrackIdBySsrc(local_description(), ssrc);
5295}
5296
5297absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5298 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005299}
5300
5301bool PeerConnection::SendData(const cricket::SendDataParams& params,
5302 const rtc::CopyOnWriteBuffer& payload,
5303 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005304 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5305 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5306 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005307 return false;
5308 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005309 if (media_transport_) {
5310 SendDataParams send_params;
5311 send_params.type = ToWebrtcDataMessageType(params.type);
5312 send_params.ordered = params.ordered;
5313 if (params.max_rtx_count >= 0) {
5314 send_params.max_rtx_count = params.max_rtx_count;
5315 } else if (params.max_rtx_ms >= 0) {
5316 send_params.max_rtx_ms = params.max_rtx_ms;
5317 }
5318 return media_transport_->SendData(params.sid, send_params, payload).ok();
5319 }
Steve Anton75737c02017-11-06 10:37:17 -08005320 return rtp_data_channel_
5321 ? rtp_data_channel_->SendData(params, payload, result)
5322 : network_thread()->Invoke<bool>(
5323 RTC_FROM_HERE,
5324 Bind(&cricket::SctpTransportInternal::SendData,
5325 sctp_transport_.get(), params, payload, result));
5326}
5327
5328bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005329 RTC_DCHECK_RUN_ON(signaling_thread());
5330 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005331 // Don't log an error here, because DataChannels are expected to call
5332 // ConnectDataChannel in this state. It's the only way to initially tell
5333 // whether or not the underlying transport is ready.
5334 return false;
5335 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005336 if (media_transport_) {
5337 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5338 &DataChannel::OnChannelReady);
5339 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5340 &DataChannel::OnDataReceived);
5341 SignalMediaTransportChannelClosing_s.connect(
5342 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5343 SignalMediaTransportChannelClosed_s.connect(
5344 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5345 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005346 rtp_data_channel_->SignalReadyToSendData.connect(
5347 webrtc_data_channel, &DataChannel::OnChannelReady);
5348 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5349 &DataChannel::OnDataReceived);
5350 } else {
5351 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5352 &DataChannel::OnChannelReady);
5353 SignalSctpDataReceived.connect(webrtc_data_channel,
5354 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005355 SignalSctpClosingProcedureStartedRemotely.connect(
5356 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5357 SignalSctpClosingProcedureComplete.connect(
5358 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005359 }
5360 return true;
5361}
5362
5363void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005364 RTC_DCHECK_RUN_ON(signaling_thread());
5365 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005366 RTC_LOG(LS_ERROR)
5367 << "DisconnectDataChannel called when rtp_data_channel_ and "
5368 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005369 return;
5370 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005371 if (media_transport_) {
5372 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5373 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5374 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5375 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5376 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005377 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5378 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5379 } else {
5380 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5381 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005382 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5383 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005384 }
5385}
5386
5387void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005388 if (media_transport_) {
5389 // No-op. Media transport does not need to add streams.
5390 return;
5391 }
Steve Anton75737c02017-11-06 10:37:17 -08005392 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005393 RTC_LOG(LS_ERROR)
5394 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005395 return;
5396 }
5397 network_thread()->Invoke<void>(
5398 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5399 sctp_transport_.get(), sid));
5400}
5401
5402void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005403 if (media_transport_) {
5404 media_transport_->CloseChannel(sid);
5405 return;
5406 }
Steve Anton75737c02017-11-06 10:37:17 -08005407 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005408 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005409 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005410 return;
5411 }
5412 network_thread()->Invoke<void>(
5413 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5414 sctp_transport_.get(), sid));
5415}
5416
5417bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005418 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005419 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005420 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005421 sctp_ready_to_send_data_;
5422}
5423
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005424void PeerConnection::OnDataReceived(int channel_id,
5425 DataMessageType type,
5426 const rtc::CopyOnWriteBuffer& buffer) {
5427 cricket::ReceiveDataParams params;
5428 params.sid = channel_id;
5429 params.type = ToCricketDataMessageType(type);
5430 media_transport_invoker_->AsyncInvoke<void>(
5431 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5432 RTC_DCHECK_RUN_ON(signaling_thread());
5433 if (!HandleOpenMessage_s(params, buffer)) {
5434 SignalMediaTransportReceivedData_s(params, buffer);
5435 }
5436 });
5437}
5438
5439void PeerConnection::OnChannelClosing(int channel_id) {
5440 media_transport_invoker_->AsyncInvoke<void>(
5441 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5442 RTC_DCHECK_RUN_ON(signaling_thread());
5443 SignalMediaTransportChannelClosing_s(channel_id);
5444 });
5445}
5446
5447void PeerConnection::OnChannelClosed(int channel_id) {
5448 media_transport_invoker_->AsyncInvoke<void>(
5449 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5450 RTC_DCHECK_RUN_ON(signaling_thread());
5451 SignalMediaTransportChannelClosed_s(channel_id);
5452 });
5453}
5454
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005455absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005456 if (sctp_mid_ && transport_controller_) {
5457 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5458 if (dtls_transport) {
5459 return dtls_transport->transport_name();
5460 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005461 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005462 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005463 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005464}
5465
Qingsi Wang72a43a12018-02-20 16:03:18 -08005466cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5467 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005468 network_thread()->Invoke<void>(
5469 RTC_FROM_HERE,
5470 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5471 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005472 return candidate_states_list;
5473}
5474
Steve Anton5dfde182018-02-06 10:34:40 -08005475std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5476 const {
5477 std::map<std::string, std::string> transport_names_by_mid;
5478 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005479 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005480 if (channel) {
5481 transport_names_by_mid[channel->content_name()] =
5482 channel->transport_name();
5483 }
Steve Anton75737c02017-11-06 10:37:17 -08005484 }
Steve Anton5dfde182018-02-06 10:34:40 -08005485 if (rtp_data_channel_) {
5486 transport_names_by_mid[rtp_data_channel_->content_name()] =
5487 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005488 }
5489 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005490 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005491 RTC_DCHECK(transport_name);
5492 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005493 }
Steve Anton5dfde182018-02-06 10:34:40 -08005494 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
Steve Anton5dfde182018-02-06 10:34:40 -08005497std::map<std::string, cricket::TransportStats>
5498PeerConnection::GetTransportStatsByNames(
5499 const std::set<std::string>& transport_names) {
5500 if (!network_thread()->IsCurrent()) {
5501 return network_thread()
5502 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5503 RTC_FROM_HERE,
5504 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005505 }
Steve Anton5dfde182018-02-06 10:34:40 -08005506 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5507 for (const std::string& transport_name : transport_names) {
5508 cricket::TransportStats transport_stats;
5509 bool success =
5510 transport_controller_->GetStats(transport_name, &transport_stats);
5511 if (success) {
5512 transport_stats_by_name[transport_name] = std::move(transport_stats);
5513 } else {
5514 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5515 << transport_name;
5516 }
5517 }
5518 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005519}
5520
5521bool PeerConnection::GetLocalCertificate(
5522 const std::string& transport_name,
5523 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005524 if (!certificate) {
5525 return false;
5526 }
5527 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5528 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005529}
5530
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005531std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005532 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005533 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005534}
5535
5536cricket::DataChannelType PeerConnection::data_channel_type() const {
5537 return data_channel_type_;
5538}
5539
5540bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5541 return pending_ice_restarts_.find(content_name) !=
5542 pending_ice_restarts_.end();
5543}
5544
Steve Anton75737c02017-11-06 10:37:17 -08005545bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5546 return transport_controller_->NeedsIceRestart(content_name);
5547}
5548
5549void PeerConnection::OnCertificateReady(
5550 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5551 transport_controller_->SetLocalCertificate(certificate);
5552}
5553
5554void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005555 SetSessionError(SessionError::kTransport,
5556 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005557}
5558
Alex Loiko9289eda2018-11-23 16:18:59 +00005559void PeerConnection::OnTransportControllerConnectionState(
5560 cricket::IceConnectionState state) {
5561 switch (state) {
5562 case cricket::kIceConnectionConnecting:
5563 // If the current state is Connected or Completed, then there were
5564 // writable channels but now there are not, so the next state must
5565 // be Disconnected.
5566 // kIceConnectionConnecting is currently used as the default,
5567 // un-connected state by the TransportController, so its only use is
5568 // detecting disconnections.
5569 if (ice_connection_state_ ==
5570 PeerConnectionInterface::kIceConnectionConnected ||
5571 ice_connection_state_ ==
5572 PeerConnectionInterface::kIceConnectionCompleted) {
5573 SetIceConnectionState(
5574 PeerConnectionInterface::kIceConnectionDisconnected);
5575 }
5576 break;
5577 case cricket::kIceConnectionFailed:
5578 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5579 break;
5580 case cricket::kIceConnectionConnected:
5581 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5582 "all transports are writable.";
5583 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5584 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5585 break;
5586 case cricket::kIceConnectionCompleted:
5587 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5588 "all transports are complete.";
5589 if (ice_connection_state_ !=
5590 PeerConnectionInterface::kIceConnectionConnected) {
5591 // If jumping directly from "checking" to "connected",
5592 // signal "connected" first.
5593 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5594 }
5595 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5596 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5597 ReportTransportStats();
5598 break;
5599 default:
5600 RTC_NOTREACHED();
5601 }
5602}
5603
Steve Anton75737c02017-11-06 10:37:17 -08005604void PeerConnection::OnTransportControllerCandidatesGathered(
5605 const std::string& transport_name,
5606 const cricket::Candidates& candidates) {
5607 RTC_DCHECK(signaling_thread()->IsCurrent());
5608 int sdp_mline_index;
5609 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005610 RTC_LOG(LS_ERROR)
5611 << "OnTransportControllerCandidatesGathered: content name "
5612 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005613 return;
5614 }
5615
5616 for (cricket::Candidates::const_iterator citer = candidates.begin();
5617 citer != candidates.end(); ++citer) {
5618 // Use transport_name as the candidate media id.
5619 std::unique_ptr<JsepIceCandidate> candidate(
5620 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5621 if (local_description()) {
5622 mutable_local_description()->AddCandidate(candidate.get());
5623 }
5624 OnIceCandidate(std::move(candidate));
5625 }
5626}
5627
5628void PeerConnection::OnTransportControllerCandidatesRemoved(
5629 const std::vector<cricket::Candidate>& candidates) {
5630 RTC_DCHECK(signaling_thread()->IsCurrent());
5631 // Sanity check.
5632 for (const cricket::Candidate& candidate : candidates) {
5633 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005634 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005635 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005636 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005637 return;
5638 }
5639 }
5640
5641 if (local_description()) {
5642 mutable_local_description()->RemoveCandidates(candidates);
5643 }
5644 OnIceCandidatesRemoved(candidates);
5645}
5646
5647void PeerConnection::OnTransportControllerDtlsHandshakeError(
5648 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005649 RTC_HISTOGRAM_ENUMERATION(
5650 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5651 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005652}
5653
Steve Antoned10bd92017-12-05 10:52:59 -08005654void PeerConnection::EnableSending() {
5655 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005656 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005657 if (channel && !channel->enabled()) {
5658 channel->Enable(true);
5659 }
Steve Anton75737c02017-11-06 10:37:17 -08005660 }
5661
Steve Anton4171afb2017-11-20 10:20:22 -08005662 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005663 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005664 }
Steve Anton75737c02017-11-06 10:37:17 -08005665}
5666
5667// Returns the media index for a local ice candidate given the content name.
5668bool PeerConnection::GetLocalCandidateMediaIndex(
5669 const std::string& content_name,
5670 int* sdp_mline_index) {
5671 if (!local_description() || !sdp_mline_index) {
5672 return false;
5673 }
5674
5675 bool content_found = false;
5676 const ContentInfos& contents = local_description()->description()->contents();
5677 for (size_t index = 0; index < contents.size(); ++index) {
5678 if (contents[index].name == content_name) {
5679 *sdp_mline_index = static_cast<int>(index);
5680 content_found = true;
5681 break;
5682 }
5683 }
5684 return content_found;
5685}
5686
5687bool PeerConnection::UseCandidatesInSessionDescription(
5688 const SessionDescriptionInterface* remote_desc) {
5689 if (!remote_desc) {
5690 return true;
5691 }
5692 bool ret = true;
5693
5694 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5695 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5696 for (size_t n = 0; n < candidates->count(); ++n) {
5697 const IceCandidateInterface* candidate = candidates->at(n);
5698 bool valid = false;
5699 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5700 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005701 RTC_LOG(LS_INFO)
5702 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005703 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005704 }
5705 continue;
5706 }
5707 ret = UseCandidate(candidate);
5708 if (!ret) {
5709 break;
5710 }
5711 }
5712 }
5713 return ret;
5714}
5715
5716bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5717 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5718 size_t remote_content_size =
5719 remote_description()->description()->contents().size();
5720 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005721 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005722 return false;
5723 }
5724
5725 cricket::ContentInfo content =
5726 remote_description()->description()->contents()[mediacontent_index];
5727 std::vector<cricket::Candidate> candidates;
5728 candidates.push_back(candidate->candidate());
5729 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005730 RTCError error =
5731 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005732 if (error.ok()) {
5733 // Candidates successfully submitted for checking.
5734 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5735 ice_connection_state_ ==
5736 PeerConnectionInterface::kIceConnectionDisconnected) {
5737 // If state is New, then the session has just gotten its first remote ICE
5738 // candidates, so go to Checking.
5739 // If state is Disconnected, the session is re-using old candidates or
5740 // receiving additional ones, so go to Checking.
5741 // If state is Connected, stay Connected.
5742 // TODO(bemasc): If state is Connected, and the new candidates are for a
5743 // newly added transport, then the state actually _should_ move to
5744 // checking. Add a way to distinguish that case.
5745 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5746 }
5747 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005748 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005749 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751 return true;
5752}
5753
5754void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005755 // Destroy video channel first since it may have a pointer to the
5756 // voice channel.
5757 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005758 if (!video_info || video_info->rejected) {
5759 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761
Steve Anton6fec8802017-12-04 10:37:29 -08005762 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5763 if (!audio_info || audio_info->rejected) {
5764 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766
5767 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5768 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005769 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005770 }
5771}
5772
Steve Antondcc3c022017-12-22 16:02:54 -08005773RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5774 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005775 const cricket::ContentGroup* bundle_group = nullptr;
5776 if (configuration_.bundle_policy ==
5777 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005778 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005779 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005780 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5781 "max-bundle configured but session description "
5782 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005783 }
5784 }
Steve Antondcc3c022017-12-22 16:02:54 -08005785 return std::move(bundle_group);
5786}
5787
5788RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005789 // Creating the media channels. Transports should already have been created
5790 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005791 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005792 if (voice && !voice->rejected &&
5793 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005794 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005795 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005796 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5797 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005798 }
5799 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5800 }
5801
Steve Antondcc3c022017-12-22 16:02:54 -08005802 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005803 if (video && !video->rejected &&
5804 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005805 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005806 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005807 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5808 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005809 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005810 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005811 }
5812
Steve Antondcc3c022017-12-22 16:02:54 -08005813 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005814 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005815 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005816 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005817 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5818 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005819 }
5820 }
5821
Steve Anton8a006912017-12-04 15:25:56 -08005822 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005823}
5824
Steve Anton4171afb2017-11-20 10:20:22 -08005825// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005826cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005827 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005828 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005829 MediaTransportInterface* media_transport = nullptr;
5830 if (configuration_.use_media_transport) {
5831 media_transport = GetMediaTransport(mid);
5832 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005833
Steve Anton75737c02017-11-06 10:37:17 -08005834 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005835 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005836 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5837 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005838 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005839 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005840 }
Steve Anton75737c02017-11-06 10:37:17 -08005841 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5842 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005843 voice_channel->SignalSentPacket.connect(this,
5844 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005845 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005846
Steve Antoneda6ccd2017-12-04 10:21:55 -08005847 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005848}
5849
Steve Anton4171afb2017-11-20 10:20:22 -08005850// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005851cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005852 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005853 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5854
5855 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005856 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005857 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005858 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5859 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005860 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005861 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005862 }
Steve Anton75737c02017-11-06 10:37:17 -08005863 video_channel->SignalDtlsSrtpSetupFailure.connect(
5864 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005865 video_channel->SignalSentPacket.connect(this,
5866 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005867 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005868
Steve Antoneda6ccd2017-12-04 10:21:55 -08005869 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005870}
5871
Zhi Huange830e682018-03-30 10:48:35 -07005872bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005873 switch (data_channel_type_) {
5874 case cricket::DCT_MEDIA_TRANSPORT:
5875 if (network_thread()->Invoke<bool>(
5876 RTC_FROM_HERE,
5877 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5878 this, mid))) {
5879 for (const auto& channel : sctp_data_channels_) {
5880 channel->OnTransportChannelCreated();
5881 }
5882 return true;
5883 }
Steve Anton75737c02017-11-06 10:37:17 -08005884 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005885 case cricket::DCT_SCTP:
5886 if (!sctp_factory_) {
5887 RTC_LOG(LS_ERROR)
5888 << "Trying to create SCTP transport, but didn't compile with "
5889 "SCTP support (HAVE_SCTP)";
5890 return false;
5891 }
5892 if (!network_thread()->Invoke<bool>(
5893 RTC_FROM_HERE,
5894 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5895 return false;
5896 }
5897 for (const auto& channel : sctp_data_channels_) {
5898 channel->OnTransportChannelCreated();
5899 }
5900 return true;
5901 case cricket::DCT_RTP:
5902 default:
5903 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5904 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5905 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5906 SrtpRequired(), GetCryptoOptions());
5907 if (!rtp_data_channel_) {
5908 return false;
5909 }
5910 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5911 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5912 rtp_data_channel_->SignalSentPacket.connect(
5913 this, &PeerConnection::OnSentPacket_w);
5914 rtp_data_channel_->SetRtpTransport(rtp_transport);
5915 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005916 }
5917
Steve Anton75737c02017-11-06 10:37:17 -08005918 return true;
5919}
5920
5921Call::Stats PeerConnection::GetCallStats() {
5922 if (!worker_thread()->IsCurrent()) {
5923 return worker_thread()->Invoke<Call::Stats>(
5924 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5925 }
5926 if (call_) {
5927 return call_->GetStats();
5928 } else {
5929 return Call::Stats();
5930 }
5931}
5932
Zhi Huange830e682018-03-30 10:48:35 -07005933bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005934 RTC_DCHECK(network_thread()->IsCurrent());
5935 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005936 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005937 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005938 RTC_DCHECK(dtls_transport);
5939 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005940 RTC_DCHECK(sctp_transport_);
5941 sctp_invoker_.reset(new rtc::AsyncInvoker());
5942 sctp_transport_->SignalReadyToSendData.connect(
5943 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5944 sctp_transport_->SignalDataReceived.connect(
5945 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005946 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5947 // another thread. Would be nice if there was a helper class similar to
5948 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5949 // code.
5950 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5951 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5952 sctp_transport_->SignalClosingProcedureComplete.connect(
5953 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005954 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005955 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005956 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005957}
5958
5959void PeerConnection::DestroySctpTransport_n() {
5960 RTC_DCHECK(network_thread()->IsCurrent());
5961 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005962 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005963 sctp_invoker_.reset(nullptr);
5964 sctp_ready_to_send_data_ = false;
5965}
5966
5967void PeerConnection::OnSctpTransportReadyToSendData_n() {
5968 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5969 RTC_DCHECK(network_thread()->IsCurrent());
5970 // Note: Cannot use rtc::Bind here because it will grab a reference to
5971 // PeerConnection and potentially cause PeerConnection to live longer than
5972 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5973 // be destroyed before PeerConnection is destroyed, and at that point all
5974 // pending tasks will be cleared.
5975 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5976 OnSctpTransportReadyToSendData_s(true);
5977 });
5978}
5979
5980void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5981 RTC_DCHECK(signaling_thread()->IsCurrent());
5982 sctp_ready_to_send_data_ = ready;
5983 SignalSctpReadyToSendData(ready);
5984}
5985
5986void PeerConnection::OnSctpTransportDataReceived_n(
5987 const cricket::ReceiveDataParams& params,
5988 const rtc::CopyOnWriteBuffer& payload) {
5989 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5990 RTC_DCHECK(network_thread()->IsCurrent());
5991 // Note: Cannot use rtc::Bind here because it will grab a reference to
5992 // PeerConnection and potentially cause PeerConnection to live longer than
5993 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5994 // be destroyed before PeerConnection is destroyed, and at that point all
5995 // pending tasks will be cleared.
5996 sctp_invoker_->AsyncInvoke<void>(
5997 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5998 OnSctpTransportDataReceived_s(params, payload);
5999 });
6000}
6001
6002void PeerConnection::OnSctpTransportDataReceived_s(
6003 const cricket::ReceiveDataParams& params,
6004 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006005 RTC_DCHECK_RUN_ON(signaling_thread());
6006 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006007 SignalSctpDataReceived(params, payload);
6008 }
6009}
6010
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006011void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006012 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6013 RTC_DCHECK(network_thread()->IsCurrent());
6014 sctp_invoker_->AsyncInvoke<void>(
6015 RTC_FROM_HERE, signaling_thread(),
6016 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006017 &SignalSctpClosingProcedureStartedRemotely, sid));
6018}
6019
6020void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6021 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6022 RTC_DCHECK(network_thread()->IsCurrent());
6023 sctp_invoker_->AsyncInvoke<void>(
6024 RTC_FROM_HERE, signaling_thread(),
6025 rtc::Bind(&sigslot::signal1<int>::operator(),
6026 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006027}
6028
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006029bool PeerConnection::SetupMediaTransportForDataChannels_n(
6030 const std::string& mid) {
6031 media_transport_ = transport_controller_->GetMediaTransport(mid);
6032 if (!media_transport_) {
6033 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6034 return false;
6035 }
6036
6037 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6038 media_transport_->SetDataSink(this);
6039 media_transport_data_mid_ = mid;
6040 transport_controller_->SignalMediaTransportStateChanged.connect(
6041 this, &PeerConnection::OnMediaTransportStateChanged_n);
6042 // Check the initial state right away, in case transport is already writable.
6043 OnMediaTransportStateChanged_n();
6044 return true;
6045}
6046
6047void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6048 if (!media_transport_) {
6049 return;
6050 }
6051 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6052 media_transport_data_mid_.reset();
6053 media_transport_->SetDataSink(nullptr);
6054 media_transport_invoker_ = nullptr;
6055 media_transport_ = nullptr;
6056}
6057
6058void PeerConnection::OnMediaTransportStateChanged_n() {
6059 if (!media_transport_data_mid_ ||
6060 transport_controller_->GetMediaTransportState(
6061 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6062 return;
6063 }
6064 media_transport_invoker_->AsyncInvoke<void>(
6065 RTC_FROM_HERE, signaling_thread(), [this] {
6066 RTC_DCHECK_RUN_ON(signaling_thread());
6067 media_transport_ready_to_send_data_ = true;
6068 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6069 });
6070}
6071
Steve Anton75737c02017-11-06 10:37:17 -08006072// Returns false if bundle is enabled and rtcp_mux is disabled.
6073bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6074 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6075 if (!bundle_enabled)
6076 return true;
6077
6078 const cricket::ContentGroup* bundle_group =
6079 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6080 RTC_DCHECK(bundle_group != NULL);
6081
6082 const cricket::ContentInfos& contents = desc->contents();
6083 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6084 citer != contents.end(); ++citer) {
6085 const cricket::ContentInfo* content = (&*citer);
6086 RTC_DCHECK(content != NULL);
6087 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006088 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006089 if (!HasRtcpMuxEnabled(content))
6090 return false;
6091 }
6092 }
6093 // RTCP-MUX is enabled in all the contents.
6094 return true;
6095}
6096
6097bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006098 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006099}
6100
Steve Anton8a006912017-12-04 15:25:56 -08006101RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006102 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006103 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006104 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006105 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006106 }
6107
6108 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006110 }
6111
Steve Anton3828c062017-12-06 10:34:51 -08006112 SdpType type = sdesc->GetType();
6113 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6114 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006115 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006116 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006117 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006118 }
6119
6120 // Verify crypto settings.
6121 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006122 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6123 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006124 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006125 if (!crypto_error.ok()) {
6126 return crypto_error;
6127 }
Steve Anton75737c02017-11-06 10:37:17 -08006128 }
6129
6130 // Verify ice-ufrag and ice-pwd.
6131 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6133 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006134 }
6135
6136 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006137 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6138 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006139 }
6140
6141 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6142 // m-lines that do not rtcp-mux enabled.
6143
6144 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006145 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006146 // With an answer we want to compare the new answer session description with
6147 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006148 const cricket::SessionDescription* offer_desc =
6149 (source == cricket::CS_LOCAL) ? remote_description()->description()
6150 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006151 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6152 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6153 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006154 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6155 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006156 }
6157 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006158 // The re-offers should respect the order of m= sections in current
6159 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006160 // With a re-offer, either the current local or current remote descriptions
6161 // could be the most up to date, so we would like to check against both of
6162 // them if they exist. It could be the case that one of them has a 0 port
6163 // for a media section, but the other does not. This is important to check
6164 // against in the case that we are recycling an m= section.
6165 const cricket::SessionDescription* current_desc = nullptr;
6166 const cricket::SessionDescription* secondary_current_desc = nullptr;
6167 if (local_description()) {
6168 current_desc = local_description()->description();
6169 if (remote_description()) {
6170 secondary_current_desc = remote_description()->description();
6171 }
6172 } else if (remote_description()) {
6173 current_desc = remote_description()->description();
6174 }
Steve Anton75737c02017-11-06 10:37:17 -08006175 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006176 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6177 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006178 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6179 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006180 }
6181 }
6182
Steve Antonba42e992018-04-09 14:10:01 -07006183 if (IsUnifiedPlan()) {
6184 // Ensure that each audio and video media section has at most one
6185 // "StreamParams". This will return an error if receiving a session
6186 // description from a "Plan B" endpoint which adds multiple tracks of the
6187 // same type. With Unified Plan, there can only be at most one track per
6188 // media section.
6189 for (const ContentInfo& content : sdesc->description()->contents()) {
6190 const MediaContentDescription& desc = *content.description;
6191 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6192 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6193 desc.streams().size() > 1u) {
6194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6195 "Media section has more than one track specified "
6196 "with a=ssrc lines which is not supported with "
6197 "Unified Plan.");
6198 }
6199 }
6200 }
6201
Steve Anton8a006912017-12-04 15:25:56 -08006202 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006203}
6204
Steve Anton3828c062017-12-06 10:34:51 -08006205bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006206 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006207 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006208 return (state == PeerConnectionInterface::kStable) ||
6209 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006210 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006211 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006212 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6213 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6214 }
6215}
6216
Steve Anton3828c062017-12-06 10:34:51 -08006217bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006218 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006219 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006220 return (state == PeerConnectionInterface::kStable) ||
6221 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006222 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006223 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006224 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6225 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6226 }
6227}
6228
Steve Antonf8470812017-12-04 10:46:21 -08006229const char* PeerConnection::SessionErrorToString(SessionError error) const {
6230 switch (error) {
6231 case SessionError::kNone:
6232 return "ERROR_NONE";
6233 case SessionError::kContent:
6234 return "ERROR_CONTENT";
6235 case SessionError::kTransport:
6236 return "ERROR_TRANSPORT";
6237 }
6238 RTC_NOTREACHED();
6239 return "";
6240}
6241
Steve Anton75737c02017-11-06 10:37:17 -08006242std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006243 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006244 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6245 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006246 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006247}
6248
Steve Anton8e20f172018-03-06 10:55:04 -08006249void PeerConnection::ReportSdpFormatReceived(
6250 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006251 int num_audio_mlines = 0;
6252 int num_video_mlines = 0;
6253 int num_audio_tracks = 0;
6254 int num_video_tracks = 0;
6255 for (const ContentInfo& content : remote_offer.description()->contents()) {
6256 cricket::MediaType media_type = content.media_description()->type();
6257 int num_tracks = std::max(
6258 1, static_cast<int>(content.media_description()->streams().size()));
6259 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6260 num_audio_mlines += 1;
6261 num_audio_tracks += num_tracks;
6262 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6263 num_video_mlines += 1;
6264 num_video_tracks += num_tracks;
6265 }
6266 }
6267 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6268 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6269 format = kSdpFormatReceivedComplexUnifiedPlan;
6270 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6271 format = kSdpFormatReceivedComplexPlanB;
6272 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6273 format = kSdpFormatReceivedSimple;
6274 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006275 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6276 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006277}
6278
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006279void PeerConnection::NoteUsageEvent(UsageEvent event) {
6280 RTC_DCHECK_RUN_ON(signaling_thread());
6281 usage_event_accumulator_ |= static_cast<int>(event);
6282}
6283
6284void PeerConnection::ReportUsagePattern() const {
6285 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006286 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6287 usage_event_accumulator_,
6288 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006289 const int bad_bits =
6290 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6291 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6292 const int good_bits =
6293 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6294 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6295 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6296 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6297 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006298 // If called after close(), we can't report, because observer may have
6299 // been deallocated, and therefore pointer is null. Write to log instead.
6300 if (observer_) {
6301 Observer()->OnInterestingUsage(usage_event_accumulator_);
6302 } else {
6303 RTC_LOG(LS_INFO) << "Interesting usage signature "
6304 << usage_event_accumulator_
6305 << " observed after observer shutdown";
6306 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006307 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006308}
6309
Steve Anton0ffaaa22018-02-23 10:31:30 -08006310void PeerConnection::ReportNegotiatedSdpSemantics(
6311 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006312 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006313 switch (answer.description()->msid_signaling()) {
6314 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006315 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006316 break;
6317 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006318 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006319 break;
6320 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006321 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006322 break;
6323 case cricket::kMsidSignalingMediaSection |
6324 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006325 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006326 break;
6327 default:
6328 RTC_NOTREACHED();
6329 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006330 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6331 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006332}
6333
Steve Anton75737c02017-11-06 10:37:17 -08006334// We need to check the local/remote description for the Transport instead of
6335// the session, because a new Transport added during renegotiation may have
6336// them unset while the session has them set from the previous negotiation.
6337// Not doing so may trigger the auto generation of transport description and
6338// mess up DTLS identity information, ICE credential, etc.
6339bool PeerConnection::ReadyToUseRemoteCandidate(
6340 const IceCandidateInterface* candidate,
6341 const SessionDescriptionInterface* remote_desc,
6342 bool* valid) {
6343 *valid = true;
6344
6345 const SessionDescriptionInterface* current_remote_desc =
6346 remote_desc ? remote_desc : remote_description();
6347
6348 if (!current_remote_desc) {
6349 return false;
6350 }
6351
6352 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6353 size_t remote_content_size =
6354 current_remote_desc->description()->contents().size();
6355 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006356 RTC_LOG(LS_ERROR)
6357 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6358 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006359
6360 *valid = false;
6361 return false;
6362 }
6363
6364 cricket::ContentInfo content =
6365 current_remote_desc->description()->contents()[mediacontent_index];
6366
6367 const std::string transport_name = GetTransportName(content.name);
6368 if (transport_name.empty()) {
6369 return false;
6370 }
Zhi Huange830e682018-03-30 10:48:35 -07006371 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006372}
6373
6374bool PeerConnection::SrtpRequired() const {
6375 return dtls_enabled_ ||
6376 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6377}
6378
6379void PeerConnection::OnTransportControllerGatheringState(
6380 cricket::IceGatheringState state) {
6381 RTC_DCHECK(signaling_thread()->IsCurrent());
6382 if (state == cricket::kIceGatheringGathering) {
6383 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6384 } else if (state == cricket::kIceGatheringComplete) {
6385 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6386 }
6387}
6388
6389void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006390 std::map<std::string, std::set<cricket::MediaType>>
6391 media_types_by_transport_name;
6392 for (auto transceiver : transceivers_) {
6393 if (transceiver->internal()->channel()) {
6394 const std::string& transport_name =
6395 transceiver->internal()->channel()->transport_name();
6396 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006397 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006398 }
Steve Anton75737c02017-11-06 10:37:17 -08006399 }
6400 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006401 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6402 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006403 }
Zhi Huange830e682018-03-30 10:48:35 -07006404
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006405 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006406 if (transport_name) {
6407 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006408 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006409 }
Zhi Huange830e682018-03-30 10:48:35 -07006410
Steve Antonc7b964c2018-02-01 14:39:45 -08006411 for (const auto& entry : media_types_by_transport_name) {
6412 const std::string& transport_name = entry.first;
6413 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006414 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006415 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006416 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006417 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006418 }
6419 }
6420}
6421// Walk through the ConnectionInfos to gather best connection usage
6422// for IPv4 and IPv6.
6423void PeerConnection::ReportBestConnectionState(
6424 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006425 for (const cricket::TransportChannelStats& channel_stats :
6426 stats.channel_stats) {
6427 for (const cricket::ConnectionInfo& connection_info :
6428 channel_stats.connection_infos) {
6429 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006430 continue;
6431 }
6432
Steve Antonc7b964c2018-02-01 14:39:45 -08006433 const cricket::Candidate& local = connection_info.local_candidate;
6434 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006435
6436 // Increment the counter for IceCandidatePairType.
6437 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6438 (local.type() == RELAY_PORT_TYPE &&
6439 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006440 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6441 GetIceCandidatePairCounter(local, remote),
6442 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006443 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6445 GetIceCandidatePairCounter(local, remote),
6446 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006447 } else {
6448 RTC_CHECK(0);
6449 }
Steve Anton75737c02017-11-06 10:37:17 -08006450
6451 // Increment the counter for IP type.
6452 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006453 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6454 kBestConnections_IPv4,
6455 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006456 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006457 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6458 kBestConnections_IPv6,
6459 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006460 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006461 RTC_CHECK(!local.address().hostname().empty() &&
6462 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006463 }
6464
6465 return;
6466 }
6467 }
6468}
6469
6470void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006471 const cricket::TransportStats& stats,
6472 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006473 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6474 return;
6475 }
6476
6477 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6478 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6479 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6480 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6481 return;
6482 }
6483
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006484 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6485 for (cricket::MediaType media_type : media_types) {
6486 switch (media_type) {
6487 case cricket::MEDIA_TYPE_AUDIO:
6488 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6489 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6490 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6491 break;
6492 case cricket::MEDIA_TYPE_VIDEO:
6493 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6494 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6495 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6496 break;
6497 case cricket::MEDIA_TYPE_DATA:
6498 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6499 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6500 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6501 break;
6502 default:
6503 RTC_NOTREACHED();
6504 continue;
6505 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006506 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006507 }
6508
6509 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6510 for (cricket::MediaType media_type : media_types) {
6511 switch (media_type) {
6512 case cricket::MEDIA_TYPE_AUDIO:
6513 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6514 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6515 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6516 break;
6517 case cricket::MEDIA_TYPE_VIDEO:
6518 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6519 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6520 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6521 break;
6522 case cricket::MEDIA_TYPE_DATA:
6523 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6524 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6525 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6526 break;
6527 default:
6528 RTC_NOTREACHED();
6529 continue;
6530 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006531 }
Steve Anton75737c02017-11-06 10:37:17 -08006532 }
6533}
6534
6535void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6536 RTC_DCHECK(worker_thread()->IsCurrent());
6537 RTC_DCHECK(call_);
6538 call_->OnSentPacket(sent_packet);
6539}
6540
6541const std::string PeerConnection::GetTransportName(
6542 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006543 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006544 if (channel) {
6545 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006546 }
Steve Anton6fec8802017-12-04 10:37:29 -08006547 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006548 RTC_DCHECK(sctp_mid_);
6549 if (content_name == *sctp_mid_) {
6550 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006551 }
6552 }
6553 // Return an empty string if failed to retrieve the transport name.
6554 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006555}
6556
Steve Anton6fec8802017-12-04 10:37:29 -08006557void PeerConnection::DestroyTransceiverChannel(
6558 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6559 transceiver) {
6560 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006561
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006562 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006563 if (channel) {
6564 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006565 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006566 }
6567}
6568
6569void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006570 if (rtp_data_channel_) {
6571 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006572 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006573 rtp_data_channel_ = nullptr;
6574 }
6575
6576 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6577 // grab a reference to this PeerConnection. If this is called from the
6578 // PeerConnection destructor, the RefCountedObject vtable will have already
6579 // been destroyed (since it is a subclass of PeerConnection) and using
6580 // rtc::Bind will cause "Pure virtual function called" error to appear.
6581
6582 if (sctp_transport_) {
6583 OnDataChannelDestroyed();
6584 network_thread()->Invoke<void>(RTC_FROM_HERE,
6585 [this] { DestroySctpTransport_n(); });
6586 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006587
6588 if (media_transport_) {
6589 OnDataChannelDestroyed();
6590 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6591 RTC_DCHECK_RUN_ON(network_thread());
6592 TeardownMediaTransportForDataChannels_n();
6593 });
6594 }
Steve Anton6fec8802017-12-04 10:37:29 -08006595}
6596
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006597void PeerConnection::DestroyChannelInterface(
6598 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006599 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006600 switch (channel->media_type()) {
6601 case cricket::MEDIA_TYPE_AUDIO:
6602 channel_manager()->DestroyVoiceChannel(
6603 static_cast<cricket::VoiceChannel*>(channel));
6604 break;
6605 case cricket::MEDIA_TYPE_VIDEO:
6606 channel_manager()->DestroyVideoChannel(
6607 static_cast<cricket::VideoChannel*>(channel));
6608 break;
6609 case cricket::MEDIA_TYPE_DATA:
6610 channel_manager()->DestroyRtpDataChannel(
6611 static_cast<cricket::RtpDataChannel*>(channel));
6612 break;
6613 default:
6614 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6615 break;
6616 }
Zhi Huange830e682018-03-30 10:48:35 -07006617}
Steve Anton6fec8802017-12-04 10:37:29 -08006618
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006619bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006620 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006621 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006622 cricket::DtlsTransportInternal* dtls_transport,
6623 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006624 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006625 auto base_channel = GetChannel(mid);
6626 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006627 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006628 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006629 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006630 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006631 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006632
6633 call_->MediaTransportChange(media_transport);
6634
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006635 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006636}
6637
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006638PeerConnectionObserver* PeerConnection::Observer() const {
6639 // In earlier production code, the pointer was not cleared on close,
6640 // which might have led to undefined behavior if the observer was not
6641 // deallocated, or strange crashes if it was.
6642 // We use CHECK in order to catch such behavior if it exists.
6643 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6644 RTC_CHECK(observer_);
6645 return observer_;
6646}
6647
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006648CryptoOptions PeerConnection::GetCryptoOptions() {
6649 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6650 // after it has been removed.
6651 return configuration_.crypto_options.has_value()
6652 ? *configuration_.crypto_options
6653 : factory_->options().crypto_options;
6654}
6655
Harald Alvestrand89061872018-01-02 14:08:34 +01006656void PeerConnection::ClearStatsCache() {
6657 if (stats_collector_) {
6658 stats_collector_->ClearCachedStatsReport();
6659 }
6660}
6661
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006662void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006663 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6664 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006665}
6666
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006667} // namespace webrtc